Completed
Branch FET-9222-rest-api-writes (a8f519)
by
unknown
76:34 queued 64:09
created
core/EE_Dependency_Map.core.php 1 patch
Indentation   +665 added lines, -665 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\services\loaders\LoaderInterface;
5 5
 
6 6
 if (! defined('EVENT_ESPRESSO_VERSION')) {
7
-    exit('No direct script access allowed');
7
+	exit('No direct script access allowed');
8 8
 }
9 9
 
10 10
 
@@ -22,670 +22,670 @@  discard block
 block discarded – undo
22 22
 {
23 23
 
24 24
 
25
-    /**
26
-     * This means that the requested class dependency is not present in the dependency map
27
-     */
28
-    const not_registered = 0;
29
-
30
-
31
-    /**
32
-     * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
33
-     */
34
-    const load_new_object = 1;
35
-
36
-    /**
37
-     * This instructs class loaders to return a previously instantiated and cached object for the requested class.
38
-     * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
39
-     */
40
-    const load_from_cache = 2;
41
-
42
-    /**
43
-     * @type EE_Dependency_Map $_instance
44
-     */
45
-    protected static $_instance;
46
-
47
-    /**
48
-     * @type EE_Request $request
49
-     */
50
-    protected $_request;
51
-
52
-    /**
53
-     * @type EE_Response $response
54
-     */
55
-    protected $_response;
56
-
57
-    /**
58
-     * @type LoaderInterface $loader
59
-     */
60
-    protected $loader;
61
-
62
-    /**
63
-     * @type array $_dependency_map
64
-     */
65
-    protected $_dependency_map = array();
66
-
67
-    /**
68
-     * @type array $_class_loaders
69
-     */
70
-    protected $_class_loaders = array();
71
-
72
-    /**
73
-     * @type array $_aliases
74
-     */
75
-    protected $_aliases = array();
76
-
77
-
78
-
79
-    /**
80
-     * EE_Dependency_Map constructor.
81
-     *
82
-     * @param EE_Request  $request
83
-     * @param EE_Response $response
84
-     */
85
-    protected function __construct(EE_Request $request, EE_Response $response)
86
-    {
87
-        $this->_request = $request;
88
-        $this->_response = $response;
89
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
90
-        do_action('EE_Dependency_Map____construct');
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     * @throws InvalidDataTypeException
97
-     * @throws InvalidInterfaceException
98
-     * @throws InvalidArgumentException
99
-     */
100
-    public function initialize()
101
-    {
102
-        $this->_register_core_dependencies();
103
-        $this->_register_core_class_loaders();
104
-        $this->_register_core_aliases();
105
-    }
106
-
107
-
108
-
109
-    /**
110
-     * @singleton method used to instantiate class object
111
-     * @access    public
112
-     * @param EE_Request  $request
113
-     * @param EE_Response $response
114
-     * @return EE_Dependency_Map
115
-     */
116
-    public static function instance(EE_Request $request = null, EE_Response $response = null)
117
-    {
118
-        // check if class object is instantiated, and instantiated properly
119
-        if (! self::$_instance instanceof EE_Dependency_Map) {
120
-            self::$_instance = new EE_Dependency_Map($request, $response);
121
-        }
122
-        return self::$_instance;
123
-    }
124
-
125
-
126
-
127
-    /**
128
-     * @param LoaderInterface $loader
129
-     */
130
-    public function setLoader(LoaderInterface $loader)
131
-    {
132
-        $this->loader = $loader;
133
-    }
134
-
135
-
136
-
137
-    /**
138
-     * @param string $class
139
-     * @param array  $dependencies
140
-     * @return boolean
141
-     */
142
-    public static function register_dependencies($class, $dependencies)
143
-    {
144
-        if (! isset(self::$_instance->_dependency_map[$class])) {
145
-            // we need to make sure that any aliases used when registering a dependency
146
-            // get resolved to the correct class name
147
-            foreach ((array)$dependencies as $dependency => $load_source) {
148
-                $alias = self::$_instance->get_alias($dependency);
149
-                unset($dependencies[$dependency]);
150
-                $dependencies[$alias] = $load_source;
151
-            }
152
-            self::$_instance->_dependency_map[$class] = (array)$dependencies;
153
-            return true;
154
-        }
155
-        return false;
156
-    }
157
-
158
-
159
-
160
-    /**
161
-     * @param string $class_name
162
-     * @param string $loader
163
-     * @return bool
164
-     * @throws EE_Error
165
-     */
166
-    public static function register_class_loader($class_name, $loader = 'load_core')
167
-    {
168
-        // check that loader is callable or method starts with "load_" and exists in EE_Registry
169
-        if (
170
-            ! is_callable($loader)
171
-            && (
172
-                strpos($loader, 'load_') !== 0
173
-                || ! method_exists('EE_Registry', $loader)
174
-            )
175
-        ) {
176
-            throw new EE_Error(
177
-                sprintf(
178
-                    esc_html__('"%1$s" is not a valid loader method on EE_Registry.', 'event_espresso'),
179
-                    $loader
180
-                )
181
-            );
182
-        }
183
-        $class_name = self::$_instance->get_alias($class_name);
184
-        if (! isset(self::$_instance->_class_loaders[$class_name])) {
185
-            self::$_instance->_class_loaders[$class_name] = $loader;
186
-            return true;
187
-        }
188
-        return false;
189
-    }
190
-
191
-
192
-
193
-    /**
194
-     * @return array
195
-     */
196
-    public function dependency_map()
197
-    {
198
-        return $this->_dependency_map;
199
-    }
200
-
201
-
202
-
203
-    /**
204
-     * returns TRUE if dependency map contains a listing for the provided class name
205
-     *
206
-     * @param string $class_name
207
-     * @return boolean
208
-     */
209
-    public function has($class_name = '')
210
-    {
211
-        return isset($this->_dependency_map[$class_name]) ? true : false;
212
-    }
213
-
214
-
215
-
216
-    /**
217
-     * returns TRUE if dependency map contains a listing for the provided class name AND dependency
218
-     *
219
-     * @param string $class_name
220
-     * @param string $dependency
221
-     * @return bool
222
-     */
223
-    public function has_dependency_for_class($class_name = '', $dependency = '')
224
-    {
225
-        $dependency = $this->get_alias($dependency);
226
-        return isset($this->_dependency_map[$class_name], $this->_dependency_map[$class_name][$dependency])
227
-            ? true
228
-            : false;
229
-    }
230
-
231
-
232
-
233
-    /**
234
-     * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
235
-     *
236
-     * @param string $class_name
237
-     * @param string $dependency
238
-     * @return int
239
-     */
240
-    public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
241
-    {
242
-        $dependency = $this->get_alias($dependency);
243
-        return $this->has_dependency_for_class($class_name, $dependency)
244
-            ? $this->_dependency_map[$class_name][$dependency]
245
-            : EE_Dependency_Map::not_registered;
246
-    }
247
-
248
-
249
-
250
-    /**
251
-     * @param string $class_name
252
-     * @return string | Closure
253
-     */
254
-    public function class_loader($class_name)
255
-    {
256
-        $class_name = $this->get_alias($class_name);
257
-        return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
258
-    }
259
-
260
-
261
-
262
-    /**
263
-     * @return array
264
-     */
265
-    public function class_loaders()
266
-    {
267
-        return $this->_class_loaders;
268
-    }
269
-
270
-
271
-
272
-    /**
273
-     * adds an alias for a classname
274
-     *
275
-     * @param string $class_name the class name that should be used (concrete class to replace interface)
276
-     * @param string $alias      the class name that would be type hinted for (abstract parent or interface)
277
-     * @param string $for_class  the class that has the dependency (is type hinting for the interface)
278
-     */
279
-    public function add_alias($class_name, $alias, $for_class = '')
280
-    {
281
-        if ($for_class !== '') {
282
-            if (! isset($this->_aliases[$for_class])) {
283
-                $this->_aliases[$for_class] = array();
284
-            }
285
-            $this->_aliases[$for_class][$class_name] = $alias;
286
-        }
287
-        $this->_aliases[$class_name] = $alias;
288
-    }
289
-
290
-
291
-
292
-    /**
293
-     * returns TRUE if the provided class name has an alias
294
-     *
295
-     * @param string $class_name
296
-     * @param string $for_class
297
-     * @return bool
298
-     */
299
-    public function has_alias($class_name = '', $for_class = '')
300
-    {
301
-        return isset($this->_aliases[$for_class], $this->_aliases[$for_class][$class_name])
302
-               || (
303
-                   isset($this->_aliases[$class_name])
304
-                   && ! is_array($this->_aliases[$class_name])
305
-               );
306
-    }
307
-
308
-
309
-
310
-    /**
311
-     * returns alias for class name if one exists, otherwise returns the original classname
312
-     * functions recursively, so that multiple aliases can be used to drill down to a classname
313
-     *  for example:
314
-     *      if the following two entries were added to the _aliases array:
315
-     *          array(
316
-     *              'interface_alias'           => 'some\namespace\interface'
317
-     *              'some\namespace\interface'  => 'some\namespace\classname'
318
-     *          )
319
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
320
-     *      to load an instance of 'some\namespace\classname'
321
-     *
322
-     * @param string $class_name
323
-     * @param string $for_class
324
-     * @return string
325
-     */
326
-    public function get_alias($class_name = '', $for_class = '')
327
-    {
328
-        if (! $this->has_alias($class_name, $for_class)) {
329
-            return $class_name;
330
-        }
331
-        if ($for_class !== '') {
332
-            return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
333
-        }
334
-        return $this->get_alias($this->_aliases[$class_name]);
335
-    }
336
-
337
-
338
-
339
-    /**
340
-     * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
341
-     * if one exists, or whether a new object should be generated every time the requested class is loaded.
342
-     * This is done by using the following class constants:
343
-     *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
344
-     *        EE_Dependency_Map::load_new_object - generates a new object every time
345
-     */
346
-    protected function _register_core_dependencies()
347
-    {
348
-        $this->_dependency_map = array(
349
-            'EE_Request_Handler'                                                                                          => array(
350
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
351
-            ),
352
-            'EE_System'                                                                                                   => array(
353
-                'EE_Registry' => EE_Dependency_Map::load_from_cache,
354
-            ),
355
-            'EE_Session'                                                                                                  => array(
356
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
357
-                'EE_Encryption'                                           => EE_Dependency_Map::load_from_cache,
358
-            ),
359
-            'EE_Cart'                                                                                                     => array(
360
-                'EE_Session' => EE_Dependency_Map::load_from_cache,
361
-            ),
362
-            'EE_Front_Controller'                                                                                         => array(
363
-                'EE_Registry'              => EE_Dependency_Map::load_from_cache,
364
-                'EE_Request_Handler'       => EE_Dependency_Map::load_from_cache,
365
-                'EE_Module_Request_Router' => EE_Dependency_Map::load_from_cache,
366
-            ),
367
-            'EE_Messenger_Collection_Loader'                                                                              => array(
368
-                'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
369
-            ),
370
-            'EE_Message_Type_Collection_Loader'                                                                           => array(
371
-                'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
372
-            ),
373
-            'EE_Message_Resource_Manager'                                                                                 => array(
374
-                'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
375
-                'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
376
-                'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
377
-            ),
378
-            'EE_Message_Factory'                                                                                          => array(
379
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
380
-            ),
381
-            'EE_messages'                                                                                                 => array(
382
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
383
-            ),
384
-            'EE_Messages_Generator'                                                                                       => array(
385
-                'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
386
-                'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
387
-                'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
388
-                'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
389
-            ),
390
-            'EE_Messages_Processor'                                                                                       => array(
391
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
392
-            ),
393
-            'EE_Messages_Queue'                                                                                           => array(
394
-                'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
395
-            ),
396
-            'EE_Messages_Template_Defaults'                                                                               => array(
397
-                'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
398
-                'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
399
-            ),
400
-            'EE_Message_To_Generate_From_Request'                                                                         => array(
401
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
402
-                'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
403
-            ),
404
-            'EventEspresso\core\services\commands\CommandBus'                                                             => array(
405
-                'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
406
-            ),
407
-            'EventEspresso\services\commands\CommandHandler'                                                              => array(
408
-                'EE_Registry'         => EE_Dependency_Map::load_from_cache,
409
-                'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
410
-            ),
411
-            'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => array(
412
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
413
-            ),
414
-            'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => array(
415
-                'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
416
-                'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
417
-            ),
418
-            'EventEspresso\core\services\commands\CommandFactory'                                                         => array(
419
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
420
-            ),
421
-            'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => array(
422
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
423
-            ),
424
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => array(
425
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
426
-            ),
427
-            'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => array(
428
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
429
-            ),
430
-            'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => array(
431
-                'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
432
-            ),
433
-            'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => array(
434
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
435
-            ),
436
-            'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => array(
437
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
438
-            ),
439
-            'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => array(
440
-                'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
441
-            ),
442
-            'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => array(
443
-                'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
444
-            ),
445
-            'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => array(
446
-                'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
447
-            ),
448
-            'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => array(
449
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
450
-            ),
451
-            'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => array(
452
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
453
-            ),
454
-            'EventEspresso\core\services\database\TableManager'                                                           => array(
455
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
456
-            ),
457
-            'EE_Data_Migration_Class_Base'                                                                                => array(
458
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
459
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
460
-            ),
461
-            'EE_DMS_Core_4_1_0'                                                                                           => array(
462
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
463
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
464
-            ),
465
-            'EE_DMS_Core_4_2_0'                                                                                           => array(
466
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
467
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
468
-            ),
469
-            'EE_DMS_Core_4_3_0'                                                                                           => array(
470
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
471
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
472
-            ),
473
-            'EE_DMS_Core_4_4_0'                                                                                           => array(
474
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
475
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
476
-            ),
477
-            'EE_DMS_Core_4_5_0'                                                                                           => array(
478
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
479
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
480
-            ),
481
-            'EE_DMS_Core_4_6_0'                                                                                           => array(
482
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
483
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
484
-            ),
485
-            'EE_DMS_Core_4_7_0'                                                                                           => array(
486
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
487
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
488
-            ),
489
-            'EE_DMS_Core_4_8_0'                                                                                           => array(
490
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
491
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
492
-            ),
493
-            'EE_DMS_Core_4_9_0'                                                                                           => array(
494
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
495
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
496
-            ),
497
-            'EventEspresso\core\services\assets\Registry'                                                                 => array(
498
-                'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
499
-                'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
500
-            ),
501
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                             => array(
502
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
503
-            ),
504
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                              => array(
505
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
506
-            ),
507
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                        => array(
508
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
509
-            ),
510
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                => array(
511
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
512
-            ),
513
-            'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                              => array(
514
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
515
-            ),
516
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                        => array(
517
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
518
-            ),
519
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                               => array(
520
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
521
-            ),
522
-            'EventEspresso\core\services\cache\BasicCacheManager'                                                         => array(
523
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
524
-            ),
525
-            'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                   => array(
526
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
527
-            ),
528
-            'EventEspresso\core\services\validation\EmailValidationService' => array(
529
-                'EE_Registration_Config'                                  => EE_Dependency_Map::load_from_cache,
530
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
531
-            ),
532
-            'EEM_Attendee' => array(
533
-                null,
534
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
535
-            ),
536
-            'EEM_WP_User' => array(
537
-                null,
538
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
539
-            ),
540
-        );
541
-    }
542
-
543
-
544
-
545
-    /**
546
-     * Registers how core classes are loaded.
547
-     * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
548
-     *        'EE_Request_Handler' => 'load_core'
549
-     *        'EE_Messages_Queue'  => 'load_lib'
550
-     *        'EEH_Debug_Tools'    => 'load_helper'
551
-     * or, if greater control is required, by providing a custom closure. For example:
552
-     *        'Some_Class' => function () {
553
-     *            return new Some_Class();
554
-     *        },
555
-     * This is required for instantiating dependencies
556
-     * where an interface has been type hinted in a class constructor. For example:
557
-     *        'Required_Interface' => function () {
558
-     *            return new A_Class_That_Implements_Required_Interface();
559
-     *        },
560
-     */
561
-    protected function _register_core_class_loaders()
562
-    {
563
-        //for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
564
-        //be used in a closure.
565
-        $request = &$this->_request;
566
-        $response = &$this->_response;
567
-        $loader = &$this->loader;
568
-        $this->_class_loaders = array(
569
-            //load_core
570
-            'EE_Capabilities'                      => 'load_core',
571
-            'EE_Encryption'                        => 'load_core',
572
-            'EE_Front_Controller'                  => 'load_core',
573
-            'EE_Module_Request_Router'             => 'load_core',
574
-            'EE_Registry'                          => 'load_core',
575
-            'EE_Request'                           => function () use (&$request) {
576
-                return $request;
577
-            },
578
-            'EE_Response'                          => function () use (&$response) {
579
-                return $response;
580
-            },
581
-            'EE_Request_Handler'                   => 'load_core',
582
-            'EE_Session'                           => 'load_core',
583
-            'EE_System'                            => 'load_core',
584
-            //load_lib
585
-            'EE_Message_Resource_Manager'          => 'load_lib',
586
-            'EE_Message_Type_Collection'           => 'load_lib',
587
-            'EE_Message_Type_Collection_Loader'    => 'load_lib',
588
-            'EE_Messenger_Collection'              => 'load_lib',
589
-            'EE_Messenger_Collection_Loader'       => 'load_lib',
590
-            'EE_Messages_Processor'                => 'load_lib',
591
-            'EE_Message_Repository'                => 'load_lib',
592
-            'EE_Messages_Queue'                    => 'load_lib',
593
-            'EE_Messages_Data_Handler_Collection'  => 'load_lib',
594
-            'EE_Message_Template_Group_Collection' => 'load_lib',
595
-            'EE_Messages_Generator'                => function () {
596
-                return EE_Registry::instance()->load_lib(
597
-                    'Messages_Generator',
598
-                    array(),
599
-                    false,
600
-                    false
601
-                );
602
-            },
603
-            'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
604
-                return EE_Registry::instance()->load_lib(
605
-                    'Messages_Template_Defaults',
606
-                    $arguments,
607
-                    false,
608
-                    false
609
-                );
610
-            },
611
-            //load_model
612
-            'EEM_Message_Template_Group'           => 'load_model',
613
-            'EEM_Message_Template'                 => 'load_model',
614
-            //load_helper
615
-            'EEH_Parse_Shortcodes'                 => function () {
616
-                if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
617
-                    return new EEH_Parse_Shortcodes();
618
-                }
619
-                return null;
620
-            },
621
-            'EE_Template_Config'                   => function () {
622
-                return EE_Config::instance()->template_settings;
623
-            },
624
-            'EE_Currency_Config'                   => function () {
625
-                return EE_Config::instance()->currency;
626
-            },
627
-            'EE_Registration_Config'                   => function () {
628
-                return EE_Config::instance()->registration;
629
-            },
630
-            'EventEspresso\core\services\loaders\Loader' => function () use (&$loader) {
631
-                return $loader;
632
-            },
633
-        );
634
-    }
635
-
636
-
637
-
638
-    /**
639
-     * can be used for supplying alternate names for classes,
640
-     * or for connecting interface names to instantiable classes
641
-     */
642
-    protected function _register_core_aliases()
643
-    {
644
-        $this->_aliases = array(
645
-            'CommandBusInterface'                                                           => 'EventEspresso\core\services\commands\CommandBusInterface',
646
-            'EventEspresso\core\services\commands\CommandBusInterface'                      => 'EventEspresso\core\services\commands\CommandBus',
647
-            'CommandHandlerManagerInterface'                                                => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
648
-            'EventEspresso\core\services\commands\CommandHandlerManagerInterface'           => 'EventEspresso\core\services\commands\CommandHandlerManager',
649
-            'CapChecker'                                                                    => 'EventEspresso\core\services\commands\middleware\CapChecker',
650
-            'AddActionHook'                                                                 => 'EventEspresso\core\services\commands\middleware\AddActionHook',
651
-            'CapabilitiesChecker'                                                           => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
652
-            'CapabilitiesCheckerInterface'                                                  => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
653
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface'  => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
654
-            'CreateRegistrationService'                                                     => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
655
-            'CreateRegCodeCommandHandler'                                                   => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
656
-            'CreateRegUrlLinkCommandHandler'                                                => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
657
-            'CreateRegistrationCommandHandler'                                              => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
658
-            'CopyRegistrationDetailsCommandHandler'                                         => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
659
-            'CopyRegistrationPaymentsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
660
-            'CancelRegistrationAndTicketLineItemCommandHandler'                             => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
661
-            'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                     => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
662
-            'CreateTicketLineItemCommandHandler'                                            => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
663
-            'TableManager'                                                                  => 'EventEspresso\core\services\database\TableManager',
664
-            'TableAnalysis'                                                                 => 'EventEspresso\core\services\database\TableAnalysis',
665
-            'EspressoShortcode'                                                             => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
666
-            'ShortcodeInterface'                                                            => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
667
-            'EventEspresso\core\services\shortcodes\ShortcodeInterface'                     => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
668
-            'EventEspresso\core\services\cache\CacheStorageInterface'                       => 'EventEspresso\core\services\cache\TransientCacheStorage',
669
-            'LoaderInterface'                                                               => 'EventEspresso\core\services\loaders\LoaderInterface',
670
-            'EventEspresso\core\services\loaders\LoaderInterface'                           => 'EventEspresso\core\services\loaders\Loader',
671
-            'CommandFactoryInterface'                                                       => 'EventEspresso\core\services\commands\CommandFactoryInterface',
672
-            'EventEspresso\core\services\commands\CommandFactoryInterface'                  => 'EventEspresso\core\services\commands\CommandFactory',
673
-            'EmailValidatorInterface'                                                       => 'EventEspresso\core\domain\services\validation\EmailValidatorInterface',
674
-            'EventEspresso\core\domain\services\validation\EmailValidatorInterface'         => 'EventEspresso\core\services\validation\EmailValidationService',
675
-        );
676
-    }
677
-
678
-
679
-
680
-    /**
681
-     * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
682
-     * request Primarily used by unit tests.
683
-     */
684
-    public function reset()
685
-    {
686
-        $this->_register_core_class_loaders();
687
-        $this->_register_core_dependencies();
688
-    }
25
+	/**
26
+	 * This means that the requested class dependency is not present in the dependency map
27
+	 */
28
+	const not_registered = 0;
29
+
30
+
31
+	/**
32
+	 * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
33
+	 */
34
+	const load_new_object = 1;
35
+
36
+	/**
37
+	 * This instructs class loaders to return a previously instantiated and cached object for the requested class.
38
+	 * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
39
+	 */
40
+	const load_from_cache = 2;
41
+
42
+	/**
43
+	 * @type EE_Dependency_Map $_instance
44
+	 */
45
+	protected static $_instance;
46
+
47
+	/**
48
+	 * @type EE_Request $request
49
+	 */
50
+	protected $_request;
51
+
52
+	/**
53
+	 * @type EE_Response $response
54
+	 */
55
+	protected $_response;
56
+
57
+	/**
58
+	 * @type LoaderInterface $loader
59
+	 */
60
+	protected $loader;
61
+
62
+	/**
63
+	 * @type array $_dependency_map
64
+	 */
65
+	protected $_dependency_map = array();
66
+
67
+	/**
68
+	 * @type array $_class_loaders
69
+	 */
70
+	protected $_class_loaders = array();
71
+
72
+	/**
73
+	 * @type array $_aliases
74
+	 */
75
+	protected $_aliases = array();
76
+
77
+
78
+
79
+	/**
80
+	 * EE_Dependency_Map constructor.
81
+	 *
82
+	 * @param EE_Request  $request
83
+	 * @param EE_Response $response
84
+	 */
85
+	protected function __construct(EE_Request $request, EE_Response $response)
86
+	{
87
+		$this->_request = $request;
88
+		$this->_response = $response;
89
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
90
+		do_action('EE_Dependency_Map____construct');
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 * @throws InvalidDataTypeException
97
+	 * @throws InvalidInterfaceException
98
+	 * @throws InvalidArgumentException
99
+	 */
100
+	public function initialize()
101
+	{
102
+		$this->_register_core_dependencies();
103
+		$this->_register_core_class_loaders();
104
+		$this->_register_core_aliases();
105
+	}
106
+
107
+
108
+
109
+	/**
110
+	 * @singleton method used to instantiate class object
111
+	 * @access    public
112
+	 * @param EE_Request  $request
113
+	 * @param EE_Response $response
114
+	 * @return EE_Dependency_Map
115
+	 */
116
+	public static function instance(EE_Request $request = null, EE_Response $response = null)
117
+	{
118
+		// check if class object is instantiated, and instantiated properly
119
+		if (! self::$_instance instanceof EE_Dependency_Map) {
120
+			self::$_instance = new EE_Dependency_Map($request, $response);
121
+		}
122
+		return self::$_instance;
123
+	}
124
+
125
+
126
+
127
+	/**
128
+	 * @param LoaderInterface $loader
129
+	 */
130
+	public function setLoader(LoaderInterface $loader)
131
+	{
132
+		$this->loader = $loader;
133
+	}
134
+
135
+
136
+
137
+	/**
138
+	 * @param string $class
139
+	 * @param array  $dependencies
140
+	 * @return boolean
141
+	 */
142
+	public static function register_dependencies($class, $dependencies)
143
+	{
144
+		if (! isset(self::$_instance->_dependency_map[$class])) {
145
+			// we need to make sure that any aliases used when registering a dependency
146
+			// get resolved to the correct class name
147
+			foreach ((array)$dependencies as $dependency => $load_source) {
148
+				$alias = self::$_instance->get_alias($dependency);
149
+				unset($dependencies[$dependency]);
150
+				$dependencies[$alias] = $load_source;
151
+			}
152
+			self::$_instance->_dependency_map[$class] = (array)$dependencies;
153
+			return true;
154
+		}
155
+		return false;
156
+	}
157
+
158
+
159
+
160
+	/**
161
+	 * @param string $class_name
162
+	 * @param string $loader
163
+	 * @return bool
164
+	 * @throws EE_Error
165
+	 */
166
+	public static function register_class_loader($class_name, $loader = 'load_core')
167
+	{
168
+		// check that loader is callable or method starts with "load_" and exists in EE_Registry
169
+		if (
170
+			! is_callable($loader)
171
+			&& (
172
+				strpos($loader, 'load_') !== 0
173
+				|| ! method_exists('EE_Registry', $loader)
174
+			)
175
+		) {
176
+			throw new EE_Error(
177
+				sprintf(
178
+					esc_html__('"%1$s" is not a valid loader method on EE_Registry.', 'event_espresso'),
179
+					$loader
180
+				)
181
+			);
182
+		}
183
+		$class_name = self::$_instance->get_alias($class_name);
184
+		if (! isset(self::$_instance->_class_loaders[$class_name])) {
185
+			self::$_instance->_class_loaders[$class_name] = $loader;
186
+			return true;
187
+		}
188
+		return false;
189
+	}
190
+
191
+
192
+
193
+	/**
194
+	 * @return array
195
+	 */
196
+	public function dependency_map()
197
+	{
198
+		return $this->_dependency_map;
199
+	}
200
+
201
+
202
+
203
+	/**
204
+	 * returns TRUE if dependency map contains a listing for the provided class name
205
+	 *
206
+	 * @param string $class_name
207
+	 * @return boolean
208
+	 */
209
+	public function has($class_name = '')
210
+	{
211
+		return isset($this->_dependency_map[$class_name]) ? true : false;
212
+	}
213
+
214
+
215
+
216
+	/**
217
+	 * returns TRUE if dependency map contains a listing for the provided class name AND dependency
218
+	 *
219
+	 * @param string $class_name
220
+	 * @param string $dependency
221
+	 * @return bool
222
+	 */
223
+	public function has_dependency_for_class($class_name = '', $dependency = '')
224
+	{
225
+		$dependency = $this->get_alias($dependency);
226
+		return isset($this->_dependency_map[$class_name], $this->_dependency_map[$class_name][$dependency])
227
+			? true
228
+			: false;
229
+	}
230
+
231
+
232
+
233
+	/**
234
+	 * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
235
+	 *
236
+	 * @param string $class_name
237
+	 * @param string $dependency
238
+	 * @return int
239
+	 */
240
+	public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
241
+	{
242
+		$dependency = $this->get_alias($dependency);
243
+		return $this->has_dependency_for_class($class_name, $dependency)
244
+			? $this->_dependency_map[$class_name][$dependency]
245
+			: EE_Dependency_Map::not_registered;
246
+	}
247
+
248
+
249
+
250
+	/**
251
+	 * @param string $class_name
252
+	 * @return string | Closure
253
+	 */
254
+	public function class_loader($class_name)
255
+	{
256
+		$class_name = $this->get_alias($class_name);
257
+		return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
258
+	}
259
+
260
+
261
+
262
+	/**
263
+	 * @return array
264
+	 */
265
+	public function class_loaders()
266
+	{
267
+		return $this->_class_loaders;
268
+	}
269
+
270
+
271
+
272
+	/**
273
+	 * adds an alias for a classname
274
+	 *
275
+	 * @param string $class_name the class name that should be used (concrete class to replace interface)
276
+	 * @param string $alias      the class name that would be type hinted for (abstract parent or interface)
277
+	 * @param string $for_class  the class that has the dependency (is type hinting for the interface)
278
+	 */
279
+	public function add_alias($class_name, $alias, $for_class = '')
280
+	{
281
+		if ($for_class !== '') {
282
+			if (! isset($this->_aliases[$for_class])) {
283
+				$this->_aliases[$for_class] = array();
284
+			}
285
+			$this->_aliases[$for_class][$class_name] = $alias;
286
+		}
287
+		$this->_aliases[$class_name] = $alias;
288
+	}
289
+
290
+
291
+
292
+	/**
293
+	 * returns TRUE if the provided class name has an alias
294
+	 *
295
+	 * @param string $class_name
296
+	 * @param string $for_class
297
+	 * @return bool
298
+	 */
299
+	public function has_alias($class_name = '', $for_class = '')
300
+	{
301
+		return isset($this->_aliases[$for_class], $this->_aliases[$for_class][$class_name])
302
+			   || (
303
+				   isset($this->_aliases[$class_name])
304
+				   && ! is_array($this->_aliases[$class_name])
305
+			   );
306
+	}
307
+
308
+
309
+
310
+	/**
311
+	 * returns alias for class name if one exists, otherwise returns the original classname
312
+	 * functions recursively, so that multiple aliases can be used to drill down to a classname
313
+	 *  for example:
314
+	 *      if the following two entries were added to the _aliases array:
315
+	 *          array(
316
+	 *              'interface_alias'           => 'some\namespace\interface'
317
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
318
+	 *          )
319
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
320
+	 *      to load an instance of 'some\namespace\classname'
321
+	 *
322
+	 * @param string $class_name
323
+	 * @param string $for_class
324
+	 * @return string
325
+	 */
326
+	public function get_alias($class_name = '', $for_class = '')
327
+	{
328
+		if (! $this->has_alias($class_name, $for_class)) {
329
+			return $class_name;
330
+		}
331
+		if ($for_class !== '') {
332
+			return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
333
+		}
334
+		return $this->get_alias($this->_aliases[$class_name]);
335
+	}
336
+
337
+
338
+
339
+	/**
340
+	 * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
341
+	 * if one exists, or whether a new object should be generated every time the requested class is loaded.
342
+	 * This is done by using the following class constants:
343
+	 *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
344
+	 *        EE_Dependency_Map::load_new_object - generates a new object every time
345
+	 */
346
+	protected function _register_core_dependencies()
347
+	{
348
+		$this->_dependency_map = array(
349
+			'EE_Request_Handler'                                                                                          => array(
350
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
351
+			),
352
+			'EE_System'                                                                                                   => array(
353
+				'EE_Registry' => EE_Dependency_Map::load_from_cache,
354
+			),
355
+			'EE_Session'                                                                                                  => array(
356
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
357
+				'EE_Encryption'                                           => EE_Dependency_Map::load_from_cache,
358
+			),
359
+			'EE_Cart'                                                                                                     => array(
360
+				'EE_Session' => EE_Dependency_Map::load_from_cache,
361
+			),
362
+			'EE_Front_Controller'                                                                                         => array(
363
+				'EE_Registry'              => EE_Dependency_Map::load_from_cache,
364
+				'EE_Request_Handler'       => EE_Dependency_Map::load_from_cache,
365
+				'EE_Module_Request_Router' => EE_Dependency_Map::load_from_cache,
366
+			),
367
+			'EE_Messenger_Collection_Loader'                                                                              => array(
368
+				'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
369
+			),
370
+			'EE_Message_Type_Collection_Loader'                                                                           => array(
371
+				'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
372
+			),
373
+			'EE_Message_Resource_Manager'                                                                                 => array(
374
+				'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
375
+				'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
376
+				'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
377
+			),
378
+			'EE_Message_Factory'                                                                                          => array(
379
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
380
+			),
381
+			'EE_messages'                                                                                                 => array(
382
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
383
+			),
384
+			'EE_Messages_Generator'                                                                                       => array(
385
+				'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
386
+				'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
387
+				'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
388
+				'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
389
+			),
390
+			'EE_Messages_Processor'                                                                                       => array(
391
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
392
+			),
393
+			'EE_Messages_Queue'                                                                                           => array(
394
+				'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
395
+			),
396
+			'EE_Messages_Template_Defaults'                                                                               => array(
397
+				'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
398
+				'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
399
+			),
400
+			'EE_Message_To_Generate_From_Request'                                                                         => array(
401
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
402
+				'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
403
+			),
404
+			'EventEspresso\core\services\commands\CommandBus'                                                             => array(
405
+				'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
406
+			),
407
+			'EventEspresso\services\commands\CommandHandler'                                                              => array(
408
+				'EE_Registry'         => EE_Dependency_Map::load_from_cache,
409
+				'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
410
+			),
411
+			'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => array(
412
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
413
+			),
414
+			'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => array(
415
+				'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
416
+				'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
417
+			),
418
+			'EventEspresso\core\services\commands\CommandFactory'                                                         => array(
419
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
420
+			),
421
+			'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => array(
422
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
423
+			),
424
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => array(
425
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
426
+			),
427
+			'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => array(
428
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
429
+			),
430
+			'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => array(
431
+				'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
432
+			),
433
+			'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => array(
434
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
435
+			),
436
+			'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => array(
437
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
438
+			),
439
+			'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => array(
440
+				'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
441
+			),
442
+			'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => array(
443
+				'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
444
+			),
445
+			'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => array(
446
+				'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
447
+			),
448
+			'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => array(
449
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
450
+			),
451
+			'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => array(
452
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
453
+			),
454
+			'EventEspresso\core\services\database\TableManager'                                                           => array(
455
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
456
+			),
457
+			'EE_Data_Migration_Class_Base'                                                                                => array(
458
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
459
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
460
+			),
461
+			'EE_DMS_Core_4_1_0'                                                                                           => array(
462
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
463
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
464
+			),
465
+			'EE_DMS_Core_4_2_0'                                                                                           => array(
466
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
467
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
468
+			),
469
+			'EE_DMS_Core_4_3_0'                                                                                           => array(
470
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
471
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
472
+			),
473
+			'EE_DMS_Core_4_4_0'                                                                                           => array(
474
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
475
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
476
+			),
477
+			'EE_DMS_Core_4_5_0'                                                                                           => array(
478
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
479
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
480
+			),
481
+			'EE_DMS_Core_4_6_0'                                                                                           => array(
482
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
483
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
484
+			),
485
+			'EE_DMS_Core_4_7_0'                                                                                           => array(
486
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
487
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
488
+			),
489
+			'EE_DMS_Core_4_8_0'                                                                                           => array(
490
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
491
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
492
+			),
493
+			'EE_DMS_Core_4_9_0'                                                                                           => array(
494
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
495
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
496
+			),
497
+			'EventEspresso\core\services\assets\Registry'                                                                 => array(
498
+				'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
499
+				'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
500
+			),
501
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                             => array(
502
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
503
+			),
504
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                              => array(
505
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
506
+			),
507
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                        => array(
508
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
509
+			),
510
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                => array(
511
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
512
+			),
513
+			'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                              => array(
514
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
515
+			),
516
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                        => array(
517
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
518
+			),
519
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                               => array(
520
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
521
+			),
522
+			'EventEspresso\core\services\cache\BasicCacheManager'                                                         => array(
523
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
524
+			),
525
+			'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                   => array(
526
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
527
+			),
528
+			'EventEspresso\core\services\validation\EmailValidationService' => array(
529
+				'EE_Registration_Config'                                  => EE_Dependency_Map::load_from_cache,
530
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
531
+			),
532
+			'EEM_Attendee' => array(
533
+				null,
534
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
535
+			),
536
+			'EEM_WP_User' => array(
537
+				null,
538
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
539
+			),
540
+		);
541
+	}
542
+
543
+
544
+
545
+	/**
546
+	 * Registers how core classes are loaded.
547
+	 * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
548
+	 *        'EE_Request_Handler' => 'load_core'
549
+	 *        'EE_Messages_Queue'  => 'load_lib'
550
+	 *        'EEH_Debug_Tools'    => 'load_helper'
551
+	 * or, if greater control is required, by providing a custom closure. For example:
552
+	 *        'Some_Class' => function () {
553
+	 *            return new Some_Class();
554
+	 *        },
555
+	 * This is required for instantiating dependencies
556
+	 * where an interface has been type hinted in a class constructor. For example:
557
+	 *        'Required_Interface' => function () {
558
+	 *            return new A_Class_That_Implements_Required_Interface();
559
+	 *        },
560
+	 */
561
+	protected function _register_core_class_loaders()
562
+	{
563
+		//for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
564
+		//be used in a closure.
565
+		$request = &$this->_request;
566
+		$response = &$this->_response;
567
+		$loader = &$this->loader;
568
+		$this->_class_loaders = array(
569
+			//load_core
570
+			'EE_Capabilities'                      => 'load_core',
571
+			'EE_Encryption'                        => 'load_core',
572
+			'EE_Front_Controller'                  => 'load_core',
573
+			'EE_Module_Request_Router'             => 'load_core',
574
+			'EE_Registry'                          => 'load_core',
575
+			'EE_Request'                           => function () use (&$request) {
576
+				return $request;
577
+			},
578
+			'EE_Response'                          => function () use (&$response) {
579
+				return $response;
580
+			},
581
+			'EE_Request_Handler'                   => 'load_core',
582
+			'EE_Session'                           => 'load_core',
583
+			'EE_System'                            => 'load_core',
584
+			//load_lib
585
+			'EE_Message_Resource_Manager'          => 'load_lib',
586
+			'EE_Message_Type_Collection'           => 'load_lib',
587
+			'EE_Message_Type_Collection_Loader'    => 'load_lib',
588
+			'EE_Messenger_Collection'              => 'load_lib',
589
+			'EE_Messenger_Collection_Loader'       => 'load_lib',
590
+			'EE_Messages_Processor'                => 'load_lib',
591
+			'EE_Message_Repository'                => 'load_lib',
592
+			'EE_Messages_Queue'                    => 'load_lib',
593
+			'EE_Messages_Data_Handler_Collection'  => 'load_lib',
594
+			'EE_Message_Template_Group_Collection' => 'load_lib',
595
+			'EE_Messages_Generator'                => function () {
596
+				return EE_Registry::instance()->load_lib(
597
+					'Messages_Generator',
598
+					array(),
599
+					false,
600
+					false
601
+				);
602
+			},
603
+			'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
604
+				return EE_Registry::instance()->load_lib(
605
+					'Messages_Template_Defaults',
606
+					$arguments,
607
+					false,
608
+					false
609
+				);
610
+			},
611
+			//load_model
612
+			'EEM_Message_Template_Group'           => 'load_model',
613
+			'EEM_Message_Template'                 => 'load_model',
614
+			//load_helper
615
+			'EEH_Parse_Shortcodes'                 => function () {
616
+				if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
617
+					return new EEH_Parse_Shortcodes();
618
+				}
619
+				return null;
620
+			},
621
+			'EE_Template_Config'                   => function () {
622
+				return EE_Config::instance()->template_settings;
623
+			},
624
+			'EE_Currency_Config'                   => function () {
625
+				return EE_Config::instance()->currency;
626
+			},
627
+			'EE_Registration_Config'                   => function () {
628
+				return EE_Config::instance()->registration;
629
+			},
630
+			'EventEspresso\core\services\loaders\Loader' => function () use (&$loader) {
631
+				return $loader;
632
+			},
633
+		);
634
+	}
635
+
636
+
637
+
638
+	/**
639
+	 * can be used for supplying alternate names for classes,
640
+	 * or for connecting interface names to instantiable classes
641
+	 */
642
+	protected function _register_core_aliases()
643
+	{
644
+		$this->_aliases = array(
645
+			'CommandBusInterface'                                                           => 'EventEspresso\core\services\commands\CommandBusInterface',
646
+			'EventEspresso\core\services\commands\CommandBusInterface'                      => 'EventEspresso\core\services\commands\CommandBus',
647
+			'CommandHandlerManagerInterface'                                                => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
648
+			'EventEspresso\core\services\commands\CommandHandlerManagerInterface'           => 'EventEspresso\core\services\commands\CommandHandlerManager',
649
+			'CapChecker'                                                                    => 'EventEspresso\core\services\commands\middleware\CapChecker',
650
+			'AddActionHook'                                                                 => 'EventEspresso\core\services\commands\middleware\AddActionHook',
651
+			'CapabilitiesChecker'                                                           => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
652
+			'CapabilitiesCheckerInterface'                                                  => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
653
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface'  => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
654
+			'CreateRegistrationService'                                                     => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
655
+			'CreateRegCodeCommandHandler'                                                   => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
656
+			'CreateRegUrlLinkCommandHandler'                                                => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
657
+			'CreateRegistrationCommandHandler'                                              => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
658
+			'CopyRegistrationDetailsCommandHandler'                                         => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
659
+			'CopyRegistrationPaymentsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
660
+			'CancelRegistrationAndTicketLineItemCommandHandler'                             => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
661
+			'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                     => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
662
+			'CreateTicketLineItemCommandHandler'                                            => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
663
+			'TableManager'                                                                  => 'EventEspresso\core\services\database\TableManager',
664
+			'TableAnalysis'                                                                 => 'EventEspresso\core\services\database\TableAnalysis',
665
+			'EspressoShortcode'                                                             => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
666
+			'ShortcodeInterface'                                                            => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
667
+			'EventEspresso\core\services\shortcodes\ShortcodeInterface'                     => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
668
+			'EventEspresso\core\services\cache\CacheStorageInterface'                       => 'EventEspresso\core\services\cache\TransientCacheStorage',
669
+			'LoaderInterface'                                                               => 'EventEspresso\core\services\loaders\LoaderInterface',
670
+			'EventEspresso\core\services\loaders\LoaderInterface'                           => 'EventEspresso\core\services\loaders\Loader',
671
+			'CommandFactoryInterface'                                                       => 'EventEspresso\core\services\commands\CommandFactoryInterface',
672
+			'EventEspresso\core\services\commands\CommandFactoryInterface'                  => 'EventEspresso\core\services\commands\CommandFactory',
673
+			'EmailValidatorInterface'                                                       => 'EventEspresso\core\domain\services\validation\EmailValidatorInterface',
674
+			'EventEspresso\core\domain\services\validation\EmailValidatorInterface'         => 'EventEspresso\core\services\validation\EmailValidationService',
675
+		);
676
+	}
677
+
678
+
679
+
680
+	/**
681
+	 * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
682
+	 * request Primarily used by unit tests.
683
+	 */
684
+	public function reset()
685
+	{
686
+		$this->_register_core_class_loaders();
687
+		$this->_register_core_dependencies();
688
+	}
689 689
 
690 690
 
691 691
 }
Please login to merge, or discard this patch.
core/libraries/form_sections/inputs/EE_Email_Input.input.php 1 patch
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -6,22 +6,22 @@
 block discarded – undo
6 6
  * @subpackage
7 7
  * @author				Mike Nelson
8 8
  */
9
-class EE_Email_Input extends EE_Form_Input_Base{
9
+class EE_Email_Input extends EE_Form_Input_Base {
10 10
 
11 11
 	/**
12 12
 	 * @param array $input_settings
13 13
 	 */
14
-	public function __construct( $input_settings = array() ){
15
-		$this->_set_display_strategy( new EE_Text_Input_Display_Strategy('email') );
16
-		$this->_set_normalization_strategy( new EE_Text_Normalization() );
14
+	public function __construct($input_settings = array()) {
15
+		$this->_set_display_strategy(new EE_Text_Input_Display_Strategy('email'));
16
+		$this->_set_normalization_strategy(new EE_Text_Normalization());
17 17
 		$this->_add_validation_strategy(
18 18
 			new EE_Email_Validation_Strategy(
19
-				isset( $input_settings[ 'validation_error_message' ] )
20
-					? $input_settings[ 'validation_error_message' ]
19
+				isset($input_settings['validation_error_message'])
20
+					? $input_settings['validation_error_message']
21 21
 					: NULL
22 22
 			)
23 23
 		);
24
-		parent::__construct( $input_settings );
25
-		$this->set_html_class( $this->html_class() . ' email' );
24
+		parent::__construct($input_settings);
25
+		$this->set_html_class($this->html_class().' email');
26 26
 	}
27 27
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Debug_Tools.helper.php 2 patches
Indentation   +639 added lines, -639 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\services\Benchmark;
2 2
 
3 3
 if (! defined('EVENT_ESPRESSO_VERSION')) {
4
-    exit('No direct script access allowed');
4
+	exit('No direct script access allowed');
5 5
 }
6 6
 
7 7
 
@@ -17,629 +17,629 @@  discard block
 block discarded – undo
17 17
 class EEH_Debug_Tools
18 18
 {
19 19
 
20
-    /**
21
-     *    instance of the EEH_Autoloader object
22
-     *
23
-     * @var    $_instance
24
-     * @access    private
25
-     */
26
-    private static $_instance;
27
-
28
-    /**
29
-     * @var array
30
-     */
31
-    protected $_memory_usage_points = array();
32
-
33
-
34
-
35
-    /**
36
-     * @singleton method used to instantiate class object
37
-     * @access    public
38
-     * @return EEH_Debug_Tools
39
-     */
40
-    public static function instance()
41
-    {
42
-        // check if class object is instantiated, and instantiated properly
43
-        if (! self::$_instance instanceof EEH_Debug_Tools) {
44
-            self::$_instance = new self();
45
-        }
46
-        return self::$_instance;
47
-    }
48
-
49
-
50
-
51
-    /**
52
-     * private class constructor
53
-     */
54
-    private function __construct()
55
-    {
56
-        // load Kint PHP debugging library
57
-        if (! class_exists('Kint') && file_exists(EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php')) {
58
-            // despite EE4 having a check for an existing copy of the Kint debugging class,
59
-            // if another plugin was loaded AFTER EE4 and they did NOT perform a similar check,
60
-            // then hilarity would ensue as PHP throws a "Cannot redeclare class Kint" error
61
-            // so we've moved it to our test folder so that it is not included with production releases
62
-            // plz use https://wordpress.org/plugins/kint-debugger/  if testing production versions of EE
63
-            require_once(EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php');
64
-        }
65
-        // if ( ! defined('DOING_AJAX') || $_REQUEST['noheader'] !== 'true' || ! isset( $_REQUEST['noheader'], $_REQUEST['TB_iframe'] ) ) {
66
-        //add_action( 'shutdown', array($this,'espresso_session_footer_dump') );
67
-        // }
68
-        $plugin = basename(EE_PLUGIN_DIR_PATH);
69
-        add_action("activate_{$plugin}", array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
70
-        add_action('activated_plugin', array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
71
-        add_action('shutdown', array('EEH_Debug_Tools', 'show_db_name'));
72
-    }
73
-
74
-
75
-
76
-    /**
77
-     *    show_db_name
78
-     *
79
-     * @return void
80
-     */
81
-    public static function show_db_name()
82
-    {
83
-        if (! defined('DOING_AJAX') && (defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS)) {
84
-            echo '<p style="font-size:10px;font-weight:normal;color:#E76700;margin: 1em 2em; text-align: right;">DB_NAME: '
85
-                 . DB_NAME
86
-                 . '</p>';
87
-        }
88
-        if (EE_DEBUG) {
89
-            Benchmark::displayResults();
90
-        }
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     *    dump EE_Session object at bottom of page after everything else has happened
97
-     *
98
-     * @return void
99
-     */
100
-    public function espresso_session_footer_dump()
101
-    {
102
-        if (
103
-            (defined('WP_DEBUG') && WP_DEBUG)
104
-            && ! defined('DOING_AJAX')
105
-            && class_exists('Kint')
106
-            && function_exists('wp_get_current_user')
107
-            && current_user_can('update_core')
108
-            && class_exists('EE_Registry')
109
-        ) {
110
-            Kint::dump(EE_Registry::instance()->SSN->id());
111
-            Kint::dump(EE_Registry::instance()->SSN);
112
-            //			Kint::dump( EE_Registry::instance()->SSN->get_session_data('cart')->get_tickets() );
113
-            $this->espresso_list_hooked_functions();
114
-            Benchmark::displayResults();
115
-        }
116
-    }
117
-
118
-
119
-
120
-    /**
121
-     *    List All Hooked Functions
122
-     *    to list all functions for a specific hook, add ee_list_hooks={hook-name} to URL
123
-     *    http://wp.smashingmagazine.com/2009/08/18/10-useful-wordpress-hook-hacks/
124
-     *
125
-     * @param string $tag
126
-     * @return void
127
-     */
128
-    public function espresso_list_hooked_functions($tag = '')
129
-    {
130
-        global $wp_filter;
131
-        echo '<br/><br/><br/><h3>Hooked Functions</h3>';
132
-        if ($tag) {
133
-            $hook[$tag] = $wp_filter[$tag];
134
-            if (! is_array($hook[$tag])) {
135
-                trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
136
-                return;
137
-            }
138
-            echo '<h5>For Tag: ' . $tag . '</h5>';
139
-        } else {
140
-            $hook = is_array($wp_filter) ? $wp_filter : array($wp_filter);
141
-            ksort($hook);
142
-        }
143
-        foreach ($hook as $tag_name => $priorities) {
144
-            echo "<br />&gt;&gt;&gt;&gt;&gt;\t<strong>$tag_name</strong><br />";
145
-            ksort($priorities);
146
-            foreach ($priorities as $priority => $function) {
147
-                echo $priority;
148
-                foreach ($function as $name => $properties) {
149
-                    echo "\t$name<br />";
150
-                }
151
-            }
152
-        }
153
-    }
154
-
155
-
156
-
157
-    /**
158
-     *    registered_filter_callbacks
159
-     *
160
-     * @param string $hook_name
161
-     * @return array
162
-     */
163
-    public static function registered_filter_callbacks($hook_name = '')
164
-    {
165
-        $filters = array();
166
-        global $wp_filter;
167
-        if (isset($wp_filter[$hook_name])) {
168
-            $filters[$hook_name] = array();
169
-            foreach ($wp_filter[$hook_name] as $priority => $callbacks) {
170
-                $filters[$hook_name][$priority] = array();
171
-                foreach ($callbacks as $callback) {
172
-                    $filters[$hook_name][$priority][] = $callback['function'];
173
-                }
174
-            }
175
-        }
176
-        return $filters;
177
-    }
178
-
179
-
180
-
181
-    /**
182
-     *    captures plugin activation errors for debugging
183
-     *
184
-     * @return void
185
-     * @throws EE_Error
186
-     */
187
-    public static function ee_plugin_activation_errors()
188
-    {
189
-        if (WP_DEBUG) {
190
-            $activation_errors = ob_get_contents();
191
-            if (! empty($activation_errors)) {
192
-                $activation_errors = date('Y-m-d H:i:s') . "\n" . $activation_errors;
193
-            }
194
-            espresso_load_required('EEH_File', EE_HELPERS . 'EEH_File.helper.php');
195
-            if (class_exists('EEH_File')) {
196
-                try {
197
-                    EEH_File::ensure_file_exists_and_is_writable(
198
-                        EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html'
199
-                    );
200
-                    EEH_File::write_to_file(
201
-                        EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html',
202
-                        $activation_errors
203
-                    );
204
-                } catch (EE_Error $e) {
205
-                    EE_Error::add_error(
206
-                        sprintf(
207
-                            __(
208
-                                'The Event Espresso activation errors file could not be setup because: %s',
209
-                                'event_espresso'
210
-                            ),
211
-                            $e->getMessage()
212
-                        ),
213
-                        __FILE__, __FUNCTION__, __LINE__
214
-                    );
215
-                }
216
-            } else {
217
-                // old school attempt
218
-                file_put_contents(
219
-                    EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html',
220
-                    $activation_errors
221
-                );
222
-            }
223
-            $activation_errors = get_option('ee_plugin_activation_errors', '') . $activation_errors;
224
-            update_option('ee_plugin_activation_errors', $activation_errors);
225
-        }
226
-    }
227
-
228
-
229
-
230
-    /**
231
-     * This basically mimics the WordPress _doing_it_wrong() function except adds our own messaging etc.
232
-     * Very useful for providing helpful messages to developers when the method of doing something has been deprecated,
233
-     * or we want to make sure they use something the right way.
234
-     *
235
-     * @access public
236
-     * @param string $function      The function that was called
237
-     * @param string $message       A message explaining what has been done incorrectly
238
-     * @param string $version       The version of Event Espresso where the error was added
239
-     * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
240
-     *                              for a deprecated function. This allows deprecation to occur during one version,
241
-     *                              but not have any notices appear until a later version. This allows developers
242
-     *                              extra time to update their code before notices appear.
243
-     * @param int    $error_type
244
-     * @uses   trigger_error()
245
-     */
246
-    public function doing_it_wrong(
247
-        $function,
248
-        $message,
249
-        $version,
250
-        $applies_when = '',
251
-        $error_type = null
252
-    ) {
253
-        $applies_when = ! empty($applies_when) ? $applies_when : espresso_version();
254
-        $error_type = $error_type !== null ? $error_type : E_USER_NOTICE;
255
-        // because we swapped the parameter order around for the last two params,
256
-        // let's verify that some third party isn't still passing an error type value for the third param
257
-        if (is_int($applies_when)) {
258
-            $error_type = $applies_when;
259
-            $applies_when = espresso_version();
260
-        }
261
-        // if not displaying notices yet, then just leave
262
-        if (version_compare(espresso_version(), $applies_when, '<')) {
263
-            return;
264
-        }
265
-        do_action('AHEE__EEH_Debug_Tools__doing_it_wrong_run', $function, $message, $version);
266
-        $version = $version === null
267
-            ? ''
268
-            : sprintf(
269
-                __('(This message was added in version %s of Event Espresso)', 'event_espresso'),
270
-                $version
271
-            );
272
-        $error_message = sprintf(
273
-            esc_html__('%1$s was called %2$sincorrectly%3$s. %4$s %5$s', 'event_espresso'),
274
-            $function,
275
-            '<strong>',
276
-            '</strong>',
277
-            $message,
278
-            $version
279
-        );
280
-        // don't trigger error if doing ajax,
281
-        // instead we'll add a transient EE_Error notice that in theory should show on the next request.
282
-        if (defined('DOING_AJAX') && DOING_AJAX) {
283
-            $error_message .= ' ' . esc_html__(
284
-                    'This is a doing_it_wrong message that was triggered during an ajax request.  The request params on this request were: ',
285
-                    'event_espresso'
286
-                );
287
-            $error_message .= '<ul><li>';
288
-            $error_message .= implode('</li><li>', EE_Registry::instance()->REQ->params());
289
-            $error_message .= '</ul>';
290
-            EE_Error::add_error($error_message, 'debug::doing_it_wrong', $function, '42');
291
-            //now we set this on the transient so it shows up on the next request.
292
-            EE_Error::get_notices(false, true);
293
-        } else {
294
-            trigger_error($error_message, $error_type);
295
-        }
296
-    }
297
-
298
-
299
-
300
-
301
-    /**
302
-     * Logger helpers
303
-     */
304
-    /**
305
-     * debug
306
-     *
307
-     * @param string $class
308
-     * @param string $func
309
-     * @param string $line
310
-     * @param array  $info
311
-     * @param bool   $display_request
312
-     * @param string $debug_index
313
-     * @param string $debug_key
314
-     * @throws EE_Error
315
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
316
-     */
317
-    public static function log(
318
-        $class = '',
319
-        $func = '',
320
-        $line = '',
321
-        $info = array(),
322
-        $display_request = false,
323
-        $debug_index = '',
324
-        $debug_key = 'EE_DEBUG_SPCO'
325
-    ) {
326
-        if (WP_DEBUG) {
327
-            $debug_key = $debug_key . '_' . EE_Session::instance()->id();
328
-            $debug_data = get_option($debug_key, array());
329
-            $default_data = array(
330
-                $class => $func . '() : ' . $line,
331
-                'REQ'  => $display_request ? $_REQUEST : '',
332
-            );
333
-            // don't serialize objects
334
-            $info = self::strip_objects($info);
335
-            $index = ! empty($debug_index) ? $debug_index : 0;
336
-            if (! isset($debug_data[$index])) {
337
-                $debug_data[$index] = array();
338
-            }
339
-            $debug_data[$index][microtime()] = array_merge($default_data, $info);
340
-            update_option($debug_key, $debug_data);
341
-        }
342
-    }
343
-
344
-
345
-
346
-    /**
347
-     * strip_objects
348
-     *
349
-     * @param array $info
350
-     * @return array
351
-     */
352
-    public static function strip_objects($info = array())
353
-    {
354
-        foreach ($info as $key => $value) {
355
-            if (is_array($value)) {
356
-                $info[$key] = self::strip_objects($value);
357
-            } else if (is_object($value)) {
358
-                $object_class = get_class($value);
359
-                $info[$object_class] = array();
360
-                $info[$object_class]['ID'] = method_exists($value, 'ID') ? $value->ID() : spl_object_hash($value);
361
-                if (method_exists($value, 'ID')) {
362
-                    $info[$object_class]['ID'] = $value->ID();
363
-                }
364
-                if (method_exists($value, 'status')) {
365
-                    $info[$object_class]['status'] = $value->status();
366
-                } else if (method_exists($value, 'status_ID')) {
367
-                    $info[$object_class]['status'] = $value->status_ID();
368
-                }
369
-                unset($info[$key]);
370
-            }
371
-        }
372
-        return (array)$info;
373
-    }
374
-
375
-
376
-
377
-    /**
378
-     * @param mixed  $var
379
-     * @param string $var_name
380
-     * @param string $file
381
-     * @param int    $line
382
-     * @param int    $heading_tag
383
-     * @param bool   $die
384
-     * @param string $margin
385
-     */
386
-    public static function printv(
387
-        $var,
388
-        $var_name = '',
389
-        $file = __FILE__,
390
-        $line = __LINE__,
391
-        $heading_tag = 5,
392
-        $die = false,
393
-        $margin = ''
394
-    ) {
395
-        $var_name = ! $var_name ? 'string' : $var_name;
396
-        $var_name = ucwords(str_replace('$', '', $var_name));
397
-        $is_method = method_exists($var_name, $var);
398
-        $var_name = ucwords(str_replace('_', ' ', $var_name));
399
-        $heading_tag = is_int($heading_tag) ? "h{$heading_tag}" : 'h5';
400
-        $result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin);
401
-        $result .= $is_method
402
-            ? EEH_Debug_Tools::grey_span('::') . EEH_Debug_Tools::orange_span($var . '()')
403
-            : EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span($var);
404
-        $result .= EEH_Debug_Tools::file_and_line($file, $line);
405
-        $result .= EEH_Debug_Tools::headingX($heading_tag);
406
-        if ($die) {
407
-            die($result);
408
-        }
409
-        echo $result;
410
-    }
411
-
412
-
413
-
414
-    /**
415
-     * @param string $var_name
416
-     * @param string $heading_tag
417
-     * @param string $margin
418
-     * @return string
419
-     */
420
-    protected static function heading($var_name = '', $heading_tag = 'h5', $margin = '')
421
-    {
422
-        if (defined('EE_TESTS_DIR')) {
423
-            return "\n{$var_name}";
424
-        }
425
-        $margin = "25px 0 0 {$margin}";
426
-        return '<' . $heading_tag . ' style="color:#2EA2CC; margin:' . $margin . ';"><b>' . $var_name . '</b>';
427
-    }
428
-
429
-
430
-
431
-    /**
432
-     * @param string $heading_tag
433
-     * @return string
434
-     */
435
-    protected static function headingX($heading_tag = 'h5')
436
-    {
437
-        if (defined('EE_TESTS_DIR')) {
438
-            return "\n";
439
-        }
440
-        return '</' . $heading_tag . '>';
441
-    }
442
-
443
-
444
-
445
-    /**
446
-     * @param string $content
447
-     * @return string
448
-     */
449
-    protected static function grey_span($content = '')
450
-    {
451
-        if (defined('EE_TESTS_DIR')) {
452
-            return $content;
453
-        }
454
-        return '<span style="color:#999">' . $content . '</span>';
455
-    }
456
-
457
-
458
-
459
-    /**
460
-     * @param string $file
461
-     * @param int    $line
462
-     * @return string
463
-     */
464
-    protected static function file_and_line($file, $line)
465
-    {
466
-        if($file === '') {
467
-            return '';
468
-        }
469
-        if (defined('EE_TESTS_DIR')) {
470
-            return "\n\t(" . $file . ' line no: ' . $line . ' ) ';
471
-        }
472
-        return '<br /><span style="font-size:9px;font-weight:normal;color:#666;line-height: 12px;">'
473
-               . $file
474
-               . '<br />line no: '
475
-               . $line
476
-               . '</span>';
477
-    }
478
-
479
-
480
-
481
-    /**
482
-     * @param string $content
483
-     * @return string
484
-     */
485
-    protected static function orange_span($content = '')
486
-    {
487
-        if (defined('EE_TESTS_DIR')) {
488
-            return $content;
489
-        }
490
-        return '<span style="color:#E76700">' . $content . '</span>';
491
-    }
492
-
493
-
494
-
495
-    /**
496
-     * @param mixed $var
497
-     * @return string
498
-     */
499
-    protected static function pre_span($var)
500
-    {
501
-        ob_start();
502
-        var_dump($var);
503
-        $var = ob_get_clean();
504
-        if (defined('EE_TESTS_DIR')) {
505
-            return "\n" . $var;
506
-        }
507
-        return '<pre style="color:#999; padding:1em; background: #fff">' . $var . '</pre>';
508
-    }
509
-
510
-
511
-
512
-    /**
513
-     * @param mixed  $var
514
-     * @param string $var_name
515
-     * @param string $file
516
-     * @param int    $line
517
-     * @param int    $heading_tag
518
-     * @param bool   $die
519
-     */
520
-    public static function printr(
521
-        $var,
522
-        $var_name = '',
523
-        $file = '',
524
-        $line = 0,
525
-        $heading_tag = 5,
526
-        $die = false
527
-    ) {
528
-        // return;
529
-        $file = str_replace(rtrim(ABSPATH, '\\/'), '', $file);
530
-        $margin = is_admin() ? ' 180px' : '0';
531
-        //$print_r = false;
532
-        if (is_string($var)) {
533
-            EEH_Debug_Tools::printv($var, $var_name, $file, $line, $heading_tag, $die, $margin);
534
-            return;
535
-        }
536
-        if (is_object($var)) {
537
-            $var_name = ! $var_name ? 'object' : $var_name;
538
-            //$print_r = true;
539
-        } else if (is_array($var)) {
540
-            $var_name = ! $var_name ? 'array' : $var_name;
541
-            //$print_r = true;
542
-        } else if (is_numeric($var)) {
543
-            $var_name = ! $var_name ? 'numeric' : $var_name;
544
-        } else if ($var === null) {
545
-            $var_name = ! $var_name ? 'null' : $var_name;
546
-        }
547
-        $var_name = ucwords(str_replace(array('$', '_'), array('', ' '), $var_name));
548
-        $heading_tag = is_int($heading_tag) ? "h{$heading_tag}" : 'h5';
549
-        $result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin);
550
-        $result .= EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span(
551
-                EEH_Debug_Tools::pre_span($var)
552
-            );
553
-        $result .= EEH_Debug_Tools::file_and_line($file, $line);
554
-        $result .= EEH_Debug_Tools::headingX($heading_tag);
555
-        if ($die) {
556
-            die($result);
557
-        }
558
-        echo $result;
559
-    }
560
-
561
-
562
-
563
-    /******************** deprecated ********************/
564
-    /**
565
-     * @deprecated 4.9.39.rc.034
566
-     */
567
-    public function reset_times()
568
-    {
569
-        Benchmark::resetTimes();
570
-    }
571
-
572
-
573
-
574
-    /**
575
-     * @deprecated 4.9.39.rc.034
576
-     * @param null $timer_name
577
-     */
578
-    public function start_timer($timer_name = null)
579
-    {
580
-        Benchmark::startTimer($timer_name);
581
-    }
582
-
583
-
584
-
585
-    /**
586
-     * @deprecated 4.9.39.rc.034
587
-     * @param string $timer_name
588
-     */
589
-    public function stop_timer($timer_name = '')
590
-    {
591
-        Benchmark::stopTimer($timer_name);
592
-    }
593
-
594
-
595
-
596
-    /**
597
-     * @deprecated 4.9.39.rc.034
598
-     * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
599
-     * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
600
-     * @return void
601
-     */
602
-    public function measure_memory($label, $output_now = false)
603
-    {
604
-        Benchmark::measureMemory($label, $output_now);
605
-    }
606
-
607
-
608
-
609
-    /**
610
-     * @deprecated 4.9.39.rc.034
611
-     * @param int $size
612
-     * @return string
613
-     */
614
-    public function convert($size)
615
-    {
616
-        return Benchmark::convert($size);
617
-    }
618
-
619
-
620
-
621
-    /**
622
-     * @deprecated 4.9.39.rc.034
623
-     * @param bool $output_now
624
-     * @return string
625
-     */
626
-    public function show_times($output_now = true)
627
-    {
628
-        return Benchmark::displayResults($output_now);
629
-    }
630
-
631
-
632
-
633
-    /**
634
-     * @deprecated 4.9.39.rc.034
635
-     * @param string $timer_name
636
-     * @param float  $total_time
637
-     * @return string
638
-     */
639
-    public function format_time($timer_name, $total_time)
640
-    {
641
-        return Benchmark::formatTime($timer_name, $total_time);
642
-    }
20
+	/**
21
+	 *    instance of the EEH_Autoloader object
22
+	 *
23
+	 * @var    $_instance
24
+	 * @access    private
25
+	 */
26
+	private static $_instance;
27
+
28
+	/**
29
+	 * @var array
30
+	 */
31
+	protected $_memory_usage_points = array();
32
+
33
+
34
+
35
+	/**
36
+	 * @singleton method used to instantiate class object
37
+	 * @access    public
38
+	 * @return EEH_Debug_Tools
39
+	 */
40
+	public static function instance()
41
+	{
42
+		// check if class object is instantiated, and instantiated properly
43
+		if (! self::$_instance instanceof EEH_Debug_Tools) {
44
+			self::$_instance = new self();
45
+		}
46
+		return self::$_instance;
47
+	}
48
+
49
+
50
+
51
+	/**
52
+	 * private class constructor
53
+	 */
54
+	private function __construct()
55
+	{
56
+		// load Kint PHP debugging library
57
+		if (! class_exists('Kint') && file_exists(EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php')) {
58
+			// despite EE4 having a check for an existing copy of the Kint debugging class,
59
+			// if another plugin was loaded AFTER EE4 and they did NOT perform a similar check,
60
+			// then hilarity would ensue as PHP throws a "Cannot redeclare class Kint" error
61
+			// so we've moved it to our test folder so that it is not included with production releases
62
+			// plz use https://wordpress.org/plugins/kint-debugger/  if testing production versions of EE
63
+			require_once(EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php');
64
+		}
65
+		// if ( ! defined('DOING_AJAX') || $_REQUEST['noheader'] !== 'true' || ! isset( $_REQUEST['noheader'], $_REQUEST['TB_iframe'] ) ) {
66
+		//add_action( 'shutdown', array($this,'espresso_session_footer_dump') );
67
+		// }
68
+		$plugin = basename(EE_PLUGIN_DIR_PATH);
69
+		add_action("activate_{$plugin}", array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
70
+		add_action('activated_plugin', array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
71
+		add_action('shutdown', array('EEH_Debug_Tools', 'show_db_name'));
72
+	}
73
+
74
+
75
+
76
+	/**
77
+	 *    show_db_name
78
+	 *
79
+	 * @return void
80
+	 */
81
+	public static function show_db_name()
82
+	{
83
+		if (! defined('DOING_AJAX') && (defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS)) {
84
+			echo '<p style="font-size:10px;font-weight:normal;color:#E76700;margin: 1em 2em; text-align: right;">DB_NAME: '
85
+				 . DB_NAME
86
+				 . '</p>';
87
+		}
88
+		if (EE_DEBUG) {
89
+			Benchmark::displayResults();
90
+		}
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 *    dump EE_Session object at bottom of page after everything else has happened
97
+	 *
98
+	 * @return void
99
+	 */
100
+	public function espresso_session_footer_dump()
101
+	{
102
+		if (
103
+			(defined('WP_DEBUG') && WP_DEBUG)
104
+			&& ! defined('DOING_AJAX')
105
+			&& class_exists('Kint')
106
+			&& function_exists('wp_get_current_user')
107
+			&& current_user_can('update_core')
108
+			&& class_exists('EE_Registry')
109
+		) {
110
+			Kint::dump(EE_Registry::instance()->SSN->id());
111
+			Kint::dump(EE_Registry::instance()->SSN);
112
+			//			Kint::dump( EE_Registry::instance()->SSN->get_session_data('cart')->get_tickets() );
113
+			$this->espresso_list_hooked_functions();
114
+			Benchmark::displayResults();
115
+		}
116
+	}
117
+
118
+
119
+
120
+	/**
121
+	 *    List All Hooked Functions
122
+	 *    to list all functions for a specific hook, add ee_list_hooks={hook-name} to URL
123
+	 *    http://wp.smashingmagazine.com/2009/08/18/10-useful-wordpress-hook-hacks/
124
+	 *
125
+	 * @param string $tag
126
+	 * @return void
127
+	 */
128
+	public function espresso_list_hooked_functions($tag = '')
129
+	{
130
+		global $wp_filter;
131
+		echo '<br/><br/><br/><h3>Hooked Functions</h3>';
132
+		if ($tag) {
133
+			$hook[$tag] = $wp_filter[$tag];
134
+			if (! is_array($hook[$tag])) {
135
+				trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
136
+				return;
137
+			}
138
+			echo '<h5>For Tag: ' . $tag . '</h5>';
139
+		} else {
140
+			$hook = is_array($wp_filter) ? $wp_filter : array($wp_filter);
141
+			ksort($hook);
142
+		}
143
+		foreach ($hook as $tag_name => $priorities) {
144
+			echo "<br />&gt;&gt;&gt;&gt;&gt;\t<strong>$tag_name</strong><br />";
145
+			ksort($priorities);
146
+			foreach ($priorities as $priority => $function) {
147
+				echo $priority;
148
+				foreach ($function as $name => $properties) {
149
+					echo "\t$name<br />";
150
+				}
151
+			}
152
+		}
153
+	}
154
+
155
+
156
+
157
+	/**
158
+	 *    registered_filter_callbacks
159
+	 *
160
+	 * @param string $hook_name
161
+	 * @return array
162
+	 */
163
+	public static function registered_filter_callbacks($hook_name = '')
164
+	{
165
+		$filters = array();
166
+		global $wp_filter;
167
+		if (isset($wp_filter[$hook_name])) {
168
+			$filters[$hook_name] = array();
169
+			foreach ($wp_filter[$hook_name] as $priority => $callbacks) {
170
+				$filters[$hook_name][$priority] = array();
171
+				foreach ($callbacks as $callback) {
172
+					$filters[$hook_name][$priority][] = $callback['function'];
173
+				}
174
+			}
175
+		}
176
+		return $filters;
177
+	}
178
+
179
+
180
+
181
+	/**
182
+	 *    captures plugin activation errors for debugging
183
+	 *
184
+	 * @return void
185
+	 * @throws EE_Error
186
+	 */
187
+	public static function ee_plugin_activation_errors()
188
+	{
189
+		if (WP_DEBUG) {
190
+			$activation_errors = ob_get_contents();
191
+			if (! empty($activation_errors)) {
192
+				$activation_errors = date('Y-m-d H:i:s') . "\n" . $activation_errors;
193
+			}
194
+			espresso_load_required('EEH_File', EE_HELPERS . 'EEH_File.helper.php');
195
+			if (class_exists('EEH_File')) {
196
+				try {
197
+					EEH_File::ensure_file_exists_and_is_writable(
198
+						EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html'
199
+					);
200
+					EEH_File::write_to_file(
201
+						EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html',
202
+						$activation_errors
203
+					);
204
+				} catch (EE_Error $e) {
205
+					EE_Error::add_error(
206
+						sprintf(
207
+							__(
208
+								'The Event Espresso activation errors file could not be setup because: %s',
209
+								'event_espresso'
210
+							),
211
+							$e->getMessage()
212
+						),
213
+						__FILE__, __FUNCTION__, __LINE__
214
+					);
215
+				}
216
+			} else {
217
+				// old school attempt
218
+				file_put_contents(
219
+					EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html',
220
+					$activation_errors
221
+				);
222
+			}
223
+			$activation_errors = get_option('ee_plugin_activation_errors', '') . $activation_errors;
224
+			update_option('ee_plugin_activation_errors', $activation_errors);
225
+		}
226
+	}
227
+
228
+
229
+
230
+	/**
231
+	 * This basically mimics the WordPress _doing_it_wrong() function except adds our own messaging etc.
232
+	 * Very useful for providing helpful messages to developers when the method of doing something has been deprecated,
233
+	 * or we want to make sure they use something the right way.
234
+	 *
235
+	 * @access public
236
+	 * @param string $function      The function that was called
237
+	 * @param string $message       A message explaining what has been done incorrectly
238
+	 * @param string $version       The version of Event Espresso where the error was added
239
+	 * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
240
+	 *                              for a deprecated function. This allows deprecation to occur during one version,
241
+	 *                              but not have any notices appear until a later version. This allows developers
242
+	 *                              extra time to update their code before notices appear.
243
+	 * @param int    $error_type
244
+	 * @uses   trigger_error()
245
+	 */
246
+	public function doing_it_wrong(
247
+		$function,
248
+		$message,
249
+		$version,
250
+		$applies_when = '',
251
+		$error_type = null
252
+	) {
253
+		$applies_when = ! empty($applies_when) ? $applies_when : espresso_version();
254
+		$error_type = $error_type !== null ? $error_type : E_USER_NOTICE;
255
+		// because we swapped the parameter order around for the last two params,
256
+		// let's verify that some third party isn't still passing an error type value for the third param
257
+		if (is_int($applies_when)) {
258
+			$error_type = $applies_when;
259
+			$applies_when = espresso_version();
260
+		}
261
+		// if not displaying notices yet, then just leave
262
+		if (version_compare(espresso_version(), $applies_when, '<')) {
263
+			return;
264
+		}
265
+		do_action('AHEE__EEH_Debug_Tools__doing_it_wrong_run', $function, $message, $version);
266
+		$version = $version === null
267
+			? ''
268
+			: sprintf(
269
+				__('(This message was added in version %s of Event Espresso)', 'event_espresso'),
270
+				$version
271
+			);
272
+		$error_message = sprintf(
273
+			esc_html__('%1$s was called %2$sincorrectly%3$s. %4$s %5$s', 'event_espresso'),
274
+			$function,
275
+			'<strong>',
276
+			'</strong>',
277
+			$message,
278
+			$version
279
+		);
280
+		// don't trigger error if doing ajax,
281
+		// instead we'll add a transient EE_Error notice that in theory should show on the next request.
282
+		if (defined('DOING_AJAX') && DOING_AJAX) {
283
+			$error_message .= ' ' . esc_html__(
284
+					'This is a doing_it_wrong message that was triggered during an ajax request.  The request params on this request were: ',
285
+					'event_espresso'
286
+				);
287
+			$error_message .= '<ul><li>';
288
+			$error_message .= implode('</li><li>', EE_Registry::instance()->REQ->params());
289
+			$error_message .= '</ul>';
290
+			EE_Error::add_error($error_message, 'debug::doing_it_wrong', $function, '42');
291
+			//now we set this on the transient so it shows up on the next request.
292
+			EE_Error::get_notices(false, true);
293
+		} else {
294
+			trigger_error($error_message, $error_type);
295
+		}
296
+	}
297
+
298
+
299
+
300
+
301
+	/**
302
+	 * Logger helpers
303
+	 */
304
+	/**
305
+	 * debug
306
+	 *
307
+	 * @param string $class
308
+	 * @param string $func
309
+	 * @param string $line
310
+	 * @param array  $info
311
+	 * @param bool   $display_request
312
+	 * @param string $debug_index
313
+	 * @param string $debug_key
314
+	 * @throws EE_Error
315
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
316
+	 */
317
+	public static function log(
318
+		$class = '',
319
+		$func = '',
320
+		$line = '',
321
+		$info = array(),
322
+		$display_request = false,
323
+		$debug_index = '',
324
+		$debug_key = 'EE_DEBUG_SPCO'
325
+	) {
326
+		if (WP_DEBUG) {
327
+			$debug_key = $debug_key . '_' . EE_Session::instance()->id();
328
+			$debug_data = get_option($debug_key, array());
329
+			$default_data = array(
330
+				$class => $func . '() : ' . $line,
331
+				'REQ'  => $display_request ? $_REQUEST : '',
332
+			);
333
+			// don't serialize objects
334
+			$info = self::strip_objects($info);
335
+			$index = ! empty($debug_index) ? $debug_index : 0;
336
+			if (! isset($debug_data[$index])) {
337
+				$debug_data[$index] = array();
338
+			}
339
+			$debug_data[$index][microtime()] = array_merge($default_data, $info);
340
+			update_option($debug_key, $debug_data);
341
+		}
342
+	}
343
+
344
+
345
+
346
+	/**
347
+	 * strip_objects
348
+	 *
349
+	 * @param array $info
350
+	 * @return array
351
+	 */
352
+	public static function strip_objects($info = array())
353
+	{
354
+		foreach ($info as $key => $value) {
355
+			if (is_array($value)) {
356
+				$info[$key] = self::strip_objects($value);
357
+			} else if (is_object($value)) {
358
+				$object_class = get_class($value);
359
+				$info[$object_class] = array();
360
+				$info[$object_class]['ID'] = method_exists($value, 'ID') ? $value->ID() : spl_object_hash($value);
361
+				if (method_exists($value, 'ID')) {
362
+					$info[$object_class]['ID'] = $value->ID();
363
+				}
364
+				if (method_exists($value, 'status')) {
365
+					$info[$object_class]['status'] = $value->status();
366
+				} else if (method_exists($value, 'status_ID')) {
367
+					$info[$object_class]['status'] = $value->status_ID();
368
+				}
369
+				unset($info[$key]);
370
+			}
371
+		}
372
+		return (array)$info;
373
+	}
374
+
375
+
376
+
377
+	/**
378
+	 * @param mixed  $var
379
+	 * @param string $var_name
380
+	 * @param string $file
381
+	 * @param int    $line
382
+	 * @param int    $heading_tag
383
+	 * @param bool   $die
384
+	 * @param string $margin
385
+	 */
386
+	public static function printv(
387
+		$var,
388
+		$var_name = '',
389
+		$file = __FILE__,
390
+		$line = __LINE__,
391
+		$heading_tag = 5,
392
+		$die = false,
393
+		$margin = ''
394
+	) {
395
+		$var_name = ! $var_name ? 'string' : $var_name;
396
+		$var_name = ucwords(str_replace('$', '', $var_name));
397
+		$is_method = method_exists($var_name, $var);
398
+		$var_name = ucwords(str_replace('_', ' ', $var_name));
399
+		$heading_tag = is_int($heading_tag) ? "h{$heading_tag}" : 'h5';
400
+		$result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin);
401
+		$result .= $is_method
402
+			? EEH_Debug_Tools::grey_span('::') . EEH_Debug_Tools::orange_span($var . '()')
403
+			: EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span($var);
404
+		$result .= EEH_Debug_Tools::file_and_line($file, $line);
405
+		$result .= EEH_Debug_Tools::headingX($heading_tag);
406
+		if ($die) {
407
+			die($result);
408
+		}
409
+		echo $result;
410
+	}
411
+
412
+
413
+
414
+	/**
415
+	 * @param string $var_name
416
+	 * @param string $heading_tag
417
+	 * @param string $margin
418
+	 * @return string
419
+	 */
420
+	protected static function heading($var_name = '', $heading_tag = 'h5', $margin = '')
421
+	{
422
+		if (defined('EE_TESTS_DIR')) {
423
+			return "\n{$var_name}";
424
+		}
425
+		$margin = "25px 0 0 {$margin}";
426
+		return '<' . $heading_tag . ' style="color:#2EA2CC; margin:' . $margin . ';"><b>' . $var_name . '</b>';
427
+	}
428
+
429
+
430
+
431
+	/**
432
+	 * @param string $heading_tag
433
+	 * @return string
434
+	 */
435
+	protected static function headingX($heading_tag = 'h5')
436
+	{
437
+		if (defined('EE_TESTS_DIR')) {
438
+			return "\n";
439
+		}
440
+		return '</' . $heading_tag . '>';
441
+	}
442
+
443
+
444
+
445
+	/**
446
+	 * @param string $content
447
+	 * @return string
448
+	 */
449
+	protected static function grey_span($content = '')
450
+	{
451
+		if (defined('EE_TESTS_DIR')) {
452
+			return $content;
453
+		}
454
+		return '<span style="color:#999">' . $content . '</span>';
455
+	}
456
+
457
+
458
+
459
+	/**
460
+	 * @param string $file
461
+	 * @param int    $line
462
+	 * @return string
463
+	 */
464
+	protected static function file_and_line($file, $line)
465
+	{
466
+		if($file === '') {
467
+			return '';
468
+		}
469
+		if (defined('EE_TESTS_DIR')) {
470
+			return "\n\t(" . $file . ' line no: ' . $line . ' ) ';
471
+		}
472
+		return '<br /><span style="font-size:9px;font-weight:normal;color:#666;line-height: 12px;">'
473
+			   . $file
474
+			   . '<br />line no: '
475
+			   . $line
476
+			   . '</span>';
477
+	}
478
+
479
+
480
+
481
+	/**
482
+	 * @param string $content
483
+	 * @return string
484
+	 */
485
+	protected static function orange_span($content = '')
486
+	{
487
+		if (defined('EE_TESTS_DIR')) {
488
+			return $content;
489
+		}
490
+		return '<span style="color:#E76700">' . $content . '</span>';
491
+	}
492
+
493
+
494
+
495
+	/**
496
+	 * @param mixed $var
497
+	 * @return string
498
+	 */
499
+	protected static function pre_span($var)
500
+	{
501
+		ob_start();
502
+		var_dump($var);
503
+		$var = ob_get_clean();
504
+		if (defined('EE_TESTS_DIR')) {
505
+			return "\n" . $var;
506
+		}
507
+		return '<pre style="color:#999; padding:1em; background: #fff">' . $var . '</pre>';
508
+	}
509
+
510
+
511
+
512
+	/**
513
+	 * @param mixed  $var
514
+	 * @param string $var_name
515
+	 * @param string $file
516
+	 * @param int    $line
517
+	 * @param int    $heading_tag
518
+	 * @param bool   $die
519
+	 */
520
+	public static function printr(
521
+		$var,
522
+		$var_name = '',
523
+		$file = '',
524
+		$line = 0,
525
+		$heading_tag = 5,
526
+		$die = false
527
+	) {
528
+		// return;
529
+		$file = str_replace(rtrim(ABSPATH, '\\/'), '', $file);
530
+		$margin = is_admin() ? ' 180px' : '0';
531
+		//$print_r = false;
532
+		if (is_string($var)) {
533
+			EEH_Debug_Tools::printv($var, $var_name, $file, $line, $heading_tag, $die, $margin);
534
+			return;
535
+		}
536
+		if (is_object($var)) {
537
+			$var_name = ! $var_name ? 'object' : $var_name;
538
+			//$print_r = true;
539
+		} else if (is_array($var)) {
540
+			$var_name = ! $var_name ? 'array' : $var_name;
541
+			//$print_r = true;
542
+		} else if (is_numeric($var)) {
543
+			$var_name = ! $var_name ? 'numeric' : $var_name;
544
+		} else if ($var === null) {
545
+			$var_name = ! $var_name ? 'null' : $var_name;
546
+		}
547
+		$var_name = ucwords(str_replace(array('$', '_'), array('', ' '), $var_name));
548
+		$heading_tag = is_int($heading_tag) ? "h{$heading_tag}" : 'h5';
549
+		$result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin);
550
+		$result .= EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span(
551
+				EEH_Debug_Tools::pre_span($var)
552
+			);
553
+		$result .= EEH_Debug_Tools::file_and_line($file, $line);
554
+		$result .= EEH_Debug_Tools::headingX($heading_tag);
555
+		if ($die) {
556
+			die($result);
557
+		}
558
+		echo $result;
559
+	}
560
+
561
+
562
+
563
+	/******************** deprecated ********************/
564
+	/**
565
+	 * @deprecated 4.9.39.rc.034
566
+	 */
567
+	public function reset_times()
568
+	{
569
+		Benchmark::resetTimes();
570
+	}
571
+
572
+
573
+
574
+	/**
575
+	 * @deprecated 4.9.39.rc.034
576
+	 * @param null $timer_name
577
+	 */
578
+	public function start_timer($timer_name = null)
579
+	{
580
+		Benchmark::startTimer($timer_name);
581
+	}
582
+
583
+
584
+
585
+	/**
586
+	 * @deprecated 4.9.39.rc.034
587
+	 * @param string $timer_name
588
+	 */
589
+	public function stop_timer($timer_name = '')
590
+	{
591
+		Benchmark::stopTimer($timer_name);
592
+	}
593
+
594
+
595
+
596
+	/**
597
+	 * @deprecated 4.9.39.rc.034
598
+	 * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
599
+	 * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
600
+	 * @return void
601
+	 */
602
+	public function measure_memory($label, $output_now = false)
603
+	{
604
+		Benchmark::measureMemory($label, $output_now);
605
+	}
606
+
607
+
608
+
609
+	/**
610
+	 * @deprecated 4.9.39.rc.034
611
+	 * @param int $size
612
+	 * @return string
613
+	 */
614
+	public function convert($size)
615
+	{
616
+		return Benchmark::convert($size);
617
+	}
618
+
619
+
620
+
621
+	/**
622
+	 * @deprecated 4.9.39.rc.034
623
+	 * @param bool $output_now
624
+	 * @return string
625
+	 */
626
+	public function show_times($output_now = true)
627
+	{
628
+		return Benchmark::displayResults($output_now);
629
+	}
630
+
631
+
632
+
633
+	/**
634
+	 * @deprecated 4.9.39.rc.034
635
+	 * @param string $timer_name
636
+	 * @param float  $total_time
637
+	 * @return string
638
+	 */
639
+	public function format_time($timer_name, $total_time)
640
+	{
641
+		return Benchmark::formatTime($timer_name, $total_time);
642
+	}
643 643
 
644 644
 
645 645
 
@@ -652,31 +652,31 @@  discard block
 block discarded – undo
652 652
  * Plugin URI: http://upthemes.com/plugins/kint-debugger/
653 653
  */
654 654
 if (class_exists('Kint') && ! function_exists('dump_wp_query')) {
655
-    function dump_wp_query()
656
-    {
657
-        global $wp_query;
658
-        d($wp_query);
659
-    }
655
+	function dump_wp_query()
656
+	{
657
+		global $wp_query;
658
+		d($wp_query);
659
+	}
660 660
 }
661 661
 /**
662 662
  * borrowed from Kint Debugger
663 663
  * Plugin URI: http://upthemes.com/plugins/kint-debugger/
664 664
  */
665 665
 if (class_exists('Kint') && ! function_exists('dump_wp')) {
666
-    function dump_wp()
667
-    {
668
-        global $wp;
669
-        d($wp);
670
-    }
666
+	function dump_wp()
667
+	{
668
+		global $wp;
669
+		d($wp);
670
+	}
671 671
 }
672 672
 /**
673 673
  * borrowed from Kint Debugger
674 674
  * Plugin URI: http://upthemes.com/plugins/kint-debugger/
675 675
  */
676 676
 if (class_exists('Kint') && ! function_exists('dump_post')) {
677
-    function dump_post()
678
-    {
679
-        global $post;
680
-        d($post);
681
-    }
677
+	function dump_post()
678
+	{
679
+		global $post;
680
+		d($post);
681
+	}
682 682
 }
Please login to merge, or discard this patch.
Spacing   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\services\Benchmark;
2 2
 
3
-if (! defined('EVENT_ESPRESSO_VERSION')) {
3
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
4 4
     exit('No direct script access allowed');
5 5
 }
6 6
 
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
     public static function instance()
41 41
     {
42 42
         // check if class object is instantiated, and instantiated properly
43
-        if (! self::$_instance instanceof EEH_Debug_Tools) {
43
+        if ( ! self::$_instance instanceof EEH_Debug_Tools) {
44 44
             self::$_instance = new self();
45 45
         }
46 46
         return self::$_instance;
@@ -54,13 +54,13 @@  discard block
 block discarded – undo
54 54
     private function __construct()
55 55
     {
56 56
         // load Kint PHP debugging library
57
-        if (! class_exists('Kint') && file_exists(EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php')) {
57
+        if ( ! class_exists('Kint') && file_exists(EE_PLUGIN_DIR_PATH.'tests'.DS.'kint'.DS.'Kint.class.php')) {
58 58
             // despite EE4 having a check for an existing copy of the Kint debugging class,
59 59
             // if another plugin was loaded AFTER EE4 and they did NOT perform a similar check,
60 60
             // then hilarity would ensue as PHP throws a "Cannot redeclare class Kint" error
61 61
             // so we've moved it to our test folder so that it is not included with production releases
62 62
             // plz use https://wordpress.org/plugins/kint-debugger/  if testing production versions of EE
63
-            require_once(EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php');
63
+            require_once(EE_PLUGIN_DIR_PATH.'tests'.DS.'kint'.DS.'Kint.class.php');
64 64
         }
65 65
         // if ( ! defined('DOING_AJAX') || $_REQUEST['noheader'] !== 'true' || ! isset( $_REQUEST['noheader'], $_REQUEST['TB_iframe'] ) ) {
66 66
         //add_action( 'shutdown', array($this,'espresso_session_footer_dump') );
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
      */
81 81
     public static function show_db_name()
82 82
     {
83
-        if (! defined('DOING_AJAX') && (defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS)) {
83
+        if ( ! defined('DOING_AJAX') && (defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS)) {
84 84
             echo '<p style="font-size:10px;font-weight:normal;color:#E76700;margin: 1em 2em; text-align: right;">DB_NAME: '
85 85
                  . DB_NAME
86 86
                  . '</p>';
@@ -131,11 +131,11 @@  discard block
 block discarded – undo
131 131
         echo '<br/><br/><br/><h3>Hooked Functions</h3>';
132 132
         if ($tag) {
133 133
             $hook[$tag] = $wp_filter[$tag];
134
-            if (! is_array($hook[$tag])) {
134
+            if ( ! is_array($hook[$tag])) {
135 135
                 trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
136 136
                 return;
137 137
             }
138
-            echo '<h5>For Tag: ' . $tag . '</h5>';
138
+            echo '<h5>For Tag: '.$tag.'</h5>';
139 139
         } else {
140 140
             $hook = is_array($wp_filter) ? $wp_filter : array($wp_filter);
141 141
             ksort($hook);
@@ -188,17 +188,17 @@  discard block
 block discarded – undo
188 188
     {
189 189
         if (WP_DEBUG) {
190 190
             $activation_errors = ob_get_contents();
191
-            if (! empty($activation_errors)) {
192
-                $activation_errors = date('Y-m-d H:i:s') . "\n" . $activation_errors;
191
+            if ( ! empty($activation_errors)) {
192
+                $activation_errors = date('Y-m-d H:i:s')."\n".$activation_errors;
193 193
             }
194
-            espresso_load_required('EEH_File', EE_HELPERS . 'EEH_File.helper.php');
194
+            espresso_load_required('EEH_File', EE_HELPERS.'EEH_File.helper.php');
195 195
             if (class_exists('EEH_File')) {
196 196
                 try {
197 197
                     EEH_File::ensure_file_exists_and_is_writable(
198
-                        EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html'
198
+                        EVENT_ESPRESSO_UPLOAD_DIR.'logs'.DS.'espresso_plugin_activation_errors.html'
199 199
                     );
200 200
                     EEH_File::write_to_file(
201
-                        EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html',
201
+                        EVENT_ESPRESSO_UPLOAD_DIR.'logs'.DS.'espresso_plugin_activation_errors.html',
202 202
                         $activation_errors
203 203
                     );
204 204
                 } catch (EE_Error $e) {
@@ -216,11 +216,11 @@  discard block
 block discarded – undo
216 216
             } else {
217 217
                 // old school attempt
218 218
                 file_put_contents(
219
-                    EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html',
219
+                    EVENT_ESPRESSO_UPLOAD_DIR.'logs'.DS.'espresso_plugin_activation_errors.html',
220 220
                     $activation_errors
221 221
                 );
222 222
             }
223
-            $activation_errors = get_option('ee_plugin_activation_errors', '') . $activation_errors;
223
+            $activation_errors = get_option('ee_plugin_activation_errors', '').$activation_errors;
224 224
             update_option('ee_plugin_activation_errors', $activation_errors);
225 225
         }
226 226
     }
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
         // don't trigger error if doing ajax,
281 281
         // instead we'll add a transient EE_Error notice that in theory should show on the next request.
282 282
         if (defined('DOING_AJAX') && DOING_AJAX) {
283
-            $error_message .= ' ' . esc_html__(
283
+            $error_message .= ' '.esc_html__(
284 284
                     'This is a doing_it_wrong message that was triggered during an ajax request.  The request params on this request were: ',
285 285
                     'event_espresso'
286 286
                 );
@@ -324,16 +324,16 @@  discard block
 block discarded – undo
324 324
         $debug_key = 'EE_DEBUG_SPCO'
325 325
     ) {
326 326
         if (WP_DEBUG) {
327
-            $debug_key = $debug_key . '_' . EE_Session::instance()->id();
327
+            $debug_key = $debug_key.'_'.EE_Session::instance()->id();
328 328
             $debug_data = get_option($debug_key, array());
329 329
             $default_data = array(
330
-                $class => $func . '() : ' . $line,
330
+                $class => $func.'() : '.$line,
331 331
                 'REQ'  => $display_request ? $_REQUEST : '',
332 332
             );
333 333
             // don't serialize objects
334 334
             $info = self::strip_objects($info);
335 335
             $index = ! empty($debug_index) ? $debug_index : 0;
336
-            if (! isset($debug_data[$index])) {
336
+            if ( ! isset($debug_data[$index])) {
337 337
                 $debug_data[$index] = array();
338 338
             }
339 339
             $debug_data[$index][microtime()] = array_merge($default_data, $info);
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
                 unset($info[$key]);
370 370
             }
371 371
         }
372
-        return (array)$info;
372
+        return (array) $info;
373 373
     }
374 374
 
375 375
 
@@ -399,8 +399,8 @@  discard block
 block discarded – undo
399 399
         $heading_tag = is_int($heading_tag) ? "h{$heading_tag}" : 'h5';
400 400
         $result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin);
401 401
         $result .= $is_method
402
-            ? EEH_Debug_Tools::grey_span('::') . EEH_Debug_Tools::orange_span($var . '()')
403
-            : EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span($var);
402
+            ? EEH_Debug_Tools::grey_span('::').EEH_Debug_Tools::orange_span($var.'()')
403
+            : EEH_Debug_Tools::grey_span(' : ').EEH_Debug_Tools::orange_span($var);
404 404
         $result .= EEH_Debug_Tools::file_and_line($file, $line);
405 405
         $result .= EEH_Debug_Tools::headingX($heading_tag);
406 406
         if ($die) {
@@ -423,7 +423,7 @@  discard block
 block discarded – undo
423 423
             return "\n{$var_name}";
424 424
         }
425 425
         $margin = "25px 0 0 {$margin}";
426
-        return '<' . $heading_tag . ' style="color:#2EA2CC; margin:' . $margin . ';"><b>' . $var_name . '</b>';
426
+        return '<'.$heading_tag.' style="color:#2EA2CC; margin:'.$margin.';"><b>'.$var_name.'</b>';
427 427
     }
428 428
 
429 429
 
@@ -437,7 +437,7 @@  discard block
 block discarded – undo
437 437
         if (defined('EE_TESTS_DIR')) {
438 438
             return "\n";
439 439
         }
440
-        return '</' . $heading_tag . '>';
440
+        return '</'.$heading_tag.'>';
441 441
     }
442 442
 
443 443
 
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
         if (defined('EE_TESTS_DIR')) {
452 452
             return $content;
453 453
         }
454
-        return '<span style="color:#999">' . $content . '</span>';
454
+        return '<span style="color:#999">'.$content.'</span>';
455 455
     }
456 456
 
457 457
 
@@ -463,11 +463,11 @@  discard block
 block discarded – undo
463 463
      */
464 464
     protected static function file_and_line($file, $line)
465 465
     {
466
-        if($file === '') {
466
+        if ($file === '') {
467 467
             return '';
468 468
         }
469 469
         if (defined('EE_TESTS_DIR')) {
470
-            return "\n\t(" . $file . ' line no: ' . $line . ' ) ';
470
+            return "\n\t(".$file.' line no: '.$line.' ) ';
471 471
         }
472 472
         return '<br /><span style="font-size:9px;font-weight:normal;color:#666;line-height: 12px;">'
473 473
                . $file
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
         if (defined('EE_TESTS_DIR')) {
488 488
             return $content;
489 489
         }
490
-        return '<span style="color:#E76700">' . $content . '</span>';
490
+        return '<span style="color:#E76700">'.$content.'</span>';
491 491
     }
492 492
 
493 493
 
@@ -502,9 +502,9 @@  discard block
 block discarded – undo
502 502
         var_dump($var);
503 503
         $var = ob_get_clean();
504 504
         if (defined('EE_TESTS_DIR')) {
505
-            return "\n" . $var;
505
+            return "\n".$var;
506 506
         }
507
-        return '<pre style="color:#999; padding:1em; background: #fff">' . $var . '</pre>';
507
+        return '<pre style="color:#999; padding:1em; background: #fff">'.$var.'</pre>';
508 508
     }
509 509
 
510 510
 
@@ -547,7 +547,7 @@  discard block
 block discarded – undo
547 547
         $var_name = ucwords(str_replace(array('$', '_'), array('', ' '), $var_name));
548 548
         $heading_tag = is_int($heading_tag) ? "h{$heading_tag}" : 'h5';
549 549
         $result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin);
550
-        $result .= EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span(
550
+        $result .= EEH_Debug_Tools::grey_span(' : ').EEH_Debug_Tools::orange_span(
551 551
                 EEH_Debug_Tools::pre_span($var)
552 552
             );
553 553
         $result .= EEH_Debug_Tools::file_and_line($file, $line);
Please login to merge, or discard this patch.
core/services/Benchmark.php 1 patch
Indentation   +224 added lines, -224 removed lines patch added patch discarded remove patch
@@ -17,230 +17,230 @@
 block discarded – undo
17 17
 class Benchmark
18 18
 {
19 19
 
20
-    /**
21
-     * array containing the start time for the timers
22
-     */
23
-    private static $start_times;
24
-
25
-    /**
26
-     * array containing all the timer'd times, which can be outputted via show_times()
27
-     */
28
-    private static $times = array();
29
-
30
-    /**
31
-     * @var array
32
-     */
33
-    protected static $memory_usage = array();
34
-
35
-
36
-
37
-    /**
38
-     * whether to benchmark code or not
39
-     */
40
-    public static function doNotRun()
41
-    {
42
-        return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
43
-    }
44
-
45
-
46
-
47
-    /**
48
-     * resetTimes
49
-     */
50
-    public static function resetTimes()
51
-    {
52
-        Benchmark::$times = array();
53
-    }
54
-
55
-
56
-
57
-    /**
58
-     * Add Benchmark::startTimer() before a block of code you want to measure the performance of
59
-     *
60
-     * @param null $timer_name
61
-     */
62
-    public static function startTimer($timer_name = null)
63
-    {
64
-        if (Benchmark::doNotRun()) {
65
-            return;
66
-        }
67
-        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
68
-        Benchmark::$start_times[$timer_name] = microtime(true);
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
75
-     *
76
-     * @param string $timer_name
77
-     */
78
-    public static function stopTimer($timer_name = '')
79
-    {
80
-        if (Benchmark::doNotRun()) {
81
-            return;
82
-        }
83
-        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
84
-        if (isset(Benchmark::$start_times[$timer_name])) {
85
-            $start_time = Benchmark::$start_times[$timer_name];
86
-            unset(Benchmark::$start_times[$timer_name]);
87
-        } else {
88
-            $start_time = array_pop(Benchmark::$start_times);
89
-        }
90
-        Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     * Measure the memory usage by PHP so far.
97
-     *
98
-     * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
99
-     * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
100
-     * @return void
101
-     */
102
-    public static function measureMemory($label, $output_now = false)
103
-    {
104
-        if (Benchmark::doNotRun()) {
105
-            return;
106
-        }
107
-        $memory_used = Benchmark::convert(memory_get_peak_usage(true));
108
-        Benchmark::$memory_usage[$label] = $memory_used;
109
-        if ($output_now) {
110
-            echo defined('EE_TESTS_DIR') ? "\r\n " : '<br />';
111
-            echo "$label : $memory_used";
112
-        }
113
-    }
114
-
115
-
116
-
117
-    /**
118
-     * will display the benchmarking results at shutdown
119
-     *
120
-     * @return void
121
-     */
122
-    public static function displayResultsAtShutdown()
123
-    {
124
-        add_action(
125
-            'shutdown',
126
-            function () {
127
-                Benchmark::displayResults();
128
-            }
129
-        );
130
-    }
131
-
132
-
133
-
134
-    /**
135
-     * displayResults
136
-     *
137
-     * @param bool $echo
138
-     * @return string
139
-     */
140
-    public static function displayResults($echo = true)
141
-    {
142
-        if (Benchmark::doNotRun()) {
143
-            return '';
144
-        }
145
-        $output = '';
146
-        if (! empty(Benchmark::$times)) {
147
-            $total = 0;
148
-            $output .= '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />';
149
-            foreach (Benchmark::$times as $timer_name => $total_time) {
150
-                $output .= Benchmark::formatTime($timer_name, $total_time) . '<br />';
151
-                $total += $total_time;
152
-            }
153
-            $output .= '<br />';
154
-            $output .= '<h4>TOTAL TIME</h4>';
155
-            $output .= Benchmark::formatTime('', $total);
156
-            $output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
157
-            $output .= '<br />';
158
-            $output .= '<h5>Performance scale (from best to worse)</h5>';
159
-            $output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
160
-            $output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
161
-            $output .= '<span style="color:limegreen">Like...groovy!</span><br />';
162
-            $output .= '<span style="color:gold">Ruh Oh</span><br />';
163
-            $output .= '<span style="color:darkorange">Zoinks!</span><br />';
164
-            $output .= '<span style="color:red">Like...HEEELLLP</span><br />';
165
-        }
166
-        if (! empty(Benchmark::$memory_usage)) {
167
-            $output .= '<h5>Memory</h5>' . implode('<br />', Benchmark::$memory_usage);
168
-        }
169
-        if (empty($output)) {
170
-            return '';
171
-        }
172
-        $output = '<div style="border:1px solid #dddddd; background-color:#ffffff;'
173
-                  . (is_admin() ? ' margin:2em 2em 2em 180px;' : ' margin:2em;')
174
-                  . ' padding:2em;">'
175
-                  . '<h4>BENCHMARKING</h4>'
176
-                  . $output
177
-                  . '</div>';
178
-        if ($echo) {
179
-            echo $output;
180
-            return '';
181
-        }
182
-        return $output;
183
-    }
184
-
185
-
186
-
187
-    /**
188
-     * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
189
-     *
190
-     * @param int $size
191
-     * @return string
192
-     */
193
-    public static function convert($size)
194
-    {
195
-        $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
196
-        return round($size / pow(1024, $i = floor(log($size, 1024))), 2) . ' ' . $unit[absint($i)];
197
-    }
198
-
199
-
200
-
201
-    /**
202
-     * @param string $timer_name
203
-     * @param float  $total_time
204
-     * @return string
205
-     */
206
-    public static function formatTime($timer_name, $total_time)
207
-    {
208
-        $total_time *= 1000;
209
-        switch ($total_time) {
210
-            case $total_time > 12500 :
211
-                $color = 'red';
212
-                $bold = 'bold';
213
-                break;
214
-            case $total_time > 2500 :
215
-                $color = 'darkorange';
216
-                $bold = 'bold';
217
-                break;
218
-            case $total_time > 500 :
219
-                $color = 'gold';
220
-                $bold = 'bold';
221
-                break;
222
-            case $total_time > 100 :
223
-                $color = 'limegreen';
224
-                $bold = 'normal';
225
-                break;
226
-            case $total_time > 20 :
227
-                $color = 'deepskyblue';
228
-                $bold = 'normal';
229
-                break;
230
-            default :
231
-                $color = 'mediumpurple';
232
-                $bold = 'normal';
233
-                break;
234
-        }
235
-        return '<span style="min-width: 10px; margin:0 1em; color:'
236
-               . $color
237
-               . '; font-weight:'
238
-               . $bold
239
-               . '; font-size:1.2em;">'
240
-               . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
241
-               . '</span> '
242
-               . $timer_name;
243
-    }
20
+	/**
21
+	 * array containing the start time for the timers
22
+	 */
23
+	private static $start_times;
24
+
25
+	/**
26
+	 * array containing all the timer'd times, which can be outputted via show_times()
27
+	 */
28
+	private static $times = array();
29
+
30
+	/**
31
+	 * @var array
32
+	 */
33
+	protected static $memory_usage = array();
34
+
35
+
36
+
37
+	/**
38
+	 * whether to benchmark code or not
39
+	 */
40
+	public static function doNotRun()
41
+	{
42
+		return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
43
+	}
44
+
45
+
46
+
47
+	/**
48
+	 * resetTimes
49
+	 */
50
+	public static function resetTimes()
51
+	{
52
+		Benchmark::$times = array();
53
+	}
54
+
55
+
56
+
57
+	/**
58
+	 * Add Benchmark::startTimer() before a block of code you want to measure the performance of
59
+	 *
60
+	 * @param null $timer_name
61
+	 */
62
+	public static function startTimer($timer_name = null)
63
+	{
64
+		if (Benchmark::doNotRun()) {
65
+			return;
66
+		}
67
+		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
68
+		Benchmark::$start_times[$timer_name] = microtime(true);
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
75
+	 *
76
+	 * @param string $timer_name
77
+	 */
78
+	public static function stopTimer($timer_name = '')
79
+	{
80
+		if (Benchmark::doNotRun()) {
81
+			return;
82
+		}
83
+		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
84
+		if (isset(Benchmark::$start_times[$timer_name])) {
85
+			$start_time = Benchmark::$start_times[$timer_name];
86
+			unset(Benchmark::$start_times[$timer_name]);
87
+		} else {
88
+			$start_time = array_pop(Benchmark::$start_times);
89
+		}
90
+		Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 * Measure the memory usage by PHP so far.
97
+	 *
98
+	 * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
99
+	 * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
100
+	 * @return void
101
+	 */
102
+	public static function measureMemory($label, $output_now = false)
103
+	{
104
+		if (Benchmark::doNotRun()) {
105
+			return;
106
+		}
107
+		$memory_used = Benchmark::convert(memory_get_peak_usage(true));
108
+		Benchmark::$memory_usage[$label] = $memory_used;
109
+		if ($output_now) {
110
+			echo defined('EE_TESTS_DIR') ? "\r\n " : '<br />';
111
+			echo "$label : $memory_used";
112
+		}
113
+	}
114
+
115
+
116
+
117
+	/**
118
+	 * will display the benchmarking results at shutdown
119
+	 *
120
+	 * @return void
121
+	 */
122
+	public static function displayResultsAtShutdown()
123
+	{
124
+		add_action(
125
+			'shutdown',
126
+			function () {
127
+				Benchmark::displayResults();
128
+			}
129
+		);
130
+	}
131
+
132
+
133
+
134
+	/**
135
+	 * displayResults
136
+	 *
137
+	 * @param bool $echo
138
+	 * @return string
139
+	 */
140
+	public static function displayResults($echo = true)
141
+	{
142
+		if (Benchmark::doNotRun()) {
143
+			return '';
144
+		}
145
+		$output = '';
146
+		if (! empty(Benchmark::$times)) {
147
+			$total = 0;
148
+			$output .= '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />';
149
+			foreach (Benchmark::$times as $timer_name => $total_time) {
150
+				$output .= Benchmark::formatTime($timer_name, $total_time) . '<br />';
151
+				$total += $total_time;
152
+			}
153
+			$output .= '<br />';
154
+			$output .= '<h4>TOTAL TIME</h4>';
155
+			$output .= Benchmark::formatTime('', $total);
156
+			$output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
157
+			$output .= '<br />';
158
+			$output .= '<h5>Performance scale (from best to worse)</h5>';
159
+			$output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
160
+			$output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
161
+			$output .= '<span style="color:limegreen">Like...groovy!</span><br />';
162
+			$output .= '<span style="color:gold">Ruh Oh</span><br />';
163
+			$output .= '<span style="color:darkorange">Zoinks!</span><br />';
164
+			$output .= '<span style="color:red">Like...HEEELLLP</span><br />';
165
+		}
166
+		if (! empty(Benchmark::$memory_usage)) {
167
+			$output .= '<h5>Memory</h5>' . implode('<br />', Benchmark::$memory_usage);
168
+		}
169
+		if (empty($output)) {
170
+			return '';
171
+		}
172
+		$output = '<div style="border:1px solid #dddddd; background-color:#ffffff;'
173
+				  . (is_admin() ? ' margin:2em 2em 2em 180px;' : ' margin:2em;')
174
+				  . ' padding:2em;">'
175
+				  . '<h4>BENCHMARKING</h4>'
176
+				  . $output
177
+				  . '</div>';
178
+		if ($echo) {
179
+			echo $output;
180
+			return '';
181
+		}
182
+		return $output;
183
+	}
184
+
185
+
186
+
187
+	/**
188
+	 * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
189
+	 *
190
+	 * @param int $size
191
+	 * @return string
192
+	 */
193
+	public static function convert($size)
194
+	{
195
+		$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
196
+		return round($size / pow(1024, $i = floor(log($size, 1024))), 2) . ' ' . $unit[absint($i)];
197
+	}
198
+
199
+
200
+
201
+	/**
202
+	 * @param string $timer_name
203
+	 * @param float  $total_time
204
+	 * @return string
205
+	 */
206
+	public static function formatTime($timer_name, $total_time)
207
+	{
208
+		$total_time *= 1000;
209
+		switch ($total_time) {
210
+			case $total_time > 12500 :
211
+				$color = 'red';
212
+				$bold = 'bold';
213
+				break;
214
+			case $total_time > 2500 :
215
+				$color = 'darkorange';
216
+				$bold = 'bold';
217
+				break;
218
+			case $total_time > 500 :
219
+				$color = 'gold';
220
+				$bold = 'bold';
221
+				break;
222
+			case $total_time > 100 :
223
+				$color = 'limegreen';
224
+				$bold = 'normal';
225
+				break;
226
+			case $total_time > 20 :
227
+				$color = 'deepskyblue';
228
+				$bold = 'normal';
229
+				break;
230
+			default :
231
+				$color = 'mediumpurple';
232
+				$bold = 'normal';
233
+				break;
234
+		}
235
+		return '<span style="min-width: 10px; margin:0 1em; color:'
236
+			   . $color
237
+			   . '; font-weight:'
238
+			   . $bold
239
+			   . '; font-size:1.2em;">'
240
+			   . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
241
+			   . '</span> '
242
+			   . $timer_name;
243
+	}
244 244
 
245 245
 
246 246
 
Please login to merge, or discard this patch.
core/db_models/fields/EE_Email_Field.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -15,50 +15,50 @@
 block discarded – undo
15 15
 class EE_Email_Field extends EE_Text_Field_Base
16 16
 {
17 17
 
18
-    /**
19
-     * @var Loader $loader
20
-     */
21
-    private $loader;
18
+	/**
19
+	 * @var Loader $loader
20
+	 */
21
+	private $loader;
22 22
 
23 23
 
24 24
 
25
-    /**
26
-     * @param string $table_column
27
-     * @param string $nice_name
28
-     * @param bool   $nullable
29
-     * @param null   $default_value
30
-     * @param Loader $loader
31
-     * @throws InvalidArgumentException
32
-     */
33
-    public function __construct($table_column, $nice_name, $nullable, $default_value = null, Loader $loader)
34
-    {
35
-        parent::__construct($table_column, $nice_name, $nullable, $default_value);
36
-        $this->setSchemaFormat('email');
37
-        $this->loader = $loader;
38
-    }
25
+	/**
26
+	 * @param string $table_column
27
+	 * @param string $nice_name
28
+	 * @param bool   $nullable
29
+	 * @param null   $default_value
30
+	 * @param Loader $loader
31
+	 * @throws InvalidArgumentException
32
+	 */
33
+	public function __construct($table_column, $nice_name, $nullable, $default_value = null, Loader $loader)
34
+	{
35
+		parent::__construct($table_column, $nice_name, $nullable, $default_value);
36
+		$this->setSchemaFormat('email');
37
+		$this->loader = $loader;
38
+	}
39 39
 
40 40
 
41 41
 
42
-    /**
43
-     * In form inputs, we should have called htmlentities and addslashes() on form inputs,
44
-     * so we need to undo that on setting of these fields
45
-     *
46
-     * @param string $email_address
47
-     * @return string
48
-     * @throws InvalidArgumentException
49
-     * @throws InvalidInterfaceException
50
-     * @throws InvalidDataTypeException
51
-     */
52
-    public function prepare_for_set($email_address)
53
-    {
54
-        $validation_service = $this->loader->getShared(
55
-            'EventEspresso\core\domain\services\validation\EmailValidatorInterface'
56
-        );
57
-        try {
58
-            $validation_service->validate($email_address);
59
-            return $email_address;
60
-        } catch (EmailValidationException $e) {
61
-            return '';
62
-        }
63
-    }
42
+	/**
43
+	 * In form inputs, we should have called htmlentities and addslashes() on form inputs,
44
+	 * so we need to undo that on setting of these fields
45
+	 *
46
+	 * @param string $email_address
47
+	 * @return string
48
+	 * @throws InvalidArgumentException
49
+	 * @throws InvalidInterfaceException
50
+	 * @throws InvalidDataTypeException
51
+	 */
52
+	public function prepare_for_set($email_address)
53
+	{
54
+		$validation_service = $this->loader->getShared(
55
+			'EventEspresso\core\domain\services\validation\EmailValidatorInterface'
56
+		);
57
+		try {
58
+			$validation_service->validate($email_address);
59
+			return $email_address;
60
+		} catch (EmailValidationException $e) {
61
+			return '';
62
+		}
63
+	}
64 64
 }
Please login to merge, or discard this patch.
core/db_models/EEM_WP_User.model.php 2 patches
Indentation   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\services\loaders\Loader;
2 2
 
3 3
 if (! defined('EVENT_ESPRESSO_VERSION')) {
4
-    exit('No direct script access allowed');
4
+	exit('No direct script access allowed');
5 5
 }
6 6
 
7 7
 
@@ -17,135 +17,135 @@  discard block
 block discarded – undo
17 17
 class EEM_WP_User extends EEM_Base
18 18
 {
19 19
 
20
-    /**
21
-     * private instance of the EEM_WP_User object
22
-     *
23
-     * @type EEM_WP_User
24
-     */
25
-    protected static $_instance = null;
20
+	/**
21
+	 * private instance of the EEM_WP_User object
22
+	 *
23
+	 * @type EEM_WP_User
24
+	 */
25
+	protected static $_instance = null;
26 26
 
27 27
 
28 28
 
29
-    /**
30
-     *    constructor
31
-     *
32
-     * @param null   $timezone
33
-     * @param Loader $loader
34
-     * @throws EE_Error
35
-     * @throws \InvalidArgumentException
36
-     */
37
-    protected function __construct($timezone = null, Loader $loader)
38
-    {
39
-        $this->singular_item = __('WP_User', 'event_espresso');
40
-        $this->plural_item = __('WP_Users', 'event_espresso');
41
-        global $wpdb;
42
-        $this->_tables = array(
43
-            'WP_User' => new EE_Primary_Table($wpdb->users, 'ID', true),
44
-        );
45
-        $this->_fields = array(
46
-            'WP_User' => array(
47
-                'ID'                  => new EE_Primary_Key_Int_Field('ID', __('WP_User ID', 'event_espresso')),
48
-                'user_login'          => new EE_Plain_Text_Field(
49
-                    'user_login',
50
-                    __('User Login', 'event_espresso'),
51
-                    false,
52
-                    ''
53
-                ),
54
-                'user_pass'           => new EE_Plain_Text_Field(
55
-                    'user_pass',
56
-                    __('User Password', 'event_espresso'),
57
-                    false,
58
-                    ''
59
-                ),
60
-                'user_nicename'       => new EE_Plain_Text_Field(
61
-                    'user_nicename',
62
-                    __(' User Nice Name', 'event_espresso'),
63
-                    false,
64
-                    ''
65
-                ),
66
-                'user_email'          => new EE_Email_Field(
67
-                    'user_email',
68
-                    __('User Email', 'event_espresso'),
69
-                    false,
70
-                    null,
71
-                    $loader
72
-                ),
73
-                'user_registered'     => new EE_Datetime_Field(
74
-                    'user_registered',
75
-                    __('Date User Registered', 'event_espresso'),
76
-                    false,
77
-                    EE_Datetime_Field::now,
78
-                    $timezone
79
-                ),
80
-                'user_activation_key' => new EE_Plain_Text_Field(
81
-                    'user_activation_key',
82
-                    __('User Activation Key', 'event_espresso'),
83
-                    false,
84
-                    ''
85
-                ),
86
-                'user_status'         => new EE_Integer_Field(
87
-                    'user_status',
88
-                    __('User Status', 'event_espresso'),
89
-                    false,
90
-                    0
91
-                ),
92
-                'display_name'        => new EE_Plain_Text_Field(
93
-                    'display_name',
94
-                    __('Display Name', 'event_espresso'),
95
-                    false,
96
-                    ''
97
-                ),
98
-            ),
99
-        );
100
-        $this->_model_relations = array(
101
-            'Attendee'       => new EE_Has_Many_Relation(),
102
-            // all models are related to the change log
103
-            // 'Change_Log'     => new EE_Has_Many_Relation(),
104
-            'Event'          => new EE_Has_Many_Relation(),
105
-            'Payment_Method' => new EE_Has_Many_Relation(),
106
-            'Price'          => new EE_Has_Many_Relation(),
107
-            'Price_Type'     => new EE_Has_Many_Relation(),
108
-            'Question'       => new EE_Has_Many_Relation(),
109
-            'Question_Group' => new EE_Has_Many_Relation(),
110
-            'Ticket'         => new EE_Has_Many_Relation(),
111
-            'Venue'          => new EE_Has_Many_Relation(),
112
-            'Message'        => new EE_Has_Many_Relation(),
113
-        );
114
-        $this->_wp_core_model = true;
115
-        $this->_caps_slug = 'users';
116
-        $this->_cap_contexts_to_cap_action_map[EEM_Base::caps_read] = 'list';
117
-        $this->_cap_contexts_to_cap_action_map[EEM_Base::caps_read_admin] = 'list';
118
-        foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
119
-            $this->_cap_restriction_generators[$context] = new EE_Restriction_Generator_WP_User();
120
-        }
121
-        //@todo: account for create_users controls whether they can create users at all
122
-        parent::__construct($timezone);
123
-        $this->loader = $loader;
124
-    }
29
+	/**
30
+	 *    constructor
31
+	 *
32
+	 * @param null   $timezone
33
+	 * @param Loader $loader
34
+	 * @throws EE_Error
35
+	 * @throws \InvalidArgumentException
36
+	 */
37
+	protected function __construct($timezone = null, Loader $loader)
38
+	{
39
+		$this->singular_item = __('WP_User', 'event_espresso');
40
+		$this->plural_item = __('WP_Users', 'event_espresso');
41
+		global $wpdb;
42
+		$this->_tables = array(
43
+			'WP_User' => new EE_Primary_Table($wpdb->users, 'ID', true),
44
+		);
45
+		$this->_fields = array(
46
+			'WP_User' => array(
47
+				'ID'                  => new EE_Primary_Key_Int_Field('ID', __('WP_User ID', 'event_espresso')),
48
+				'user_login'          => new EE_Plain_Text_Field(
49
+					'user_login',
50
+					__('User Login', 'event_espresso'),
51
+					false,
52
+					''
53
+				),
54
+				'user_pass'           => new EE_Plain_Text_Field(
55
+					'user_pass',
56
+					__('User Password', 'event_espresso'),
57
+					false,
58
+					''
59
+				),
60
+				'user_nicename'       => new EE_Plain_Text_Field(
61
+					'user_nicename',
62
+					__(' User Nice Name', 'event_espresso'),
63
+					false,
64
+					''
65
+				),
66
+				'user_email'          => new EE_Email_Field(
67
+					'user_email',
68
+					__('User Email', 'event_espresso'),
69
+					false,
70
+					null,
71
+					$loader
72
+				),
73
+				'user_registered'     => new EE_Datetime_Field(
74
+					'user_registered',
75
+					__('Date User Registered', 'event_espresso'),
76
+					false,
77
+					EE_Datetime_Field::now,
78
+					$timezone
79
+				),
80
+				'user_activation_key' => new EE_Plain_Text_Field(
81
+					'user_activation_key',
82
+					__('User Activation Key', 'event_espresso'),
83
+					false,
84
+					''
85
+				),
86
+				'user_status'         => new EE_Integer_Field(
87
+					'user_status',
88
+					__('User Status', 'event_espresso'),
89
+					false,
90
+					0
91
+				),
92
+				'display_name'        => new EE_Plain_Text_Field(
93
+					'display_name',
94
+					__('Display Name', 'event_espresso'),
95
+					false,
96
+					''
97
+				),
98
+			),
99
+		);
100
+		$this->_model_relations = array(
101
+			'Attendee'       => new EE_Has_Many_Relation(),
102
+			// all models are related to the change log
103
+			// 'Change_Log'     => new EE_Has_Many_Relation(),
104
+			'Event'          => new EE_Has_Many_Relation(),
105
+			'Payment_Method' => new EE_Has_Many_Relation(),
106
+			'Price'          => new EE_Has_Many_Relation(),
107
+			'Price_Type'     => new EE_Has_Many_Relation(),
108
+			'Question'       => new EE_Has_Many_Relation(),
109
+			'Question_Group' => new EE_Has_Many_Relation(),
110
+			'Ticket'         => new EE_Has_Many_Relation(),
111
+			'Venue'          => new EE_Has_Many_Relation(),
112
+			'Message'        => new EE_Has_Many_Relation(),
113
+		);
114
+		$this->_wp_core_model = true;
115
+		$this->_caps_slug = 'users';
116
+		$this->_cap_contexts_to_cap_action_map[EEM_Base::caps_read] = 'list';
117
+		$this->_cap_contexts_to_cap_action_map[EEM_Base::caps_read_admin] = 'list';
118
+		foreach ($this->_cap_contexts_to_cap_action_map as $context => $action) {
119
+			$this->_cap_restriction_generators[$context] = new EE_Restriction_Generator_WP_User();
120
+		}
121
+		//@todo: account for create_users controls whether they can create users at all
122
+		parent::__construct($timezone);
123
+		$this->loader = $loader;
124
+	}
125 125
 
126 126
 
127 127
 
128
-    /**
129
-     * We don't need a foreign key to the WP_User model, we just need its primary key
130
-     *
131
-     * @return string
132
-     */
133
-    public function wp_user_field_name()
134
-    {
135
-        return $this->primary_key_name();
136
-    }
128
+	/**
129
+	 * We don't need a foreign key to the WP_User model, we just need its primary key
130
+	 *
131
+	 * @return string
132
+	 */
133
+	public function wp_user_field_name()
134
+	{
135
+		return $this->primary_key_name();
136
+	}
137 137
 
138 138
 
139 139
 
140
-    /**
141
-     * This WP_User model IS owned, even though it doesn't have a foreign key to itself
142
-     *
143
-     * @return boolean
144
-     */
145
-    public function is_owned()
146
-    {
147
-        return true;
148
-    }
140
+	/**
141
+	 * This WP_User model IS owned, even though it doesn't have a foreign key to itself
142
+	 *
143
+	 * @return boolean
144
+	 */
145
+	public function is_owned()
146
+	{
147
+		return true;
148
+	}
149 149
 }
150 150
 // End of file EEM_WP_User.model.php
151 151
 // Location: /core/db_models/EEM_WP_User.model.php
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@
 block discarded – undo
1 1
 <?php use EventEspresso\core\services\loaders\Loader;
2 2
 
3
-if (! defined('EVENT_ESPRESSO_VERSION')) {
3
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
4 4
     exit('No direct script access allowed');
5 5
 }
6 6
 
Please login to merge, or discard this patch.
core/db_models/EEM_Attendee.model.php 2 patches
Indentation   +325 added lines, -325 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\services\loaders\Loader;
2 2
 
3 3
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
4
-    exit('No direct script access allowed');
4
+	exit('No direct script access allowed');
5 5
 }
6 6
 require_once(EE_MODELS . 'EEM_Base.model.php');
7 7
 
@@ -17,338 +17,338 @@  discard block
 block discarded – undo
17 17
 class EEM_Attendee extends EEM_CPT_Base
18 18
 {
19 19
 
20
-    // private instance of the Attendee object
21
-    protected static $_instance = null;
20
+	// private instance of the Attendee object
21
+	protected static $_instance = null;
22 22
 
23
-    /**
24
-     * QST_system for questions are strings not ints now,
25
-     * so these constants are deprecated.
26
-     * Please instead use the EEM_Attendee::system_question_* constants
27
-     *
28
-     * @deprecated
29
-     */
30
-    const fname_question_id = 1;
23
+	/**
24
+	 * QST_system for questions are strings not ints now,
25
+	 * so these constants are deprecated.
26
+	 * Please instead use the EEM_Attendee::system_question_* constants
27
+	 *
28
+	 * @deprecated
29
+	 */
30
+	const fname_question_id = 1;
31 31
 
32
-    /**
33
-     * @deprecated
34
-     */
35
-    const lname_question_id = 2;
32
+	/**
33
+	 * @deprecated
34
+	 */
35
+	const lname_question_id = 2;
36 36
 
37 37
 
38
-    /**
39
-     * @deprecated
40
-     */
41
-    const email_question_id = 3;
38
+	/**
39
+	 * @deprecated
40
+	 */
41
+	const email_question_id = 3;
42 42
 
43 43
 
44
-    /**
45
-     * @deprecated
46
-     */
47
-    const address_question_id = 4;
44
+	/**
45
+	 * @deprecated
46
+	 */
47
+	const address_question_id = 4;
48 48
 
49 49
 
50
-    /**
51
-     * @deprecated
52
-     */
53
-    const address2_question_id = 5;
54
-
55
-
56
-    /**
57
-     * @deprecated
58
-     */
59
-    const city_question_id = 6;
60
-
61
-
62
-    /**
63
-     * @deprecated
64
-     */
65
-    const state_question_id = 7;
66
-
67
-
68
-    /**
69
-     * @deprecated
70
-     */
71
-    const country_question_id = 8;
72
-
73
-
74
-    /**
75
-     * @deprecated
76
-     */
77
-    const zip_question_id = 9;
78
-
79
-
80
-    /**
81
-     * @deprecated
82
-     */
83
-    const phone_question_id = 10;
84
-
85
-    /**
86
-     * When looking for questions that correspond to attendee fields,
87
-     * look for the question with this QST_system value.
88
-     * These replace the old constants like EEM_Attendee::*_question_id
89
-     */
90
-    const system_question_fname    = 'fname';
91
-
92
-    const system_question_lname    = 'lname';
93
-
94
-    const system_question_email    = 'email';
95
-
96
-    const system_question_address  = 'address';
97
-
98
-    const system_question_address2 = 'address2';
99
-
100
-    const system_question_city     = 'city';
101
-
102
-    const system_question_state    = 'state';
103
-
104
-    const system_question_country  = 'country';
105
-
106
-    const system_question_zip      = 'zip';
107
-
108
-    const system_question_phone    = 'phone';
109
-
110
-    /**
111
-     * Keys are all the EEM_Attendee::system_question_* constants, which are
112
-     * also all the values of QST_system in the questions table, and values
113
-     * are their corresponding Attendee field names
114
-     *
115
-     * @var array
116
-     */
117
-    protected $_system_question_to_attendee_field_name = array(
118
-        EEM_Attendee::system_question_fname    => 'ATT_fname',
119
-        EEM_Attendee::system_question_lname    => 'ATT_lname',
120
-        EEM_Attendee::system_question_email    => 'ATT_email',
121
-        EEM_Attendee::system_question_address  => 'ATT_address',
122
-        EEM_Attendee::system_question_address2 => 'ATT_address2',
123
-        EEM_Attendee::system_question_city     => 'ATT_city',
124
-        EEM_Attendee::system_question_state    => 'STA_ID',
125
-        EEM_Attendee::system_question_country  => 'CNT_ISO',
126
-        EEM_Attendee::system_question_zip      => 'ATT_zip',
127
-        EEM_Attendee::system_question_phone    => 'ATT_phone',
128
-    );
129
-
130
-
131
-
132
-    /**
133
-     *        private constructor to prevent direct creation
134
-     *
135
-     * @Constructor
136
-     * @access protected
137
-     * @param null   $timezone
138
-     * @param Loader $loader
139
-     * @throws EE_Error
140
-     * @throws \InvalidArgumentException
141
-     */
142
-    protected function __construct($timezone = null, Loader $loader)
143
-    {
144
-        $this->singular_item = __('Attendee', 'event_espresso');
145
-        $this->plural_item = __('Attendees', 'event_espresso');
146
-        $this->_tables = array(
147
-            'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
148
-            'Attendee_Meta' => new EE_Secondary_Table('esp_attendee_meta', 'ATTM_ID', 'ATT_ID'),
149
-        );
150
-        $this->_fields = array(
151
-            'Attendee_CPT'  => array(
152
-                'ATT_ID'        => new EE_Primary_Key_Int_Field('ID', __("Attendee ID", "event_espresso")),
153
-                'ATT_full_name' => new EE_Plain_Text_Field('post_title', __("Attendee Full Name", "event_espresso"),
154
-                    false, __("Unknown", "event_espresso")),
155
-                'ATT_bio'       => new EE_Post_Content_Field('post_content', __("Attendee Biography", "event_espresso"),
156
-                    false, __("No Biography Provided", "event_espresso")),
157
-                'ATT_slug'      => new EE_Slug_Field('post_name', __("Attendee URL Slug", "event_espresso"), false),
158
-                'ATT_created'   => new EE_Datetime_Field('post_date', __("Time Attendee Created", "event_espresso"),
159
-                    false, EE_Datetime_Field::now),
160
-                'ATT_short_bio' => new EE_Simple_HTML_Field('post_excerpt',
161
-                    __("Attendee Short Biography", "event_espresso"), true,
162
-                    __("No Biography Provided", "event_espresso")),
163
-                'ATT_modified'  => new EE_Datetime_Field('post_modified',
164
-                    __("Time Attendee Last Modified", "event_espresso"), false, EE_Datetime_Field::now),
165
-                'ATT_author'    => new EE_WP_User_Field('post_author',
166
-                    __("Creator ID of the first Event attended", "event_espresso"), false),
167
-                'ATT_parent'    => new EE_DB_Only_Int_Field('post_parent',
168
-                    __("Parent Attendee (unused)", "event_espresso"), false, 0),
169
-                'post_type'     => new EE_WP_Post_Type_Field('espresso_attendees'),
170
-                // EE_DB_Only_Text_Field('post_type', __("Post Type of Attendee", "event_espresso"), false,'espresso_attendees'),
171
-                'status'        => new EE_WP_Post_Status_Field('post_status', __('Attendee Status', 'event_espresso'),
172
-                    false, 'publish'),
173
-            ),
174
-            'Attendee_Meta' => array(
175
-                'ATTM_ID'      => new EE_DB_Only_Int_Field('ATTM_ID', __('Attendee Meta Row ID', 'event_espresso'),
176
-                    false),
177
-                'ATT_ID_fk'    => new EE_DB_Only_Int_Field('ATT_ID',
178
-                    __("Foreign Key to Attendee in Post Table", "event_espresso"), false),
179
-                'ATT_fname'    => new EE_Plain_Text_Field('ATT_fname', __('First Name', 'event_espresso'), true, ''),
180
-                'ATT_lname'    => new EE_Plain_Text_Field('ATT_lname', __('Last Name', 'event_espresso'), true, ''),
181
-                'ATT_address'  => new EE_Plain_Text_Field('ATT_address', __('Address Part 1', 'event_espresso'), true,
182
-                    ''),
183
-                'ATT_address2' => new EE_Plain_Text_Field('ATT_address2', __('Address Part 2', 'event_espresso'), true,
184
-                    ''),
185
-                'ATT_city'     => new EE_Plain_Text_Field('ATT_city', __('City', 'event_espresso'), true, ''),
186
-                'STA_ID'       => new EE_Foreign_Key_Int_Field('STA_ID', __('State', 'event_espresso'), true, 0,
187
-                    'State'),
188
-                'CNT_ISO'      => new EE_Foreign_Key_String_Field('CNT_ISO', __('Country', 'event_espresso'), true, '',
189
-                    'Country'),
190
-                'ATT_zip'      => new EE_Plain_Text_Field('ATT_zip', __('ZIP/Postal Code', 'event_espresso'), true, ''),
191
-                'ATT_email'    => new EE_Email_Field(
192
-                    'ATT_email',
193
-                    __('Email Address', 'event_espresso'),
194
-                    true,
195
-                    null,
196
-                    $loader
197
-                ),
198
-                'ATT_phone'    => new EE_Plain_Text_Field('ATT_phone', __('Phone', 'event_espresso'), true, ''),
199
-            ),
200
-        );
201
-        $this->_model_relations = array(
202
-            'Registration'      => new EE_Has_Many_Relation(),
203
-            'State'             => new EE_Belongs_To_Relation(),
204
-            'Country'           => new EE_Belongs_To_Relation(),
205
-            'Event'             => new EE_HABTM_Relation('Registration', false),
206
-            'WP_User'           => new EE_Belongs_To_Relation(),
207
-            'Message'           => new EE_Has_Many_Any_Relation(false),
208
-            //allow deletion of attendees even if they have messages in the queue for them.
209
-            'Term_Relationship' => new EE_Has_Many_Relation(),
210
-            'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
211
-        );
212
-        $this->_caps_slug = 'contacts';
213
-        parent::__construct($timezone);
214
-    }
215
-
216
-
217
-
218
-    /**
219
-     * Gets the name of the field on the attendee model corresponding to the system question string
220
-     * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
221
-     *
222
-     * @param string $system_question_string
223
-     * @return string|null if not found
224
-     */
225
-    public function get_attendee_field_for_system_question($system_question_string)
226
-    {
227
-        return isset($this->_system_question_to_attendee_field_name[$system_question_string])
228
-            ? $this->_system_question_to_attendee_field_name[$system_question_string] : null;
229
-    }
230
-
231
-
232
-
233
-    /**
234
-     * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
235
-     * @return array
236
-     */
237
-    public function system_question_to_attendee_field_mapping(){
238
-        return $this->_system_question_to_attendee_field_name;
239
-    }
240
-
241
-
242
-
243
-    /**
244
-     * Gets all the attendees for a transaction (by using the esp_registration as a join table)
245
-     *
246
-     * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
247
-     * @return EE_Attendee[]
248
-     */
249
-    public function get_attendees_for_transaction($transaction_id_or_obj)
250
-    {
251
-        return $this->get_all(array(
252
-            array(
253
-                'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
254
-                    ? $transaction_id_or_obj->ID() : $transaction_id_or_obj,
255
-            ),
256
-        ));
257
-    }
258
-
259
-
260
-
261
-    /**
262
-     *        retrieve  a single attendee from db via their ID
263
-     *
264
-     * @access        public
265
-     * @param        $ATT_ID
266
-     * @return        mixed        array on success, FALSE on fail
267
-     * @deprecated
268
-     */
269
-    public function get_attendee_by_ID($ATT_ID = false)
270
-    {
271
-        // retrieve a particular EE_Attendee
272
-        return $this->get_one_by_ID($ATT_ID);
273
-    }
274
-
275
-
276
-
277
-    /**
278
-     *        retrieve  a single attendee from db via their ID
279
-     *
280
-     * @access        public
281
-     * @param        array $where_cols_n_values
282
-     * @return        mixed        array on success, FALSE on fail
283
-     */
284
-    public function get_attendee($where_cols_n_values = array())
285
-    {
286
-        if (empty($where_cols_n_values)) {
287
-            return false;
288
-        }
289
-        $attendee = $this->get_all(array($where_cols_n_values));
290
-        if ( ! empty($attendee)) {
291
-            return array_shift($attendee);
292
-        } else {
293
-            return false;
294
-        }
295
-    }
296
-
297
-
298
-
299
-    /**
300
-     *        Search for an existing Attendee record in the DB
301
-     *
302
-     * @access        public
303
-     * @param array $where_cols_n_values
304
-     * @return bool|mixed
305
-     */
306
-    public function find_existing_attendee($where_cols_n_values = null)
307
-    {
308
-        // search by combo of first and last names plus the email address
309
-        $attendee_data_keys = array(
310
-            'ATT_fname' => $this->_ATT_fname,
311
-            'ATT_lname' => $this->_ATT_lname,
312
-            'ATT_email' => $this->_ATT_email,
313
-        );
314
-        // no search params means attendee object already exists.
315
-        $where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values) ? $where_cols_n_values
316
-            : $attendee_data_keys;
317
-        $valid_data = true;
318
-        // check for required values
319
-        $valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
320
-            ? $valid_data : false;
321
-        $valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
322
-            ? $valid_data : false;
323
-        $valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
324
-            ? $valid_data : false;
325
-        if ($valid_data) {
326
-            $attendee = $this->get_attendee($where_cols_n_values);
327
-            if ($attendee instanceof EE_Attendee) {
328
-                return $attendee;
329
-            }
330
-        }
331
-        return false;
332
-    }
333
-
334
-
335
-
336
-    /**
337
-     * Takes an incoming array of EE_Registration ids and sends back a list of corresponding non duplicate
338
-     * EE_Attendee objects.
339
-     *
340
-     * @since    4.3.0
341
-     * @param  array $ids array of EE_Registration ids
342
-     * @return  EE_Attendee[]
343
-     */
344
-    public function get_array_of_contacts_from_reg_ids($ids)
345
-    {
346
-        $ids = (array)$ids;
347
-        $_where = array(
348
-            'Registration.REG_ID' => array('in', $ids),
349
-        );
350
-        return $this->get_all(array($_where));
351
-    }
50
+	/**
51
+	 * @deprecated
52
+	 */
53
+	const address2_question_id = 5;
54
+
55
+
56
+	/**
57
+	 * @deprecated
58
+	 */
59
+	const city_question_id = 6;
60
+
61
+
62
+	/**
63
+	 * @deprecated
64
+	 */
65
+	const state_question_id = 7;
66
+
67
+
68
+	/**
69
+	 * @deprecated
70
+	 */
71
+	const country_question_id = 8;
72
+
73
+
74
+	/**
75
+	 * @deprecated
76
+	 */
77
+	const zip_question_id = 9;
78
+
79
+
80
+	/**
81
+	 * @deprecated
82
+	 */
83
+	const phone_question_id = 10;
84
+
85
+	/**
86
+	 * When looking for questions that correspond to attendee fields,
87
+	 * look for the question with this QST_system value.
88
+	 * These replace the old constants like EEM_Attendee::*_question_id
89
+	 */
90
+	const system_question_fname    = 'fname';
91
+
92
+	const system_question_lname    = 'lname';
93
+
94
+	const system_question_email    = 'email';
95
+
96
+	const system_question_address  = 'address';
97
+
98
+	const system_question_address2 = 'address2';
99
+
100
+	const system_question_city     = 'city';
101
+
102
+	const system_question_state    = 'state';
103
+
104
+	const system_question_country  = 'country';
105
+
106
+	const system_question_zip      = 'zip';
107
+
108
+	const system_question_phone    = 'phone';
109
+
110
+	/**
111
+	 * Keys are all the EEM_Attendee::system_question_* constants, which are
112
+	 * also all the values of QST_system in the questions table, and values
113
+	 * are their corresponding Attendee field names
114
+	 *
115
+	 * @var array
116
+	 */
117
+	protected $_system_question_to_attendee_field_name = array(
118
+		EEM_Attendee::system_question_fname    => 'ATT_fname',
119
+		EEM_Attendee::system_question_lname    => 'ATT_lname',
120
+		EEM_Attendee::system_question_email    => 'ATT_email',
121
+		EEM_Attendee::system_question_address  => 'ATT_address',
122
+		EEM_Attendee::system_question_address2 => 'ATT_address2',
123
+		EEM_Attendee::system_question_city     => 'ATT_city',
124
+		EEM_Attendee::system_question_state    => 'STA_ID',
125
+		EEM_Attendee::system_question_country  => 'CNT_ISO',
126
+		EEM_Attendee::system_question_zip      => 'ATT_zip',
127
+		EEM_Attendee::system_question_phone    => 'ATT_phone',
128
+	);
129
+
130
+
131
+
132
+	/**
133
+	 *        private constructor to prevent direct creation
134
+	 *
135
+	 * @Constructor
136
+	 * @access protected
137
+	 * @param null   $timezone
138
+	 * @param Loader $loader
139
+	 * @throws EE_Error
140
+	 * @throws \InvalidArgumentException
141
+	 */
142
+	protected function __construct($timezone = null, Loader $loader)
143
+	{
144
+		$this->singular_item = __('Attendee', 'event_espresso');
145
+		$this->plural_item = __('Attendees', 'event_espresso');
146
+		$this->_tables = array(
147
+			'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
148
+			'Attendee_Meta' => new EE_Secondary_Table('esp_attendee_meta', 'ATTM_ID', 'ATT_ID'),
149
+		);
150
+		$this->_fields = array(
151
+			'Attendee_CPT'  => array(
152
+				'ATT_ID'        => new EE_Primary_Key_Int_Field('ID', __("Attendee ID", "event_espresso")),
153
+				'ATT_full_name' => new EE_Plain_Text_Field('post_title', __("Attendee Full Name", "event_espresso"),
154
+					false, __("Unknown", "event_espresso")),
155
+				'ATT_bio'       => new EE_Post_Content_Field('post_content', __("Attendee Biography", "event_espresso"),
156
+					false, __("No Biography Provided", "event_espresso")),
157
+				'ATT_slug'      => new EE_Slug_Field('post_name', __("Attendee URL Slug", "event_espresso"), false),
158
+				'ATT_created'   => new EE_Datetime_Field('post_date', __("Time Attendee Created", "event_espresso"),
159
+					false, EE_Datetime_Field::now),
160
+				'ATT_short_bio' => new EE_Simple_HTML_Field('post_excerpt',
161
+					__("Attendee Short Biography", "event_espresso"), true,
162
+					__("No Biography Provided", "event_espresso")),
163
+				'ATT_modified'  => new EE_Datetime_Field('post_modified',
164
+					__("Time Attendee Last Modified", "event_espresso"), false, EE_Datetime_Field::now),
165
+				'ATT_author'    => new EE_WP_User_Field('post_author',
166
+					__("Creator ID of the first Event attended", "event_espresso"), false),
167
+				'ATT_parent'    => new EE_DB_Only_Int_Field('post_parent',
168
+					__("Parent Attendee (unused)", "event_espresso"), false, 0),
169
+				'post_type'     => new EE_WP_Post_Type_Field('espresso_attendees'),
170
+				// EE_DB_Only_Text_Field('post_type', __("Post Type of Attendee", "event_espresso"), false,'espresso_attendees'),
171
+				'status'        => new EE_WP_Post_Status_Field('post_status', __('Attendee Status', 'event_espresso'),
172
+					false, 'publish'),
173
+			),
174
+			'Attendee_Meta' => array(
175
+				'ATTM_ID'      => new EE_DB_Only_Int_Field('ATTM_ID', __('Attendee Meta Row ID', 'event_espresso'),
176
+					false),
177
+				'ATT_ID_fk'    => new EE_DB_Only_Int_Field('ATT_ID',
178
+					__("Foreign Key to Attendee in Post Table", "event_espresso"), false),
179
+				'ATT_fname'    => new EE_Plain_Text_Field('ATT_fname', __('First Name', 'event_espresso'), true, ''),
180
+				'ATT_lname'    => new EE_Plain_Text_Field('ATT_lname', __('Last Name', 'event_espresso'), true, ''),
181
+				'ATT_address'  => new EE_Plain_Text_Field('ATT_address', __('Address Part 1', 'event_espresso'), true,
182
+					''),
183
+				'ATT_address2' => new EE_Plain_Text_Field('ATT_address2', __('Address Part 2', 'event_espresso'), true,
184
+					''),
185
+				'ATT_city'     => new EE_Plain_Text_Field('ATT_city', __('City', 'event_espresso'), true, ''),
186
+				'STA_ID'       => new EE_Foreign_Key_Int_Field('STA_ID', __('State', 'event_espresso'), true, 0,
187
+					'State'),
188
+				'CNT_ISO'      => new EE_Foreign_Key_String_Field('CNT_ISO', __('Country', 'event_espresso'), true, '',
189
+					'Country'),
190
+				'ATT_zip'      => new EE_Plain_Text_Field('ATT_zip', __('ZIP/Postal Code', 'event_espresso'), true, ''),
191
+				'ATT_email'    => new EE_Email_Field(
192
+					'ATT_email',
193
+					__('Email Address', 'event_espresso'),
194
+					true,
195
+					null,
196
+					$loader
197
+				),
198
+				'ATT_phone'    => new EE_Plain_Text_Field('ATT_phone', __('Phone', 'event_espresso'), true, ''),
199
+			),
200
+		);
201
+		$this->_model_relations = array(
202
+			'Registration'      => new EE_Has_Many_Relation(),
203
+			'State'             => new EE_Belongs_To_Relation(),
204
+			'Country'           => new EE_Belongs_To_Relation(),
205
+			'Event'             => new EE_HABTM_Relation('Registration', false),
206
+			'WP_User'           => new EE_Belongs_To_Relation(),
207
+			'Message'           => new EE_Has_Many_Any_Relation(false),
208
+			//allow deletion of attendees even if they have messages in the queue for them.
209
+			'Term_Relationship' => new EE_Has_Many_Relation(),
210
+			'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
211
+		);
212
+		$this->_caps_slug = 'contacts';
213
+		parent::__construct($timezone);
214
+	}
215
+
216
+
217
+
218
+	/**
219
+	 * Gets the name of the field on the attendee model corresponding to the system question string
220
+	 * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
221
+	 *
222
+	 * @param string $system_question_string
223
+	 * @return string|null if not found
224
+	 */
225
+	public function get_attendee_field_for_system_question($system_question_string)
226
+	{
227
+		return isset($this->_system_question_to_attendee_field_name[$system_question_string])
228
+			? $this->_system_question_to_attendee_field_name[$system_question_string] : null;
229
+	}
230
+
231
+
232
+
233
+	/**
234
+	 * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
235
+	 * @return array
236
+	 */
237
+	public function system_question_to_attendee_field_mapping(){
238
+		return $this->_system_question_to_attendee_field_name;
239
+	}
240
+
241
+
242
+
243
+	/**
244
+	 * Gets all the attendees for a transaction (by using the esp_registration as a join table)
245
+	 *
246
+	 * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
247
+	 * @return EE_Attendee[]
248
+	 */
249
+	public function get_attendees_for_transaction($transaction_id_or_obj)
250
+	{
251
+		return $this->get_all(array(
252
+			array(
253
+				'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
254
+					? $transaction_id_or_obj->ID() : $transaction_id_or_obj,
255
+			),
256
+		));
257
+	}
258
+
259
+
260
+
261
+	/**
262
+	 *        retrieve  a single attendee from db via their ID
263
+	 *
264
+	 * @access        public
265
+	 * @param        $ATT_ID
266
+	 * @return        mixed        array on success, FALSE on fail
267
+	 * @deprecated
268
+	 */
269
+	public function get_attendee_by_ID($ATT_ID = false)
270
+	{
271
+		// retrieve a particular EE_Attendee
272
+		return $this->get_one_by_ID($ATT_ID);
273
+	}
274
+
275
+
276
+
277
+	/**
278
+	 *        retrieve  a single attendee from db via their ID
279
+	 *
280
+	 * @access        public
281
+	 * @param        array $where_cols_n_values
282
+	 * @return        mixed        array on success, FALSE on fail
283
+	 */
284
+	public function get_attendee($where_cols_n_values = array())
285
+	{
286
+		if (empty($where_cols_n_values)) {
287
+			return false;
288
+		}
289
+		$attendee = $this->get_all(array($where_cols_n_values));
290
+		if ( ! empty($attendee)) {
291
+			return array_shift($attendee);
292
+		} else {
293
+			return false;
294
+		}
295
+	}
296
+
297
+
298
+
299
+	/**
300
+	 *        Search for an existing Attendee record in the DB
301
+	 *
302
+	 * @access        public
303
+	 * @param array $where_cols_n_values
304
+	 * @return bool|mixed
305
+	 */
306
+	public function find_existing_attendee($where_cols_n_values = null)
307
+	{
308
+		// search by combo of first and last names plus the email address
309
+		$attendee_data_keys = array(
310
+			'ATT_fname' => $this->_ATT_fname,
311
+			'ATT_lname' => $this->_ATT_lname,
312
+			'ATT_email' => $this->_ATT_email,
313
+		);
314
+		// no search params means attendee object already exists.
315
+		$where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values) ? $where_cols_n_values
316
+			: $attendee_data_keys;
317
+		$valid_data = true;
318
+		// check for required values
319
+		$valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
320
+			? $valid_data : false;
321
+		$valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
322
+			? $valid_data : false;
323
+		$valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
324
+			? $valid_data : false;
325
+		if ($valid_data) {
326
+			$attendee = $this->get_attendee($where_cols_n_values);
327
+			if ($attendee instanceof EE_Attendee) {
328
+				return $attendee;
329
+			}
330
+		}
331
+		return false;
332
+	}
333
+
334
+
335
+
336
+	/**
337
+	 * Takes an incoming array of EE_Registration ids and sends back a list of corresponding non duplicate
338
+	 * EE_Attendee objects.
339
+	 *
340
+	 * @since    4.3.0
341
+	 * @param  array $ids array of EE_Registration ids
342
+	 * @return  EE_Attendee[]
343
+	 */
344
+	public function get_array_of_contacts_from_reg_ids($ids)
345
+	{
346
+		$ids = (array)$ids;
347
+		$_where = array(
348
+			'Registration.REG_ID' => array('in', $ids),
349
+		);
350
+		return $this->get_all(array($_where));
351
+	}
352 352
 
353 353
 
354 354
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
4 4
     exit('No direct script access allowed');
5 5
 }
6
-require_once(EE_MODELS . 'EEM_Base.model.php');
6
+require_once(EE_MODELS.'EEM_Base.model.php');
7 7
 
8 8
 
9 9
 
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
      * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
235 235
      * @return array
236 236
      */
237
-    public function system_question_to_attendee_field_mapping(){
237
+    public function system_question_to_attendee_field_mapping() {
238 238
         return $this->_system_question_to_attendee_field_name;
239 239
     }
240 240
 
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
      */
344 344
     public function get_array_of_contacts_from_reg_ids($ids)
345 345
     {
346
-        $ids = (array)$ids;
346
+        $ids = (array) $ids;
347 347
         $_where = array(
348 348
             'Registration.REG_ID' => array('in', $ids),
349 349
         );
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +5884 added lines, -5884 removed lines patch added patch discarded remove patch
@@ -28,5892 +28,5892 @@
 block discarded – undo
28 28
 abstract class EEM_Base extends EE_Base
29 29
 {
30 30
 
31
-    /**
32
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
33
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
34
-     * They almost always WILL NOT, but it's not necessarily a requirement.
35
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
36
-     *
37
-     * @var boolean
38
-     */
39
-    private $_values_already_prepared_by_model_object = 0;
40
-
41
-    /**
42
-     * when $_values_already_prepared_by_model_object equals this, we assume
43
-     * the data is just like form input that needs to have the model fields'
44
-     * prepare_for_set and prepare_for_use_in_db called on it
45
-     */
46
-    const not_prepared_by_model_object = 0;
47
-
48
-    /**
49
-     * when $_values_already_prepared_by_model_object equals this, we
50
-     * assume this value is coming from a model object and doesn't need to have
51
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
52
-     */
53
-    const prepared_by_model_object = 1;
54
-
55
-    /**
56
-     * when $_values_already_prepared_by_model_object equals this, we assume
57
-     * the values are already to be used in the database (ie no processing is done
58
-     * on them by the model's fields)
59
-     */
60
-    const prepared_for_use_in_db = 2;
61
-
62
-
63
-    protected $singular_item = 'Item';
64
-
65
-    protected $plural_item   = 'Items';
66
-
67
-    /**
68
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
69
-     */
70
-    protected $_tables;
71
-
72
-    /**
73
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
74
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
75
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
76
-     *
77
-     * @var \EE_Model_Field_Base[][] $_fields
78
-     */
79
-    protected $_fields;
80
-
81
-    /**
82
-     * array of different kinds of relations
83
-     *
84
-     * @var \EE_Model_Relation_Base[] $_model_relations
85
-     */
86
-    protected $_model_relations;
87
-
88
-    /**
89
-     * @var \EE_Index[] $_indexes
90
-     */
91
-    protected $_indexes = array();
92
-
93
-    /**
94
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
95
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
96
-     * by setting the same columns as used in these queries in the query yourself.
97
-     *
98
-     * @var EE_Default_Where_Conditions
99
-     */
100
-    protected $_default_where_conditions_strategy;
101
-
102
-    /**
103
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
104
-     * This is particularly useful when you want something between 'none' and 'default'
105
-     *
106
-     * @var EE_Default_Where_Conditions
107
-     */
108
-    protected $_minimum_where_conditions_strategy;
109
-
110
-    /**
111
-     * String describing how to find the "owner" of this model's objects.
112
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
113
-     * But when there isn't, this indicates which related model, or transiently-related model,
114
-     * has the foreign key to the wp_users table.
115
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
116
-     * related to events, and events have a foreign key to wp_users.
117
-     * On EEM_Transaction, this would be 'Transaction.Event'
118
-     *
119
-     * @var string
120
-     */
121
-    protected $_model_chain_to_wp_user = '';
122
-
123
-    /**
124
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
125
-     * don't need it (particularly CPT models)
126
-     *
127
-     * @var bool
128
-     */
129
-    protected $_ignore_where_strategy = false;
130
-
131
-    /**
132
-     * String used in caps relating to this model. Eg, if the caps relating to this
133
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
134
-     *
135
-     * @var string. If null it hasn't been initialized yet. If false then we
136
-     * have indicated capabilities don't apply to this
137
-     */
138
-    protected $_caps_slug = null;
139
-
140
-    /**
141
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
142
-     * and next-level keys are capability names, and each's value is a
143
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
144
-     * they specify which context to use (ie, frontend, backend, edit or delete)
145
-     * and then each capability in the corresponding sub-array that they're missing
146
-     * adds the where conditions onto the query.
147
-     *
148
-     * @var array
149
-     */
150
-    protected $_cap_restrictions = array(
151
-        self::caps_read       => array(),
152
-        self::caps_read_admin => array(),
153
-        self::caps_edit       => array(),
154
-        self::caps_delete     => array(),
155
-    );
156
-
157
-    /**
158
-     * Array defining which cap restriction generators to use to create default
159
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
160
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
161
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
162
-     * automatically set this to false (not just null).
163
-     *
164
-     * @var EE_Restriction_Generator_Base[]
165
-     */
166
-    protected $_cap_restriction_generators = array();
167
-
168
-    /**
169
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
170
-     */
171
-    const caps_read       = 'read';
172
-
173
-    const caps_read_admin = 'read_admin';
174
-
175
-    const caps_edit       = 'edit';
176
-
177
-    const caps_delete     = 'delete';
178
-
179
-    /**
180
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
181
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
182
-     * maps to 'read' because when looking for relevant permissions we're going to use
183
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
184
-     *
185
-     * @var array
186
-     */
187
-    protected $_cap_contexts_to_cap_action_map = array(
188
-        self::caps_read       => 'read',
189
-        self::caps_read_admin => 'read',
190
-        self::caps_edit       => 'edit',
191
-        self::caps_delete     => 'delete',
192
-    );
193
-
194
-    /**
195
-     * Timezone
196
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
197
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
198
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
199
-     * EE_Datetime_Field data type will have access to it.
200
-     *
201
-     * @var string
202
-     */
203
-    protected $_timezone;
204
-
205
-
206
-    /**
207
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
208
-     * multisite.
209
-     *
210
-     * @var int
211
-     */
212
-    protected static $_model_query_blog_id;
213
-
214
-    /**
215
-     * A copy of _fields, except the array keys are the model names pointed to by
216
-     * the field
217
-     *
218
-     * @var EE_Model_Field_Base[]
219
-     */
220
-    private $_cache_foreign_key_to_fields = array();
221
-
222
-    /**
223
-     * Cached list of all the fields on the model, indexed by their name
224
-     *
225
-     * @var EE_Model_Field_Base[]
226
-     */
227
-    private $_cached_fields = null;
228
-
229
-    /**
230
-     * Cached list of all the fields on the model, except those that are
231
-     * marked as only pertinent to the database
232
-     *
233
-     * @var EE_Model_Field_Base[]
234
-     */
235
-    private $_cached_fields_non_db_only = null;
236
-
237
-    /**
238
-     * A cached reference to the primary key for quick lookup
239
-     *
240
-     * @var EE_Model_Field_Base
241
-     */
242
-    private $_primary_key_field = null;
243
-
244
-    /**
245
-     * Flag indicating whether this model has a primary key or not
246
-     *
247
-     * @var boolean
248
-     */
249
-    protected $_has_primary_key_field = null;
250
-
251
-    /**
252
-     * Whether or not this model is based off a table in WP core only (CPTs should set
253
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
254
-     * This should be true for models that deal with data that should exist independent of EE.
255
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
256
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
257
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
258
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
259
-     * @var boolean
260
-     */
261
-    protected $_wp_core_model = false;
262
-
263
-    /**
264
-     *    List of valid operators that can be used for querying.
265
-     * The keys are all operators we'll accept, the values are the real SQL
266
-     * operators used
267
-     *
268
-     * @var array
269
-     */
270
-    protected $_valid_operators = array(
271
-        '='           => '=',
272
-        '<='          => '<=',
273
-        '<'           => '<',
274
-        '>='          => '>=',
275
-        '>'           => '>',
276
-        '!='          => '!=',
277
-        'LIKE'        => 'LIKE',
278
-        'like'        => 'LIKE',
279
-        'NOT_LIKE'    => 'NOT LIKE',
280
-        'not_like'    => 'NOT LIKE',
281
-        'NOT LIKE'    => 'NOT LIKE',
282
-        'not like'    => 'NOT LIKE',
283
-        'IN'          => 'IN',
284
-        'in'          => 'IN',
285
-        'NOT_IN'      => 'NOT IN',
286
-        'not_in'      => 'NOT IN',
287
-        'NOT IN'      => 'NOT IN',
288
-        'not in'      => 'NOT IN',
289
-        'between'     => 'BETWEEN',
290
-        'BETWEEN'     => 'BETWEEN',
291
-        'IS_NOT_NULL' => 'IS NOT NULL',
292
-        'is_not_null' => 'IS NOT NULL',
293
-        'IS NOT NULL' => 'IS NOT NULL',
294
-        'is not null' => 'IS NOT NULL',
295
-        'IS_NULL'     => 'IS NULL',
296
-        'is_null'     => 'IS NULL',
297
-        'IS NULL'     => 'IS NULL',
298
-        'is null'     => 'IS NULL',
299
-        'REGEXP'      => 'REGEXP',
300
-        'regexp'      => 'REGEXP',
301
-        'NOT_REGEXP'  => 'NOT REGEXP',
302
-        'not_regexp'  => 'NOT REGEXP',
303
-        'NOT REGEXP'  => 'NOT REGEXP',
304
-        'not regexp'  => 'NOT REGEXP',
305
-    );
306
-
307
-    /**
308
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
309
-     *
310
-     * @var array
311
-     */
312
-    protected $_in_style_operators = array('IN', 'NOT IN');
313
-
314
-    /**
315
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
316
-     * '12-31-2012'"
317
-     *
318
-     * @var array
319
-     */
320
-    protected $_between_style_operators = array('BETWEEN');
321
-
322
-    /**
323
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
324
-     * @var array
325
-     */
326
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
327
-    /**
328
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
329
-     * on a join table.
330
-     *
331
-     * @var array
332
-     */
333
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
334
-
335
-    /**
336
-     * Allowed values for $query_params['order'] for ordering in queries
337
-     *
338
-     * @var array
339
-     */
340
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
341
-
342
-    /**
343
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
344
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
345
-     *
346
-     * @var array
347
-     */
348
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
349
-
350
-    /**
351
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
352
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
353
-     *
354
-     * @var array
355
-     */
356
-    private $_allowed_query_params = array(
357
-        0,
358
-        'limit',
359
-        'order_by',
360
-        'group_by',
361
-        'having',
362
-        'force_join',
363
-        'order',
364
-        'on_join_limit',
365
-        'default_where_conditions',
366
-        'caps',
367
-    );
368
-
369
-    /**
370
-     * All the data types that can be used in $wpdb->prepare statements.
371
-     *
372
-     * @var array
373
-     */
374
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
375
-
376
-    /**
377
-     *    EE_Registry Object
378
-     *
379
-     * @var    object
380
-     * @access    protected
381
-     */
382
-    protected $EE = null;
383
-
384
-
385
-    /**
386
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
387
-     *
388
-     * @var int
389
-     */
390
-    protected $_show_next_x_db_queries = 0;
391
-
392
-    /**
393
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
394
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
395
-     *
396
-     * @var array
397
-     */
398
-    protected $_custom_selections = array();
399
-
400
-    /**
401
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
402
-     * caches every model object we've fetched from the DB on this request
403
-     *
404
-     * @var array
405
-     */
406
-    protected $_entity_map;
407
-
408
-    /**
409
-     * @var Loader $loader
410
-     */
411
-    private static $loader;
412
-
413
-
414
-    /**
415
-     * constant used to show EEM_Base has not yet verified the db on this http request
416
-     */
417
-    const db_verified_none = 0;
418
-
419
-    /**
420
-     * constant used to show EEM_Base has verified the EE core db on this http request,
421
-     * but not the addons' dbs
422
-     */
423
-    const db_verified_core = 1;
424
-
425
-    /**
426
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
427
-     * the EE core db too)
428
-     */
429
-    const db_verified_addons = 2;
430
-
431
-    /**
432
-     * indicates whether an EEM_Base child has already re-verified the DB
433
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
434
-     * looking like EEM_Base::db_verified_*
435
-     *
436
-     * @var int - 0 = none, 1 = core, 2 = addons
437
-     */
438
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
439
-
440
-    /**
441
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
442
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
443
-     *        registrations for non-trashed tickets for non-trashed datetimes)
444
-     */
445
-    const default_where_conditions_all = 'all';
446
-
447
-    /**
448
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
449
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
450
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
451
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
452
-     *        models which share tables with other models, this can return data for the wrong model.
453
-     */
454
-    const default_where_conditions_this_only = 'this_model_only';
455
-
456
-    /**
457
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
458
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
459
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
460
-     */
461
-    const default_where_conditions_others_only = 'other_models_only';
462
-
463
-    /**
464
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
465
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
466
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
467
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
468
-     *        (regardless of whether those events and venues are trashed)
469
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
470
-     *        events.
471
-     */
472
-    const default_where_conditions_minimum_all = 'minimum';
473
-
474
-    /**
475
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
476
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
477
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
478
-     *        not)
479
-     */
480
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
481
-
482
-    /**
483
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
484
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
485
-     *        it's possible it will return table entries for other models. You should use
486
-     *        EEM_Base::default_where_conditions_minimum_all instead.
487
-     */
488
-    const default_where_conditions_none = 'none';
489
-
490
-
491
-
492
-    /**
493
-     * About all child constructors:
494
-     * they should define the _tables, _fields and _model_relations arrays.
495
-     * Should ALWAYS be called after child constructor.
496
-     * In order to make the child constructors to be as simple as possible, this parent constructor
497
-     * finalizes constructing all the object's attributes.
498
-     * Generally, rather than requiring a child to code
499
-     * $this->_tables = array(
500
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
501
-     *        ...);
502
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
503
-     * each EE_Table has a function to set the table's alias after the constructor, using
504
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
505
-     * do something similar.
506
-     *
507
-     * @param null $timezone
508
-     * @throws \EE_Error
509
-     */
510
-    protected function __construct($timezone = null)
511
-    {
512
-        // check that the model has not been loaded too soon
513
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
514
-            throw new EE_Error (
515
-                sprintf(
516
-                    __('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.',
517
-                        'event_espresso'),
518
-                    get_class($this)
519
-                )
520
-            );
521
-        }
522
-        /**
523
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
524
-         */
525
-        if (empty(EEM_Base::$_model_query_blog_id)) {
526
-            EEM_Base::set_model_query_blog_id();
527
-        }
528
-        /**
529
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
530
-         * just use EE_Register_Model_Extension
531
-         *
532
-         * @var EE_Table_Base[] $_tables
533
-         */
534
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
535
-        foreach ($this->_tables as $table_alias => $table_obj) {
536
-            /** @var $table_obj EE_Table_Base */
537
-            $table_obj->_construct_finalize_with_alias($table_alias);
538
-            if ($table_obj instanceof EE_Secondary_Table) {
539
-                /** @var $table_obj EE_Secondary_Table */
540
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
541
-            }
542
-        }
543
-        /**
544
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
545
-         * EE_Register_Model_Extension
546
-         *
547
-         * @param EE_Model_Field_Base[] $_fields
548
-         */
549
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
550
-        $this->_invalidate_field_caches();
551
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
552
-            if (! array_key_exists($table_alias, $this->_tables)) {
553
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
554
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
555
-            }
556
-            foreach ($fields_for_table as $field_name => $field_obj) {
557
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
558
-                //primary key field base has a slightly different _construct_finalize
559
-                /** @var $field_obj EE_Model_Field_Base */
560
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
561
-            }
562
-        }
563
-        // everything is related to Extra_Meta
564
-        if (get_class($this) !== 'EEM_Extra_Meta') {
565
-            //make extra meta related to everything, but don't block deleting things just
566
-            //because they have related extra meta info. For now just orphan those extra meta
567
-            //in the future we should automatically delete them
568
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
569
-        }
570
-        //and change logs
571
-        if (get_class($this) !== 'EEM_Change_Log') {
572
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
573
-        }
574
-        /**
575
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
576
-         * EE_Register_Model_Extension
577
-         *
578
-         * @param EE_Model_Relation_Base[] $_model_relations
579
-         */
580
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
581
-            $this->_model_relations);
582
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
583
-            /** @var $relation_obj EE_Model_Relation_Base */
584
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
585
-        }
586
-        foreach ($this->_indexes as $index_name => $index_obj) {
587
-            /** @var $index_obj EE_Index */
588
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
589
-        }
590
-        $this->set_timezone($timezone);
591
-        //finalize default where condition strategy, or set default
592
-        if (! $this->_default_where_conditions_strategy) {
593
-            //nothing was set during child constructor, so set default
594
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
595
-        }
596
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
597
-        if (! $this->_minimum_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
602
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
603
-        //to indicate to NOT set it, set it to the logical default
604
-        if ($this->_caps_slug === null) {
605
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
606
-        }
607
-        //initialize the standard cap restriction generators if none were specified by the child constructor
608
-        if ($this->_cap_restriction_generators !== false) {
609
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
610
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
611
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
612
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
613
-                        new EE_Restriction_Generator_Protected(),
614
-                        $cap_context,
615
-                        $this
616
-                    );
617
-                }
618
-            }
619
-        }
620
-        //if there are cap restriction generators, use them to make the default cap restrictions
621
-        if ($this->_cap_restriction_generators !== false) {
622
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
623
-                if (! $generator_object) {
624
-                    continue;
625
-                }
626
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
627
-                    throw new EE_Error(
628
-                        sprintf(
629
-                            __('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.',
630
-                                'event_espresso'),
631
-                            $context,
632
-                            $this->get_this_model_name()
633
-                        )
634
-                    );
635
-                }
636
-                $action = $this->cap_action_for_context($context);
637
-                if (! $generator_object->construction_finalized()) {
638
-                    $generator_object->_construct_finalize($this, $action);
639
-                }
640
-            }
641
-        }
642
-        do_action('AHEE__' . get_class($this) . '__construct__end');
643
-    }
644
-
645
-
646
-
647
-    /**
648
-     * Used to set the $_model_query_blog_id static property.
649
-     *
650
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
651
-     *                      value for get_current_blog_id() will be used.
652
-     */
653
-    public static function set_model_query_blog_id($blog_id = 0)
654
-    {
655
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
656
-    }
657
-
658
-
659
-
660
-    /**
661
-     * Returns whatever is set as the internal $model_query_blog_id.
662
-     *
663
-     * @return int
664
-     */
665
-    public static function get_model_query_blog_id()
666
-    {
667
-        return EEM_Base::$_model_query_blog_id;
668
-    }
669
-
670
-
671
-
672
-    /**
673
-     *        This function is a singleton method used to instantiate the Espresso_model object
674
-     *
675
-     * @access public
676
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
677
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
678
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
679
-     *                         timezone in the 'timezone_string' wp option)
680
-     * @return static (as in the concrete child class)
681
-     */
682
-    public static function instance($timezone = null)
683
-    {
684
-        // check if instance of Espresso_model already exists
685
-        if (! static::$_instance instanceof static) {
686
-            // instantiate Espresso_model
687
-            static::$_instance = new static($timezone, self::getLoader());
688
-        }
689
-        //we might have a timezone set, let set_timezone decide what to do with it
690
-        static::$_instance->set_timezone($timezone);
691
-        // Espresso_model object
692
-        return static::$_instance;
693
-    }
694
-
695
-
696
-
697
-    /**
698
-     * resets the model and returns it
699
-     *
700
-     * @param null | string $timezone
701
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
702
-     * all its properties reset; if it wasn't instantiated, returns null)
703
-     */
704
-    public static function reset($timezone = null)
705
-    {
706
-        if (static::$_instance instanceof EEM_Base) {
707
-            //let's try to NOT swap out the current instance for a new one
708
-            //because if someone has a reference to it, we can't remove their reference
709
-            //so it's best to keep using the same reference, but change the original object
710
-            //reset all its properties to their original values as defined in the class
711
-            $r = new ReflectionClass(get_class(static::$_instance));
712
-            $static_properties = $r->getStaticProperties();
713
-            foreach ($r->getDefaultProperties() as $property => $value) {
714
-                //don't set instance to null like it was originally,
715
-                //but it's static anyways, and we're ignoring static properties (for now at least)
716
-                if (! isset($static_properties[$property])) {
717
-                    static::$_instance->{$property} = $value;
718
-                }
719
-            }
720
-            //and then directly call its constructor again, like we would if we
721
-            //were creating a new one
722
-            static::$_instance->__construct($timezone, self::getLoader());
723
-            return self::instance();
724
-        }
725
-        return null;
726
-    }
727
-
728
-
729
-
730
-    private static function getLoader()
731
-    {
732
-        if(! self::$loader instanceof Loader) {
733
-            self::$loader = new Loader();
734
-        }
735
-        return self::$loader;
736
-    }
737
-
738
-    /**
739
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
740
-     *
741
-     * @param  boolean $translated return localized strings or JUST the array.
742
-     * @return array
743
-     * @throws \EE_Error
744
-     */
745
-    public function status_array($translated = false)
746
-    {
747
-        if (! array_key_exists('Status', $this->_model_relations)) {
748
-            return array();
749
-        }
750
-        $model_name = $this->get_this_model_name();
751
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
752
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
753
-        $status_array = array();
754
-        foreach ($stati as $status) {
755
-            $status_array[$status->ID()] = $status->get('STS_code');
756
-        }
757
-        return $translated
758
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
759
-            : $status_array;
760
-    }
761
-
762
-
763
-
764
-    /**
765
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
766
-     *
767
-     * @param array $query_params             {
768
-     * @var array $0 (where) array {
769
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
770
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
771
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
772
-     *                                        conditions based on related models (and even
773
-     *                                        models-related-to-related-models) prepend the model's name onto the field
774
-     *                                        name. Eg,
775
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
776
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
777
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
778
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
779
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
780
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
781
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
782
-     *                                        to Venues (even when each of those models actually consisted of two
783
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
784
-     *                                        just having
785
-     *                                        "Venue.VNU_ID", you could have
786
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
787
-     *                                        events are related to Registrations, which are related to Attendees). You
788
-     *                                        can take it even further with
789
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
790
-     *                                        (from the default of '='), change the value to an numerically-indexed
791
-     *                                        array, where the first item in the list is the operator. eg: array(
792
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
793
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
794
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
795
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
796
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
797
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
798
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
799
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
800
-     *                                        the value is a field, simply provide a third array item (true) to the
801
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
802
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
803
-     *                                        Note: you can also use related model field names like you would any other
804
-     *                                        field name. eg:
805
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
806
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
807
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
808
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
809
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
810
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
811
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
812
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
813
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
814
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
815
-     *                                        "stick" until you specify an AND. eg
816
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
817
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
818
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
819
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
820
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
821
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
822
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
823
-     *                                        too, eg:
824
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
825
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
826
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
827
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
828
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
829
-     *                                        the OFFSET, the 2nd is the LIMIT
830
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
831
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
832
-     *                                        following format array('on_join_limit'
833
-     *                                        => array( 'table_alias', array(1,2) ) ).
834
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
835
-     *                                        values are either 'ASC' or 'DESC'.
836
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
837
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
838
-     *                                        DESC..." respectively. Like the
839
-     *                                        'where' conditions, these fields can be on related models. Eg
840
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
841
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
842
-     *                                        Attendee, Price, Datetime, etc.)
843
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
844
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
845
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
846
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
847
-     *                                        order by the primary key. Eg,
848
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
849
-     *                                        //(will join with the Datetime model's table(s) and order by its field
850
-     *                                        DTT_EVT_start) or
851
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
852
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
853
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
854
-     *                                        'group_by'=>'VNU_ID', or
855
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
856
-     *                                        if no
857
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
858
-     *                                        model's primary key (or combined primary keys). This avoids some
859
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
860
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
861
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
862
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
863
-     *                                        results)
864
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
865
-     *                                        array where values are models to be joined in the query.Eg
866
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
867
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
868
-     *                                        probably only want to do this in hopes of increasing efficiency, as
869
-     *                                        related models which belongs to the current model
870
-     *                                        (ie, the current model has a foreign key to them, like how Registration
871
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
872
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
873
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
874
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
875
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
876
-     *                                        default where conditions set it to 'other_models_only'. If you only want
877
-     *                                        this model's default where conditions added to the query, use
878
-     *                                        'this_model_only'. If you want to use all default where conditions
879
-     *                                        (default), set to 'all'.
880
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
881
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
882
-     *                                        everything? Or should we only show the current user items they should be
883
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
884
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
885
-     *                                        }
886
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
887
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
888
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
889
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
890
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
891
-     *                                        array( array(
892
-     *                                        'OR'=>array(
893
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
894
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
895
-     *                                        )
896
-     *                                        ),
897
-     *                                        'limit'=>10,
898
-     *                                        'group_by'=>'TXN_ID'
899
-     *                                        ));
900
-     *                                        get all the answers to the question titled "shirt size" for event with id
901
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
902
-     *                                        'Question.QST_display_text'=>'shirt size',
903
-     *                                        'Registration.Event.EVT_ID'=>12
904
-     *                                        ),
905
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
906
-     *                                        ));
907
-     * @throws \EE_Error
908
-     */
909
-    public function get_all($query_params = array())
910
-    {
911
-        if (isset($query_params['limit'])
912
-            && ! isset($query_params['group_by'])
913
-        ) {
914
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
915
-        }
916
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
917
-    }
918
-
919
-
920
-
921
-    /**
922
-     * Modifies the query parameters so we only get back model objects
923
-     * that "belong" to the current user
924
-     *
925
-     * @param array $query_params @see EEM_Base::get_all()
926
-     * @return array like EEM_Base::get_all
927
-     */
928
-    public function alter_query_params_to_only_include_mine($query_params = array())
929
-    {
930
-        $wp_user_field_name = $this->wp_user_field_name();
931
-        if ($wp_user_field_name) {
932
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
933
-        }
934
-        return $query_params;
935
-    }
936
-
937
-
938
-
939
-    /**
940
-     * Returns the name of the field's name that points to the WP_User table
941
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
942
-     * foreign key to the WP_User table)
943
-     *
944
-     * @return string|boolean string on success, boolean false when there is no
945
-     * foreign key to the WP_User table
946
-     */
947
-    public function wp_user_field_name()
948
-    {
949
-        try {
950
-            if (! empty($this->_model_chain_to_wp_user)) {
951
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
952
-                $last_model_name = end($models_to_follow_to_wp_users);
953
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
954
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
955
-            } else {
956
-                $model_with_fk_to_wp_users = $this;
957
-                $model_chain_to_wp_user = '';
958
-            }
959
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
960
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
961
-        } catch (EE_Error $e) {
962
-            return false;
963
-        }
964
-    }
965
-
966
-
967
-
968
-    /**
969
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
970
-     * (or transiently-related model) has a foreign key to the wp_users table;
971
-     * useful for finding if model objects of this type are 'owned' by the current user.
972
-     * This is an empty string when the foreign key is on this model and when it isn't,
973
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
974
-     * (or transiently-related model)
975
-     *
976
-     * @return string
977
-     */
978
-    public function model_chain_to_wp_user()
979
-    {
980
-        return $this->_model_chain_to_wp_user;
981
-    }
982
-
983
-
984
-
985
-    /**
986
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
987
-     * like how registrations don't have a foreign key to wp_users, but the
988
-     * events they are for are), or is unrelated to wp users.
989
-     * generally available
990
-     *
991
-     * @return boolean
992
-     */
993
-    public function is_owned()
994
-    {
995
-        if ($this->model_chain_to_wp_user()) {
996
-            return true;
997
-        } else {
998
-            try {
999
-                $this->get_foreign_key_to('WP_User');
1000
-                return true;
1001
-            } catch (EE_Error $e) {
1002
-                return false;
1003
-            }
1004
-        }
1005
-    }
1006
-
1007
-
1008
-
1009
-    /**
1010
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1011
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1012
-     * the model)
1013
-     *
1014
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1015
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1016
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1017
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1018
-     *                                  override this and set the select to "*", or a specific column name, like
1019
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1020
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1021
-     *                                  the aliases used to refer to this selection, and values are to be
1022
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1023
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1024
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1025
-     * @throws \EE_Error
1026
-     */
1027
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1028
-    {
1029
-        // remember the custom selections, if any, and type cast as array
1030
-        // (unless $columns_to_select is an object, then just set as an empty array)
1031
-        // Note: (array) 'some string' === array( 'some string' )
1032
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1033
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1034
-        $select_expressions = $columns_to_select !== null
1035
-            ? $this->_construct_select_from_input($columns_to_select)
1036
-            : $this->_construct_default_select_sql($model_query_info);
1037
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1038
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1039
-    }
1040
-
1041
-
1042
-
1043
-    /**
1044
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1045
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1046
-     * take care of joins, field preparation etc.
1047
-     *
1048
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1049
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1050
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1051
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1052
-     *                                  override this and set the select to "*", or a specific column name, like
1053
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1054
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1055
-     *                                  the aliases used to refer to this selection, and values are to be
1056
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1057
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1058
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1059
-     * @throws \EE_Error
1060
-     */
1061
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1062
-    {
1063
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1064
-    }
1065
-
1066
-
1067
-
1068
-    /**
1069
-     * For creating a custom select statement
1070
-     *
1071
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1072
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1073
-     *                                 SQL, and 1=>is the datatype
1074
-     * @throws EE_Error
1075
-     * @return string
1076
-     */
1077
-    private function _construct_select_from_input($columns_to_select)
1078
-    {
1079
-        if (is_array($columns_to_select)) {
1080
-            $select_sql_array = array();
1081
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1082
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1083
-                    throw new EE_Error(
1084
-                        sprintf(
1085
-                            __(
1086
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1087
-                                "event_espresso"
1088
-                            ),
1089
-                            $selection_and_datatype,
1090
-                            $alias
1091
-                        )
1092
-                    );
1093
-                }
1094
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1095
-                    throw new EE_Error(
1096
-                        sprintf(
1097
-                            __(
1098
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1099
-                                "event_espresso"
1100
-                            ),
1101
-                            $selection_and_datatype[1],
1102
-                            $selection_and_datatype[0],
1103
-                            $alias,
1104
-                            implode(",", $this->_valid_wpdb_data_types)
1105
-                        )
1106
-                    );
1107
-                }
1108
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1109
-            }
1110
-            $columns_to_select_string = implode(", ", $select_sql_array);
1111
-        } else {
1112
-            $columns_to_select_string = $columns_to_select;
1113
-        }
1114
-        return $columns_to_select_string;
1115
-    }
1116
-
1117
-
1118
-
1119
-    /**
1120
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1121
-     *
1122
-     * @return string
1123
-     * @throws \EE_Error
1124
-     */
1125
-    public function primary_key_name()
1126
-    {
1127
-        return $this->get_primary_key_field()->get_name();
1128
-    }
1129
-
1130
-
1131
-
1132
-    /**
1133
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1134
-     * If there is no primary key on this model, $id is treated as primary key string
1135
-     *
1136
-     * @param mixed $id int or string, depending on the type of the model's primary key
1137
-     * @return EE_Base_Class
1138
-     */
1139
-    public function get_one_by_ID($id)
1140
-    {
1141
-        if ($this->get_from_entity_map($id)) {
1142
-            return $this->get_from_entity_map($id);
1143
-        }
1144
-        return $this->get_one(
1145
-            $this->alter_query_params_to_restrict_by_ID(
1146
-                $id,
1147
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1148
-            )
1149
-        );
1150
-    }
1151
-
1152
-
1153
-
1154
-    /**
1155
-     * Alters query parameters to only get items with this ID are returned.
1156
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1157
-     * or could just be a simple primary key ID
1158
-     *
1159
-     * @param int   $id
1160
-     * @param array $query_params
1161
-     * @return array of normal query params, @see EEM_Base::get_all
1162
-     * @throws \EE_Error
1163
-     */
1164
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1165
-    {
1166
-        if (! isset($query_params[0])) {
1167
-            $query_params[0] = array();
1168
-        }
1169
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1170
-        if ($conditions_from_id === null) {
1171
-            $query_params[0][$this->primary_key_name()] = $id;
1172
-        } else {
1173
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1174
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1175
-        }
1176
-        return $query_params;
1177
-    }
1178
-
1179
-
1180
-
1181
-    /**
1182
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1183
-     * array. If no item is found, null is returned.
1184
-     *
1185
-     * @param array $query_params like EEM_Base's $query_params variable.
1186
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1187
-     * @throws \EE_Error
1188
-     */
1189
-    public function get_one($query_params = array())
1190
-    {
1191
-        if (! is_array($query_params)) {
1192
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1193
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1194
-                    gettype($query_params)), '4.6.0');
1195
-            $query_params = array();
1196
-        }
1197
-        $query_params['limit'] = 1;
1198
-        $items = $this->get_all($query_params);
1199
-        if (empty($items)) {
1200
-            return null;
1201
-        } else {
1202
-            return array_shift($items);
1203
-        }
1204
-    }
1205
-
1206
-
1207
-
1208
-    /**
1209
-     * Returns the next x number of items in sequence from the given value as
1210
-     * found in the database matching the given query conditions.
1211
-     *
1212
-     * @param mixed $current_field_value    Value used for the reference point.
1213
-     * @param null  $field_to_order_by      What field is used for the
1214
-     *                                      reference point.
1215
-     * @param int   $limit                  How many to return.
1216
-     * @param array $query_params           Extra conditions on the query.
1217
-     * @param null  $columns_to_select      If left null, then an array of
1218
-     *                                      EE_Base_Class objects is returned,
1219
-     *                                      otherwise you can indicate just the
1220
-     *                                      columns you want returned.
1221
-     * @return EE_Base_Class[]|array
1222
-     * @throws \EE_Error
1223
-     */
1224
-    public function next_x(
1225
-        $current_field_value,
1226
-        $field_to_order_by = null,
1227
-        $limit = 1,
1228
-        $query_params = array(),
1229
-        $columns_to_select = null
1230
-    ) {
1231
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1232
-            $columns_to_select);
1233
-    }
1234
-
1235
-
1236
-
1237
-    /**
1238
-     * Returns the previous x number of items in sequence from the given value
1239
-     * as found in the database matching the given query conditions.
1240
-     *
1241
-     * @param mixed $current_field_value    Value used for the reference point.
1242
-     * @param null  $field_to_order_by      What field is used for the
1243
-     *                                      reference point.
1244
-     * @param int   $limit                  How many to return.
1245
-     * @param array $query_params           Extra conditions on the query.
1246
-     * @param null  $columns_to_select      If left null, then an array of
1247
-     *                                      EE_Base_Class objects is returned,
1248
-     *                                      otherwise you can indicate just the
1249
-     *                                      columns you want returned.
1250
-     * @return EE_Base_Class[]|array
1251
-     * @throws \EE_Error
1252
-     */
1253
-    public function previous_x(
1254
-        $current_field_value,
1255
-        $field_to_order_by = null,
1256
-        $limit = 1,
1257
-        $query_params = array(),
1258
-        $columns_to_select = null
1259
-    ) {
1260
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1261
-            $columns_to_select);
1262
-    }
1263
-
1264
-
1265
-
1266
-    /**
1267
-     * Returns the next item in sequence from the given value as found in the
1268
-     * database matching the given query conditions.
1269
-     *
1270
-     * @param mixed $current_field_value    Value used for the reference point.
1271
-     * @param null  $field_to_order_by      What field is used for the
1272
-     *                                      reference point.
1273
-     * @param array $query_params           Extra conditions on the query.
1274
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1275
-     *                                      object is returned, otherwise you
1276
-     *                                      can indicate just the columns you
1277
-     *                                      want and a single array indexed by
1278
-     *                                      the columns will be returned.
1279
-     * @return EE_Base_Class|null|array()
1280
-     * @throws \EE_Error
1281
-     */
1282
-    public function next(
1283
-        $current_field_value,
1284
-        $field_to_order_by = null,
1285
-        $query_params = array(),
1286
-        $columns_to_select = null
1287
-    ) {
1288
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1289
-            $columns_to_select);
1290
-        return empty($results) ? null : reset($results);
1291
-    }
1292
-
1293
-
1294
-
1295
-    /**
1296
-     * Returns the previous item in sequence from the given value as found in
1297
-     * the database matching the given query conditions.
1298
-     *
1299
-     * @param mixed $current_field_value    Value used for the reference point.
1300
-     * @param null  $field_to_order_by      What field is used for the
1301
-     *                                      reference point.
1302
-     * @param array $query_params           Extra conditions on the query.
1303
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1304
-     *                                      object is returned, otherwise you
1305
-     *                                      can indicate just the columns you
1306
-     *                                      want and a single array indexed by
1307
-     *                                      the columns will be returned.
1308
-     * @return EE_Base_Class|null|array()
1309
-     * @throws EE_Error
1310
-     */
1311
-    public function previous(
1312
-        $current_field_value,
1313
-        $field_to_order_by = null,
1314
-        $query_params = array(),
1315
-        $columns_to_select = null
1316
-    ) {
1317
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1318
-            $columns_to_select);
1319
-        return empty($results) ? null : reset($results);
1320
-    }
1321
-
1322
-
1323
-
1324
-    /**
1325
-     * Returns the a consecutive number of items in sequence from the given
1326
-     * value as found in the database matching the given query conditions.
1327
-     *
1328
-     * @param mixed  $current_field_value   Value used for the reference point.
1329
-     * @param string $operand               What operand is used for the sequence.
1330
-     * @param string $field_to_order_by     What field is used for the reference point.
1331
-     * @param int    $limit                 How many to return.
1332
-     * @param array  $query_params          Extra conditions on the query.
1333
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1334
-     *                                      otherwise you can indicate just the columns you want returned.
1335
-     * @return EE_Base_Class[]|array
1336
-     * @throws EE_Error
1337
-     */
1338
-    protected function _get_consecutive(
1339
-        $current_field_value,
1340
-        $operand = '>',
1341
-        $field_to_order_by = null,
1342
-        $limit = 1,
1343
-        $query_params = array(),
1344
-        $columns_to_select = null
1345
-    ) {
1346
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1347
-        if (empty($field_to_order_by)) {
1348
-            if ($this->has_primary_key_field()) {
1349
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1350
-            } else {
1351
-                if (WP_DEBUG) {
1352
-                    throw new EE_Error(__('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).',
1353
-                        'event_espresso'));
1354
-                }
1355
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1356
-                return array();
1357
-            }
1358
-        }
1359
-        if (! is_array($query_params)) {
1360
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1361
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1362
-                    gettype($query_params)), '4.6.0');
1363
-            $query_params = array();
1364
-        }
1365
-        //let's add the where query param for consecutive look up.
1366
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1367
-        $query_params['limit'] = $limit;
1368
-        //set direction
1369
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1370
-        $query_params['order_by'] = $operand === '>'
1371
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1372
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1373
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1374
-        if (empty($columns_to_select)) {
1375
-            return $this->get_all($query_params);
1376
-        } else {
1377
-            //getting just the fields
1378
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1379
-        }
1380
-    }
1381
-
1382
-
1383
-
1384
-    /**
1385
-     * This sets the _timezone property after model object has been instantiated.
1386
-     *
1387
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1388
-     */
1389
-    public function set_timezone($timezone)
1390
-    {
1391
-        if ($timezone !== null) {
1392
-            $this->_timezone = $timezone;
1393
-        }
1394
-        //note we need to loop through relations and set the timezone on those objects as well.
1395
-        foreach ($this->_model_relations as $relation) {
1396
-            $relation->set_timezone($timezone);
1397
-        }
1398
-        //and finally we do the same for any datetime fields
1399
-        foreach ($this->_fields as $field) {
1400
-            if ($field instanceof EE_Datetime_Field) {
1401
-                $field->set_timezone($timezone);
1402
-            }
1403
-        }
1404
-    }
1405
-
1406
-
1407
-
1408
-    /**
1409
-     * This just returns whatever is set for the current timezone.
1410
-     *
1411
-     * @access public
1412
-     * @return string
1413
-     */
1414
-    public function get_timezone()
1415
-    {
1416
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1417
-        if (empty($this->_timezone)) {
1418
-            foreach ($this->_fields as $field) {
1419
-                if ($field instanceof EE_Datetime_Field) {
1420
-                    $this->set_timezone($field->get_timezone());
1421
-                    break;
1422
-                }
1423
-            }
1424
-        }
1425
-        //if timezone STILL empty then return the default timezone for the site.
1426
-        if (empty($this->_timezone)) {
1427
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1428
-        }
1429
-        return $this->_timezone;
1430
-    }
1431
-
1432
-
1433
-
1434
-    /**
1435
-     * This returns the date formats set for the given field name and also ensures that
1436
-     * $this->_timezone property is set correctly.
1437
-     *
1438
-     * @since 4.6.x
1439
-     * @param string $field_name The name of the field the formats are being retrieved for.
1440
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1441
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1442
-     * @return array formats in an array with the date format first, and the time format last.
1443
-     */
1444
-    public function get_formats_for($field_name, $pretty = false)
1445
-    {
1446
-        $field_settings = $this->field_settings_for($field_name);
1447
-        //if not a valid EE_Datetime_Field then throw error
1448
-        if (! $field_settings instanceof EE_Datetime_Field) {
1449
-            throw new EE_Error(sprintf(__('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.',
1450
-                'event_espresso'), $field_name));
1451
-        }
1452
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1453
-        //the field.
1454
-        $this->_timezone = $field_settings->get_timezone();
1455
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1456
-    }
1457
-
1458
-
1459
-
1460
-    /**
1461
-     * This returns the current time in a format setup for a query on this model.
1462
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1463
-     * it will return:
1464
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1465
-     *  NOW
1466
-     *  - or a unix timestamp (equivalent to time())
1467
-     *
1468
-     * @since 4.6.x
1469
-     * @param string $field_name       The field the current time is needed for.
1470
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1471
-     *                                 formatted string matching the set format for the field in the set timezone will
1472
-     *                                 be returned.
1473
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1474
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1475
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1476
-     *                                 exception is triggered.
1477
-     */
1478
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1479
-    {
1480
-        $formats = $this->get_formats_for($field_name);
1481
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1482
-        if ($timestamp) {
1483
-            return $DateTime->format('U');
1484
-        }
1485
-        //not returning timestamp, so return formatted string in timezone.
1486
-        switch ($what) {
1487
-            case 'time' :
1488
-                return $DateTime->format($formats[1]);
1489
-                break;
1490
-            case 'date' :
1491
-                return $DateTime->format($formats[0]);
1492
-                break;
1493
-            default :
1494
-                return $DateTime->format(implode(' ', $formats));
1495
-                break;
1496
-        }
1497
-    }
1498
-
1499
-
1500
-
1501
-    /**
1502
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1503
-     * for the model are.  Returns a DateTime object.
1504
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1505
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1506
-     * ignored.
1507
-     *
1508
-     * @param string $field_name      The field being setup.
1509
-     * @param string $timestring      The date time string being used.
1510
-     * @param string $incoming_format The format for the time string.
1511
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1512
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1513
-     *                                format is
1514
-     *                                'U', this is ignored.
1515
-     * @return DateTime
1516
-     * @throws \EE_Error
1517
-     */
1518
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1519
-    {
1520
-        //just using this to ensure the timezone is set correctly internally
1521
-        $this->get_formats_for($field_name);
1522
-        //load EEH_DTT_Helper
1523
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1524
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1525
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1526
-    }
1527
-
1528
-
1529
-
1530
-    /**
1531
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1532
-     *
1533
-     * @return EE_Table_Base[]
1534
-     */
1535
-    public function get_tables()
1536
-    {
1537
-        return $this->_tables;
1538
-    }
1539
-
1540
-
1541
-
1542
-    /**
1543
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1544
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1545
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1546
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1547
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1548
-     * model object with EVT_ID = 1
1549
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1550
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1551
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1552
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1553
-     * are not specified)
1554
-     *
1555
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1556
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1557
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1558
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1559
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1560
-     *                                         ID=34, we'd use this method as follows:
1561
-     *                                         EEM_Transaction::instance()->update(
1562
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1563
-     *                                         array(array('TXN_ID'=>34)));
1564
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1565
-     *                                         in client code into what's expected to be stored on each field. Eg,
1566
-     *                                         consider updating Question's QST_admin_label field is of type
1567
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1568
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1569
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1570
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1571
-     *                                         TRUE, it is assumed that you've already called
1572
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1573
-     *                                         malicious javascript. However, if
1574
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1575
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1576
-     *                                         and every other field, before insertion. We provide this parameter
1577
-     *                                         because model objects perform their prepare_for_set function on all
1578
-     *                                         their values, and so don't need to be called again (and in many cases,
1579
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1580
-     *                                         prepare_for_set method...)
1581
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1582
-     *                                         in this model's entity map according to $fields_n_values that match
1583
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1584
-     *                                         by setting this to FALSE, but be aware that model objects being used
1585
-     *                                         could get out-of-sync with the database
1586
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1587
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1588
-     *                                         bad)
1589
-     * @throws \EE_Error
1590
-     */
1591
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1592
-    {
1593
-        if (! is_array($query_params)) {
1594
-            EE_Error::doing_it_wrong('EEM_Base::update',
1595
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1596
-                    gettype($query_params)), '4.6.0');
1597
-            $query_params = array();
1598
-        }
1599
-        /**
1600
-         * Action called before a model update call has been made.
1601
-         *
1602
-         * @param EEM_Base $model
1603
-         * @param array    $fields_n_values the updated fields and their new values
1604
-         * @param array    $query_params    @see EEM_Base::get_all()
1605
-         */
1606
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1607
-        /**
1608
-         * Filters the fields about to be updated given the query parameters. You can provide the
1609
-         * $query_params to $this->get_all() to find exactly which records will be updated
1610
-         *
1611
-         * @param array    $fields_n_values fields and their new values
1612
-         * @param EEM_Base $model           the model being queried
1613
-         * @param array    $query_params    see EEM_Base::get_all()
1614
-         */
1615
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1616
-            $query_params);
1617
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1618
-        //to do that, for each table, verify that it's PK isn't null.
1619
-        $tables = $this->get_tables();
1620
-        //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
1621
-        //NOTE: we should make this code more efficient by NOT querying twice
1622
-        //before the real update, but that needs to first go through ALPHA testing
1623
-        //as it's dangerous. says Mike August 8 2014
1624
-        //we want to make sure the default_where strategy is ignored
1625
-        $this->_ignore_where_strategy = true;
1626
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1627
-        foreach ($wpdb_select_results as $wpdb_result) {
1628
-            // type cast stdClass as array
1629
-            $wpdb_result = (array)$wpdb_result;
1630
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1631
-            if ($this->has_primary_key_field()) {
1632
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1633
-            } else {
1634
-                //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)
1635
-                $main_table_pk_value = null;
1636
-            }
1637
-            //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
1638
-            //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
1639
-            if (count($tables) > 1) {
1640
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1641
-                //in that table, and so we'll want to insert one
1642
-                foreach ($tables as $table_obj) {
1643
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1644
-                    //if there is no private key for this table on the results, it means there's no entry
1645
-                    //in this table, right? so insert a row in the current table, using any fields available
1646
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1647
-                           && $wpdb_result[$this_table_pk_column])
1648
-                    ) {
1649
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1650
-                            $main_table_pk_value);
1651
-                        //if we died here, report the error
1652
-                        if (! $success) {
1653
-                            return false;
1654
-                        }
1655
-                    }
1656
-                }
1657
-            }
1658
-            //				//and now check that if we have cached any models by that ID on the model, that
1659
-            //				//they also get updated properly
1660
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1661
-            //				if( $model_object ){
1662
-            //					foreach( $fields_n_values as $field => $value ){
1663
-            //						$model_object->set($field, $value);
1664
-            //let's make sure default_where strategy is followed now
1665
-            $this->_ignore_where_strategy = false;
1666
-        }
1667
-        //if we want to keep model objects in sync, AND
1668
-        //if this wasn't called from a model object (to update itself)
1669
-        //then we want to make sure we keep all the existing
1670
-        //model objects in sync with the db
1671
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1672
-            if ($this->has_primary_key_field()) {
1673
-                $model_objs_affected_ids = $this->get_col($query_params);
1674
-            } else {
1675
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1676
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1677
-                $model_objs_affected_ids = array();
1678
-                foreach ($models_affected_key_columns as $row) {
1679
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1680
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1681
-                }
1682
-            }
1683
-            if (! $model_objs_affected_ids) {
1684
-                //wait wait wait- if nothing was affected let's stop here
1685
-                return 0;
1686
-            }
1687
-            foreach ($model_objs_affected_ids as $id) {
1688
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1689
-                if ($model_obj_in_entity_map) {
1690
-                    foreach ($fields_n_values as $field => $new_value) {
1691
-                        $model_obj_in_entity_map->set($field, $new_value);
1692
-                    }
1693
-                }
1694
-            }
1695
-            //if there is a primary key on this model, we can now do a slight optimization
1696
-            if ($this->has_primary_key_field()) {
1697
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1698
-                $query_params = array(
1699
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1700
-                    'limit'                    => count($model_objs_affected_ids),
1701
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1702
-                );
1703
-            }
1704
-        }
1705
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1706
-        $SQL = "UPDATE "
1707
-               . $model_query_info->get_full_join_sql()
1708
-               . " SET "
1709
-               . $this->_construct_update_sql($fields_n_values)
1710
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1711
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1712
-        /**
1713
-         * Action called after a model update call has been made.
1714
-         *
1715
-         * @param EEM_Base $model
1716
-         * @param array    $fields_n_values the updated fields and their new values
1717
-         * @param array    $query_params    @see EEM_Base::get_all()
1718
-         * @param int      $rows_affected
1719
-         */
1720
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1721
-        return $rows_affected;//how many supposedly got updated
1722
-    }
1723
-
1724
-
1725
-
1726
-    /**
1727
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1728
-     * are teh values of the field specified (or by default the primary key field)
1729
-     * that matched the query params. Note that you should pass the name of the
1730
-     * model FIELD, not the database table's column name.
1731
-     *
1732
-     * @param array  $query_params @see EEM_Base::get_all()
1733
-     * @param string $field_to_select
1734
-     * @return array just like $wpdb->get_col()
1735
-     * @throws \EE_Error
1736
-     */
1737
-    public function get_col($query_params = array(), $field_to_select = null)
1738
-    {
1739
-        if ($field_to_select) {
1740
-            $field = $this->field_settings_for($field_to_select);
1741
-        } elseif ($this->has_primary_key_field()) {
1742
-            $field = $this->get_primary_key_field();
1743
-        } else {
1744
-            //no primary key, just grab the first column
1745
-            $field = reset($this->field_settings());
1746
-        }
1747
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1748
-        $select_expressions = $field->get_qualified_column();
1749
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1750
-        return $this->_do_wpdb_query('get_col', array($SQL));
1751
-    }
1752
-
1753
-
1754
-
1755
-    /**
1756
-     * Returns a single column value for a single row from the database
1757
-     *
1758
-     * @param array  $query_params    @see EEM_Base::get_all()
1759
-     * @param string $field_to_select @see EEM_Base::get_col()
1760
-     * @return string
1761
-     * @throws \EE_Error
1762
-     */
1763
-    public function get_var($query_params = array(), $field_to_select = null)
1764
-    {
1765
-        $query_params['limit'] = 1;
1766
-        $col = $this->get_col($query_params, $field_to_select);
1767
-        if (! empty($col)) {
1768
-            return reset($col);
1769
-        } else {
1770
-            return null;
1771
-        }
1772
-    }
1773
-
1774
-
1775
-
1776
-    /**
1777
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1778
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1779
-     * injection, but currently no further filtering is done
1780
-     *
1781
-     * @global      $wpdb
1782
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1783
-     *                               be updated to in the DB
1784
-     * @return string of SQL
1785
-     * @throws \EE_Error
1786
-     */
1787
-    public function _construct_update_sql($fields_n_values)
1788
-    {
1789
-        /** @type WPDB $wpdb */
1790
-        global $wpdb;
1791
-        $cols_n_values = array();
1792
-        foreach ($fields_n_values as $field_name => $value) {
1793
-            $field_obj = $this->field_settings_for($field_name);
1794
-            //if the value is NULL, we want to assign the value to that.
1795
-            //wpdb->prepare doesn't really handle that properly
1796
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1797
-            $value_sql = $prepared_value === null ? 'NULL'
1798
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1799
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1800
-        }
1801
-        return implode(",", $cols_n_values);
1802
-    }
1803
-
1804
-
1805
-
1806
-    /**
1807
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1808
-     * Performs a HARD delete, meaning the database row should always be removed,
1809
-     * not just have a flag field on it switched
1810
-     * Wrapper for EEM_Base::delete_permanently()
1811
-     *
1812
-     * @param mixed $id
1813
-     * @param boolean $allow_blocking
1814
-     * @return int the number of rows deleted
1815
-     * @throws \EE_Error
1816
-     */
1817
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1818
-    {
1819
-        return $this->delete_permanently(
1820
-            array(
1821
-                array($this->get_primary_key_field()->get_name() => $id),
1822
-                'limit' => 1,
1823
-            ),
1824
-            $allow_blocking
1825
-        );
1826
-    }
1827
-
1828
-
1829
-
1830
-    /**
1831
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1832
-     * Wrapper for EEM_Base::delete()
1833
-     *
1834
-     * @param mixed $id
1835
-     * @param boolean $allow_blocking
1836
-     * @return int the number of rows deleted
1837
-     * @throws \EE_Error
1838
-     */
1839
-    public function delete_by_ID($id, $allow_blocking = true)
1840
-    {
1841
-        return $this->delete(
1842
-            array(
1843
-                array($this->get_primary_key_field()->get_name() => $id),
1844
-                'limit' => 1,
1845
-            ),
1846
-            $allow_blocking
1847
-        );
1848
-    }
1849
-
1850
-
1851
-
1852
-    /**
1853
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1854
-     * meaning if the model has a field that indicates its been "trashed" or
1855
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1856
-     *
1857
-     * @see EEM_Base::delete_permanently
1858
-     * @param array   $query_params
1859
-     * @param boolean $allow_blocking
1860
-     * @return int how many rows got deleted
1861
-     * @throws \EE_Error
1862
-     */
1863
-    public function delete($query_params, $allow_blocking = true)
1864
-    {
1865
-        return $this->delete_permanently($query_params, $allow_blocking);
1866
-    }
1867
-
1868
-
1869
-
1870
-    /**
1871
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1872
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1873
-     * as archived, not actually deleted
1874
-     *
1875
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1876
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1877
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1878
-     *                                deletes regardless of other objects which may depend on it. Its generally
1879
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1880
-     *                                DB
1881
-     * @return int how many rows got deleted
1882
-     * @throws \EE_Error
1883
-     */
1884
-    public function delete_permanently($query_params, $allow_blocking = true)
1885
-    {
1886
-        /**
1887
-         * Action called just before performing a real deletion query. You can use the
1888
-         * model and its $query_params to find exactly which items will be deleted
1889
-         *
1890
-         * @param EEM_Base $model
1891
-         * @param array    $query_params   @see EEM_Base::get_all()
1892
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1893
-         *                                 to block (prevent) this deletion
1894
-         */
1895
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1896
-        //some MySQL databases may be running safe mode, which may restrict
1897
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1898
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1899
-        //to delete them
1900
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1901
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1902
-        if ($deletion_where) {
1903
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1904
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1905
-            $table_aliases = array_keys($this->_tables);
1906
-            $SQL = "DELETE "
1907
-                   . implode(", ", $table_aliases)
1908
-                   . " FROM "
1909
-                   . $model_query_info->get_full_join_sql()
1910
-                   . " WHERE "
1911
-                   . $deletion_where;
1912
-            //		/echo "delete sql:$SQL";
1913
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1914
-        } else {
1915
-            $rows_deleted = 0;
1916
-        }
1917
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1918
-        if ($this->has_primary_key_field()) {
1919
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1920
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1921
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1922
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1923
-                }
1924
-            }
1925
-        }
1926
-        /**
1927
-         * Action called just after performing a real deletion query. Although at this point the
1928
-         * items should have been deleted
1929
-         *
1930
-         * @param EEM_Base $model
1931
-         * @param array    $query_params @see EEM_Base::get_all()
1932
-         * @param int      $rows_deleted
1933
-         */
1934
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1935
-        return $rows_deleted;//how many supposedly got deleted
1936
-    }
1937
-
1938
-
1939
-
1940
-    /**
1941
-     * Checks all the relations that throw error messages when there are blocking related objects
1942
-     * for related model objects. If there are any related model objects on those relations,
1943
-     * adds an EE_Error, and return true
1944
-     *
1945
-     * @param EE_Base_Class|int $this_model_obj_or_id
1946
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1947
-     *                                                 should be ignored when determining whether there are related
1948
-     *                                                 model objects which block this model object's deletion. Useful
1949
-     *                                                 if you know A is related to B and are considering deleting A,
1950
-     *                                                 but want to see if A has any other objects blocking its deletion
1951
-     *                                                 before removing the relation between A and B
1952
-     * @return boolean
1953
-     * @throws \EE_Error
1954
-     */
1955
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1956
-    {
1957
-        //first, if $ignore_this_model_obj was supplied, get its model
1958
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1959
-            $ignored_model = $ignore_this_model_obj->get_model();
1960
-        } else {
1961
-            $ignored_model = null;
1962
-        }
1963
-        //now check all the relations of $this_model_obj_or_id and see if there
1964
-        //are any related model objects blocking it?
1965
-        $is_blocked = false;
1966
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1967
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1968
-                //if $ignore_this_model_obj was supplied, then for the query
1969
-                //on that model needs to be told to ignore $ignore_this_model_obj
1970
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1971
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1972
-                        array(
1973
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1974
-                                '!=',
1975
-                                $ignore_this_model_obj->ID(),
1976
-                            ),
1977
-                        ),
1978
-                    ));
1979
-                } else {
1980
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1981
-                }
1982
-                if ($related_model_objects) {
1983
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1984
-                    $is_blocked = true;
1985
-                }
1986
-            }
1987
-        }
1988
-        return $is_blocked;
1989
-    }
1990
-
1991
-
1992
-
1993
-    /**
1994
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1995
-     * well.
1996
-     *
1997
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1998
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1999
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
2000
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
2001
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
2002
-     *                                      easily corrupt your DB
2003
-     * @throws EE_Error
2004
-     * @return string    everything that comes after the WHERE statement.
2005
-     */
2006
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2007
-    {
2008
-        if ($this->has_primary_key_field()) {
2009
-            $primary_table = $this->_get_main_table();
2010
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2011
-            $other_tables = $this->_get_other_tables();
2012
-            /**
2013
-             * @var EE_Primary_Key_Field_Base[] $other_tables_pk_fields  keys are table aliases
2014
-             */
2015
-            $other_tables_pk_fields = array();
2016
-            /**
2017
-             * @var EE_Primary_Key_Field_Base[] $other_tables_fk_fields EE_Foreign_Key_Field_Base[] keys are table aliases
2018
-             */
2019
-            $other_tables_fk_fields = array();
2020
-            foreach($other_tables as $other_table_alias => $other_table_obj){
2021
-                $other_tables_pk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_pk_column());
2022
-                $other_tables_fk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_fk_column());
2023
-            }
2024
-            $deletes = $query = array();
2025
-            foreach ($objects_for_deletion as $delete_object) {
2026
-                //before we mark this object for deletion,
2027
-                //make sure there's no related objects blocking its deletion (if we're checking)
2028
-                if (
2029
-                    $allow_blocking
2030
-                    && $this->delete_is_blocked_by_related_models(
2031
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
2032
-                    )
2033
-                ) {
2034
-                    continue;
2035
-                }
2036
-                //primary table deletes
2037
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2038
-
2039
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2040
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()],
2041
-                        $primary_table_pk_field
2042
-                    );
2043
-                }
2044
-                //other tables
2045
-                if (! empty($other_tables)) {
2046
-                    foreach ($other_tables as $other_table_alias => $other_table_obj) {
2047
-                        $other_table_pk_field = $other_tables_pk_fields[$other_table_alias];
2048
-                        $other_table_fk_field = $other_tables_fk_fields[$other_table_alias];
2049
-                        //first check if we've got the foreign key column here.
2050
-                        if (isset($delete_object[$other_table_obj->get_fully_qualified_fk_column()])) {
2051
-                            $deletes[$other_table_obj->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2052
-                                $delete_object[$other_table_obj->get_fully_qualified_fk_column()],
2053
-                                $other_table_fk_field
2054
-                            );
2055
-                        }
2056
-                        // wait! it's entirely possible that we'll have a the primary key
2057
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2058
-                        if (isset($delete_object[$other_table_obj->get_fully_qualified_pk_column()])) {
2059
-                            $deletes[$other_table_obj->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2060
-                                $delete_object[$other_table_obj->get_fully_qualified_pk_column()],
2061
-                                $other_table_pk_field
2062
-                            );
2063
-                        }
2064
-                        // finally, it is possible that the fk for this table is found
2065
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2066
-                        if (isset($delete_object[$other_table_obj->get_fully_qualified_pk_on_fk_table()])) {
2067
-                            $deletes[$other_table_obj->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2068
-                                $delete_object[$other_table_obj->get_fully_qualified_pk_column()],
2069
-                                $other_table_pk_field
2070
-                            );
2071
-                        }
2072
-                    }
2073
-                }
2074
-            }
2075
-            //we should have deletes now, so let's just go through and setup the where statement
2076
-            foreach ($deletes as $column => $values) {
2077
-                //make sure we have unique $values;
2078
-                $values = array_unique($values);
2079
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2080
-            }
2081
-            return ! empty($query) ? implode(' AND ', $query) : '';
2082
-        }
2083
-        $combined_primary_key_fields = $this->get_combined_primary_key_fields();
2084
-        if (count($combined_primary_key_fields) > 1) {
2085
-            $ways_to_identify_a_row = array();
2086
-            //note: because there's no primary key, that means nothing else  can be pointing to this model, right?
2087
-            foreach ($objects_for_deletion as $delete_object) {
2088
-                $combined_primary_key_row_values = array();
2089
-                foreach ($combined_primary_key_fields as $field_in_combined_primary_key) {
2090
-                    if ($field_in_combined_primary_key instanceof EE_Model_Field_Base) {
2091
-                        $combined_primary_key_row_values[] = $field_in_combined_primary_key->get_qualified_column()
2092
-                                                           . "="
2093
-                                                           . $delete_object[$field_in_combined_primary_key->get_qualified_column()];
2094
-                    }
2095
-                }
2096
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $combined_primary_key_row_values) . ")";
2097
-            }
2098
-            return implode(" OR ", $ways_to_identify_a_row);
2099
-        } else {
2100
-            //so there's no primary key and no combined key...
2101
-            //sorry, can't help you
2102
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2103
-                "event_espresso"), get_class($this)));
2104
-        }
2105
-    }
2106
-
2107
-
2108
-    /**
2109
-     * Gets the model field by the fully qualified name
2110
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2111
-     * @return EE_Model_Field_Base
2112
-     */
2113
-    public function get_field_by_column($qualified_column_name)
2114
-    {
2115
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2116
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2117
-               return $field_obj;
2118
-           }
2119
-       }
2120
-        throw new EE_Error(
2121
-            sprintf(
2122
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2123
-                $this->get_this_model_name(),
2124
-                $qualified_column_name
2125
-            )
2126
-        );
2127
-    }
2128
-
2129
-
2130
-
2131
-    /**
2132
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2133
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2134
-     * column
2135
-     *
2136
-     * @param array  $query_params   like EEM_Base::get_all's
2137
-     * @param string $field_to_count field on model to count by (not column name)
2138
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2139
-     *                               that by the setting $distinct to TRUE;
2140
-     * @return int
2141
-     * @throws \EE_Error
2142
-     */
2143
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2144
-    {
2145
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2146
-        if ($field_to_count) {
2147
-            $field_obj = $this->field_settings_for($field_to_count);
2148
-            $column_to_count = $field_obj->get_qualified_column();
2149
-        } elseif ($this->has_primary_key_field()) {
2150
-            $pk_field_obj = $this->get_primary_key_field();
2151
-            $column_to_count = $pk_field_obj->get_qualified_column();
2152
-        } else {
2153
-            //there's no primary key
2154
-            //if we're counting distinct items, and there's no primary key,
2155
-            //we need to list out the columns for distinction;
2156
-            //otherwise we can just use star
2157
-            if ($distinct) {
2158
-                $columns_to_use = array();
2159
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2160
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2161
-                }
2162
-                $column_to_count = implode(',', $columns_to_use);
2163
-            } else {
2164
-                $column_to_count = '*';
2165
-            }
2166
-        }
2167
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2168
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2169
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2170
-    }
2171
-
2172
-
2173
-
2174
-    /**
2175
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2176
-     *
2177
-     * @param array  $query_params like EEM_Base::get_all
2178
-     * @param string $field_to_sum name of field (array key in $_fields array)
2179
-     * @return float
2180
-     * @throws \EE_Error
2181
-     */
2182
-    public function sum($query_params, $field_to_sum = null)
2183
-    {
2184
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2185
-        if ($field_to_sum) {
2186
-            $field_obj = $this->field_settings_for($field_to_sum);
2187
-        } else {
2188
-            $field_obj = $this->get_primary_key_field();
2189
-        }
2190
-        $column_to_count = $field_obj->get_qualified_column();
2191
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2192
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2193
-        $data_type = $field_obj->get_wpdb_data_type();
2194
-        if ($data_type === '%d' || $data_type === '%s') {
2195
-            return (float)$return_value;
2196
-        } else {//must be %f
2197
-            return (float)$return_value;
2198
-        }
2199
-    }
2200
-
2201
-
2202
-
2203
-    /**
2204
-     * Just calls the specified method on $wpdb with the given arguments
2205
-     * Consolidates a little extra error handling code
2206
-     *
2207
-     * @param string $wpdb_method
2208
-     * @param array  $arguments_to_provide
2209
-     * @throws EE_Error
2210
-     * @global wpdb  $wpdb
2211
-     * @return mixed
2212
-     */
2213
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2214
-    {
2215
-        //if we're in maintenance mode level 2, DON'T run any queries
2216
-        //because level 2 indicates the database needs updating and
2217
-        //is probably out of sync with the code
2218
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2219
-            throw new EE_Error(sprintf(__("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.",
2220
-                "event_espresso")));
2221
-        }
2222
-        /** @type WPDB $wpdb */
2223
-        global $wpdb;
2224
-        if (! method_exists($wpdb, $wpdb_method)) {
2225
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2226
-                'event_espresso'), $wpdb_method));
2227
-        }
2228
-        if (WP_DEBUG) {
2229
-            $old_show_errors_value = $wpdb->show_errors;
2230
-            $wpdb->show_errors(false);
2231
-        }
2232
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2233
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2234
-        if (WP_DEBUG) {
2235
-            $wpdb->show_errors($old_show_errors_value);
2236
-            if (! empty($wpdb->last_error)) {
2237
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2238
-            } elseif ($result === false) {
2239
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2240
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2241
-            }
2242
-        } elseif ($result === false) {
2243
-            EE_Error::add_error(
2244
-                sprintf(
2245
-                    __('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"',
2246
-                        'event_espresso'),
2247
-                    $wpdb_method,
2248
-                    var_export($arguments_to_provide, true),
2249
-                    $wpdb->last_error
2250
-                ),
2251
-                __FILE__,
2252
-                __FUNCTION__,
2253
-                __LINE__
2254
-            );
2255
-        }
2256
-        return $result;
2257
-    }
2258
-
2259
-
2260
-
2261
-    /**
2262
-     * Attempts to run the indicated WPDB method with the provided arguments,
2263
-     * and if there's an error tries to verify the DB is correct. Uses
2264
-     * the static property EEM_Base::$_db_verification_level to determine whether
2265
-     * we should try to fix the EE core db, the addons, or just give up
2266
-     *
2267
-     * @param string $wpdb_method
2268
-     * @param array  $arguments_to_provide
2269
-     * @return mixed
2270
-     */
2271
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2272
-    {
2273
-        /** @type WPDB $wpdb */
2274
-        global $wpdb;
2275
-        $wpdb->last_error = null;
2276
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2277
-        // was there an error running the query? but we don't care on new activations
2278
-        // (we're going to setup the DB anyway on new activations)
2279
-        if (($result === false || ! empty($wpdb->last_error))
2280
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2281
-        ) {
2282
-            switch (EEM_Base::$_db_verification_level) {
2283
-                case EEM_Base::db_verified_none :
2284
-                    // let's double-check core's DB
2285
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2286
-                    break;
2287
-                case EEM_Base::db_verified_core :
2288
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2289
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2290
-                    break;
2291
-                case EEM_Base::db_verified_addons :
2292
-                    // ummmm... you in trouble
2293
-                    return $result;
2294
-                    break;
2295
-            }
2296
-            if (! empty($error_message)) {
2297
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2298
-                trigger_error($error_message);
2299
-            }
2300
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2301
-        }
2302
-        return $result;
2303
-    }
2304
-
2305
-
2306
-
2307
-    /**
2308
-     * Verifies the EE core database is up-to-date and records that we've done it on
2309
-     * EEM_Base::$_db_verification_level
2310
-     *
2311
-     * @param string $wpdb_method
2312
-     * @param array  $arguments_to_provide
2313
-     * @return string
2314
-     */
2315
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2316
-    {
2317
-        /** @type WPDB $wpdb */
2318
-        global $wpdb;
2319
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2320
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2321
-        $error_message = sprintf(
2322
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2323
-                'event_espresso'),
2324
-            $wpdb->last_error,
2325
-            $wpdb_method,
2326
-            wp_json_encode($arguments_to_provide)
2327
-        );
2328
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2329
-        return $error_message;
2330
-    }
2331
-
2332
-
2333
-
2334
-    /**
2335
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2336
-     * EEM_Base::$_db_verification_level
2337
-     *
2338
-     * @param $wpdb_method
2339
-     * @param $arguments_to_provide
2340
-     * @return string
2341
-     */
2342
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2343
-    {
2344
-        /** @type WPDB $wpdb */
2345
-        global $wpdb;
2346
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2347
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2348
-        $error_message = sprintf(
2349
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2350
-                'event_espresso'),
2351
-            $wpdb->last_error,
2352
-            $wpdb_method,
2353
-            wp_json_encode($arguments_to_provide)
2354
-        );
2355
-        EE_System::instance()->initialize_addons();
2356
-        return $error_message;
2357
-    }
2358
-
2359
-
2360
-
2361
-    /**
2362
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2363
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2364
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2365
-     * ..."
2366
-     *
2367
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2368
-     * @return string
2369
-     */
2370
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2371
-    {
2372
-        return " FROM " . $model_query_info->get_full_join_sql() .
2373
-               $model_query_info->get_where_sql() .
2374
-               $model_query_info->get_group_by_sql() .
2375
-               $model_query_info->get_having_sql() .
2376
-               $model_query_info->get_order_by_sql() .
2377
-               $model_query_info->get_limit_sql();
2378
-    }
2379
-
2380
-
2381
-
2382
-    /**
2383
-     * Set to easily debug the next X queries ran from this model.
2384
-     *
2385
-     * @param int $count
2386
-     */
2387
-    public function show_next_x_db_queries($count = 1)
2388
-    {
2389
-        $this->_show_next_x_db_queries = $count;
2390
-    }
2391
-
2392
-
2393
-
2394
-    /**
2395
-     * @param $sql_query
2396
-     */
2397
-    public function show_db_query_if_previously_requested($sql_query)
2398
-    {
2399
-        if ($this->_show_next_x_db_queries > 0) {
2400
-            echo $sql_query;
2401
-            $this->_show_next_x_db_queries--;
2402
-        }
2403
-    }
2404
-
2405
-
2406
-
2407
-    /**
2408
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2409
-     * There are the 3 cases:
2410
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2411
-     * $otherModelObject has no ID, it is first saved.
2412
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2413
-     * has no ID, it is first saved.
2414
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2415
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2416
-     * join table
2417
-     *
2418
-     * @param        EE_Base_Class                     /int $thisModelObject
2419
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2420
-     * @param string $relationName                     , key in EEM_Base::_relations
2421
-     *                                                 an attendee to a group, you also want to specify which role they
2422
-     *                                                 will have in that group. So you would use this parameter to
2423
-     *                                                 specify array('role-column-name'=>'role-id')
2424
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2425
-     *                                                 to for relation to methods that allow you to further specify
2426
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2427
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2428
-     *                                                 because these will be inserted in any new rows created as well.
2429
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2430
-     * @throws \EE_Error
2431
-     */
2432
-    public function add_relationship_to(
2433
-        $id_or_obj,
2434
-        $other_model_id_or_obj,
2435
-        $relationName,
2436
-        $extra_join_model_fields_n_values = array()
2437
-    ) {
2438
-        $relation_obj = $this->related_settings_for($relationName);
2439
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2440
-    }
2441
-
2442
-
2443
-
2444
-    /**
2445
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2446
-     * There are the 3 cases:
2447
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2448
-     * error
2449
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2450
-     * an error
2451
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2452
-     *
2453
-     * @param        EE_Base_Class /int $id_or_obj
2454
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2455
-     * @param string $relationName key in EEM_Base::_relations
2456
-     * @return boolean of success
2457
-     * @throws \EE_Error
2458
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2459
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2460
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2461
-     *                             because these will be inserted in any new rows created as well.
2462
-     */
2463
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2464
-    {
2465
-        $relation_obj = $this->related_settings_for($relationName);
2466
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2467
-    }
2468
-
2469
-
2470
-
2471
-    /**
2472
-     * @param mixed           $id_or_obj
2473
-     * @param string          $relationName
2474
-     * @param array           $where_query_params
2475
-     * @param EE_Base_Class[] objects to which relations were removed
2476
-     * @return \EE_Base_Class[]
2477
-     * @throws \EE_Error
2478
-     */
2479
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2480
-    {
2481
-        $relation_obj = $this->related_settings_for($relationName);
2482
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2483
-    }
2484
-
2485
-
2486
-
2487
-    /**
2488
-     * Gets all the related items of the specified $model_name, using $query_params.
2489
-     * Note: by default, we remove the "default query params"
2490
-     * because we want to get even deleted items etc.
2491
-     *
2492
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2493
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2494
-     * @param array  $query_params like EEM_Base::get_all
2495
-     * @return EE_Base_Class[]
2496
-     * @throws \EE_Error
2497
-     */
2498
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2499
-    {
2500
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2501
-        $relation_settings = $this->related_settings_for($model_name);
2502
-        return $relation_settings->get_all_related($model_obj, $query_params);
2503
-    }
2504
-
2505
-
2506
-
2507
-    /**
2508
-     * Deletes all the model objects across the relation indicated by $model_name
2509
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2510
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2511
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2512
-     *
2513
-     * @param EE_Base_Class|int|string $id_or_obj
2514
-     * @param string                   $model_name
2515
-     * @param array                    $query_params
2516
-     * @return int how many deleted
2517
-     * @throws \EE_Error
2518
-     */
2519
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2520
-    {
2521
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2522
-        $relation_settings = $this->related_settings_for($model_name);
2523
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2524
-    }
2525
-
2526
-
2527
-
2528
-    /**
2529
-     * Hard deletes all the model objects across the relation indicated by $model_name
2530
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2531
-     * the model objects can't be hard deleted because of blocking related model objects,
2532
-     * just does a soft-delete on them instead.
2533
-     *
2534
-     * @param EE_Base_Class|int|string $id_or_obj
2535
-     * @param string                   $model_name
2536
-     * @param array                    $query_params
2537
-     * @return int how many deleted
2538
-     * @throws \EE_Error
2539
-     */
2540
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2541
-    {
2542
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2543
-        $relation_settings = $this->related_settings_for($model_name);
2544
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2545
-    }
2546
-
2547
-
2548
-
2549
-    /**
2550
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2551
-     * unless otherwise specified in the $query_params
2552
-     *
2553
-     * @param        int             /EE_Base_Class $id_or_obj
2554
-     * @param string $model_name     like 'Event', or 'Registration'
2555
-     * @param array  $query_params   like EEM_Base::get_all's
2556
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2557
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2558
-     *                               that by the setting $distinct to TRUE;
2559
-     * @return int
2560
-     * @throws \EE_Error
2561
-     */
2562
-    public function count_related(
2563
-        $id_or_obj,
2564
-        $model_name,
2565
-        $query_params = array(),
2566
-        $field_to_count = null,
2567
-        $distinct = false
2568
-    ) {
2569
-        $related_model = $this->get_related_model_obj($model_name);
2570
-        //we're just going to use the query params on the related model's normal get_all query,
2571
-        //except add a condition to say to match the current mod
2572
-        if (! isset($query_params['default_where_conditions'])) {
2573
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2574
-        }
2575
-        $this_model_name = $this->get_this_model_name();
2576
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2577
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2578
-        return $related_model->count($query_params, $field_to_count, $distinct);
2579
-    }
2580
-
2581
-
2582
-
2583
-    /**
2584
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2585
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2586
-     *
2587
-     * @param        int           /EE_Base_Class $id_or_obj
2588
-     * @param string $model_name   like 'Event', or 'Registration'
2589
-     * @param array  $query_params like EEM_Base::get_all's
2590
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2591
-     * @return float
2592
-     * @throws \EE_Error
2593
-     */
2594
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2595
-    {
2596
-        $related_model = $this->get_related_model_obj($model_name);
2597
-        if (! is_array($query_params)) {
2598
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2599
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2600
-                    gettype($query_params)), '4.6.0');
2601
-            $query_params = array();
2602
-        }
2603
-        //we're just going to use the query params on the related model's normal get_all query,
2604
-        //except add a condition to say to match the current mod
2605
-        if (! isset($query_params['default_where_conditions'])) {
2606
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2607
-        }
2608
-        $this_model_name = $this->get_this_model_name();
2609
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2610
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2611
-        return $related_model->sum($query_params, $field_to_sum);
2612
-    }
2613
-
2614
-
2615
-
2616
-    /**
2617
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2618
-     * $modelObject
2619
-     *
2620
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2621
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2622
-     * @param array               $query_params     like EEM_Base::get_all's
2623
-     * @return EE_Base_Class
2624
-     * @throws \EE_Error
2625
-     */
2626
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2627
-    {
2628
-        $query_params['limit'] = 1;
2629
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2630
-        if ($results) {
2631
-            return array_shift($results);
2632
-        } else {
2633
-            return null;
2634
-        }
2635
-    }
2636
-
2637
-
2638
-
2639
-    /**
2640
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2641
-     *
2642
-     * @return string
2643
-     */
2644
-    public function get_this_model_name()
2645
-    {
2646
-        return str_replace("EEM_", "", get_class($this));
2647
-    }
2648
-
2649
-
2650
-
2651
-    /**
2652
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2653
-     *
2654
-     * @return EE_Any_Foreign_Model_Name_Field
2655
-     * @throws EE_Error
2656
-     */
2657
-    public function get_field_containing_related_model_name()
2658
-    {
2659
-        foreach ($this->field_settings(true) as $field) {
2660
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2661
-                $field_with_model_name = $field;
2662
-            }
2663
-        }
2664
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2665
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2666
-                $this->get_this_model_name()));
2667
-        }
2668
-        return $field_with_model_name;
2669
-    }
2670
-
2671
-
2672
-
2673
-    /**
2674
-     * Inserts a new entry into the database, for each table.
2675
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2676
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2677
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2678
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2679
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2680
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2681
-     *
2682
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2683
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2684
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2685
-     *                              of EEM_Base)
2686
-     * @return int new primary key on main table that got inserted
2687
-     * @throws EE_Error
2688
-     */
2689
-    public function insert($field_n_values)
2690
-    {
2691
-        /**
2692
-         * Filters the fields and their values before inserting an item using the models
2693
-         *
2694
-         * @param array    $fields_n_values keys are the fields and values are their new values
2695
-         * @param EEM_Base $model           the model used
2696
-         */
2697
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2698
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2699
-            $main_table = $this->_get_main_table();
2700
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2701
-            if ($new_id !== false) {
2702
-                foreach ($this->_get_other_tables() as $other_table) {
2703
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2704
-                }
2705
-            }
2706
-            /**
2707
-             * Done just after attempting to insert a new model object
2708
-             *
2709
-             * @param EEM_Base   $model           used
2710
-             * @param array      $fields_n_values fields and their values
2711
-             * @param int|string the              ID of the newly-inserted model object
2712
-             */
2713
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2714
-            return $new_id;
2715
-        } else {
2716
-            return false;
2717
-        }
2718
-    }
2719
-
2720
-
2721
-
2722
-    /**
2723
-     * Checks that the result would satisfy the unique indexes on this model
2724
-     *
2725
-     * @param array  $field_n_values
2726
-     * @param string $action
2727
-     * @return boolean
2728
-     * @throws \EE_Error
2729
-     */
2730
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2731
-    {
2732
-        foreach ($this->unique_indexes() as $index_name => $index) {
2733
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2734
-            if ($this->exists(array($uniqueness_where_params))) {
2735
-                EE_Error::add_error(
2736
-                    sprintf(
2737
-                        __(
2738
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2739
-                            "event_espresso"
2740
-                        ),
2741
-                        $action,
2742
-                        $this->_get_class_name(),
2743
-                        $index_name,
2744
-                        implode(",", $index->field_names()),
2745
-                        http_build_query($uniqueness_where_params)
2746
-                    ),
2747
-                    __FILE__,
2748
-                    __FUNCTION__,
2749
-                    __LINE__
2750
-                );
2751
-                return false;
2752
-            }
2753
-        }
2754
-        return true;
2755
-    }
2756
-
2757
-
2758
-
2759
-    /**
2760
-     * Checks the database for an item that conflicts (ie, if this item were
2761
-     * saved to the DB would break some uniqueness requirement, like a primary key
2762
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2763
-     * can be either an EE_Base_Class or an array of fields n values
2764
-     *
2765
-     * @param EE_Base_Class|array $obj_or_fields_array
2766
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2767
-     *                                                 when looking for conflicts
2768
-     *                                                 (ie, if false, we ignore the model object's primary key
2769
-     *                                                 when finding "conflicts". If true, it's also considered).
2770
-     *                                                 Only works for INT primary key,
2771
-     *                                                 STRING primary keys cannot be ignored
2772
-     * @throws EE_Error
2773
-     * @return EE_Base_Class|array
2774
-     */
2775
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2776
-    {
2777
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2778
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2779
-        } elseif (is_array($obj_or_fields_array)) {
2780
-            $fields_n_values = $obj_or_fields_array;
2781
-        } else {
2782
-            throw new EE_Error(
2783
-                sprintf(
2784
-                    __(
2785
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2786
-                        "event_espresso"
2787
-                    ),
2788
-                    get_class($this),
2789
-                    $obj_or_fields_array
2790
-                )
2791
-            );
2792
-        }
2793
-        $query_params = array();
2794
-        if ($this->has_primary_key_field()
2795
-            && ($include_primary_key
2796
-                || $this->get_primary_key_field()
2797
-                   instanceof
2798
-                   EE_Primary_Key_String_Field)
2799
-            && isset($fields_n_values[$this->primary_key_name()])
2800
-        ) {
2801
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2802
-        }
2803
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2804
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2805
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2806
-        }
2807
-        //if there is nothing to base this search on, then we shouldn't find anything
2808
-        if (empty($query_params)) {
2809
-            return array();
2810
-        } else {
2811
-            return $this->get_one($query_params);
2812
-        }
2813
-    }
2814
-
2815
-
2816
-
2817
-    /**
2818
-     * Like count, but is optimized and returns a boolean instead of an int
2819
-     *
2820
-     * @param array $query_params
2821
-     * @return boolean
2822
-     * @throws \EE_Error
2823
-     */
2824
-    public function exists($query_params)
2825
-    {
2826
-        $query_params['limit'] = 1;
2827
-        return $this->count($query_params) > 0;
2828
-    }
2829
-
2830
-
2831
-
2832
-    /**
2833
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2834
-     *
2835
-     * @param int|string $id
2836
-     * @return boolean
2837
-     * @throws \EE_Error
2838
-     */
2839
-    public function exists_by_ID($id)
2840
-    {
2841
-        return $this->exists(
2842
-            array(
2843
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2844
-                array(
2845
-                    $this->primary_key_name() => $id,
2846
-                ),
2847
-            )
2848
-        );
2849
-    }
2850
-
2851
-
2852
-
2853
-    /**
2854
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2855
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2856
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2857
-     * on the main table)
2858
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2859
-     * cases where we want to call it directly rather than via insert().
2860
-     *
2861
-     * @access   protected
2862
-     * @param EE_Table_Base $table
2863
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2864
-     *                                       float
2865
-     * @param int           $new_id          for now we assume only int keys
2866
-     * @throws EE_Error
2867
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2868
-     * @return int ID of new row inserted, or FALSE on failure
2869
-     */
2870
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2871
-    {
2872
-        global $wpdb;
2873
-        $insertion_col_n_values = array();
2874
-        $format_for_insertion = array();
2875
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2876
-        foreach ($fields_on_table as $field_name => $field_obj) {
2877
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2878
-            if ($field_obj->is_auto_increment()) {
2879
-                continue;
2880
-            }
2881
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2882
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2883
-            if ($prepared_value !== null) {
2884
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2885
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2886
-            }
2887
-        }
2888
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2889
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2890
-            //so add the fk to the main table as a column
2891
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2892
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2893
-        }
2894
-        //insert the new entry
2895
-        $result = $this->_do_wpdb_query('insert',
2896
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2897
-        if ($result === false) {
2898
-            return false;
2899
-        }
2900
-        //ok, now what do we return for the ID of the newly-inserted thing?
2901
-        if ($this->has_primary_key_field()) {
2902
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2903
-                return $wpdb->insert_id;
2904
-            } else {
2905
-                //it's not an auto-increment primary key, so
2906
-                //it must have been supplied
2907
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2908
-            }
2909
-        } else {
2910
-            //we can't return a  primary key because there is none. instead return
2911
-            //a unique string indicating this model
2912
-            return $this->get_index_primary_key_string($fields_n_values);
2913
-        }
2914
-    }
2915
-
2916
-
2917
-
2918
-    /**
2919
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2920
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2921
-     * and there is no default, we pass it along. WPDB will take care of it)
2922
-     *
2923
-     * @param EE_Model_Field_Base $field_obj
2924
-     * @param array               $fields_n_values
2925
-     * @return mixed string|int|float depending on what the table column will be expecting
2926
-     * @throws \EE_Error
2927
-     */
2928
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2929
-    {
2930
-        //if this field doesn't allow nullable, don't allow it
2931
-        if (! $field_obj->is_nullable()
2932
-            && (
2933
-                ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2934
-        ) {
2935
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2936
-        }
2937
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2938
-            : null;
2939
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2940
-    }
2941
-
2942
-
2943
-
2944
-    /**
2945
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2946
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2947
-     * the field's prepare_for_set() method.
2948
-     *
2949
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2950
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2951
-     *                                   top of file)
2952
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2953
-     *                                   $value is a custom selection
2954
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2955
-     */
2956
-    private function _prepare_value_for_use_in_db($value, $field)
2957
-    {
2958
-        if ($field && $field instanceof EE_Model_Field_Base) {
2959
-            switch ($this->_values_already_prepared_by_model_object) {
2960
-                /** @noinspection PhpMissingBreakStatementInspection */
2961
-                case self::not_prepared_by_model_object:
2962
-                    $value = $field->prepare_for_set($value);
2963
-                //purposefully left out "return"
2964
-                case self::prepared_by_model_object:
2965
-                    $value = $field->prepare_for_use_in_db($value);
2966
-                case self::prepared_for_use_in_db:
2967
-                    //leave the value alone
2968
-            }
2969
-            return $value;
2970
-        } else {
2971
-            return $value;
2972
-        }
2973
-    }
2974
-
2975
-
2976
-
2977
-    /**
2978
-     * Returns the main table on this model
2979
-     *
2980
-     * @return EE_Primary_Table
2981
-     * @throws EE_Error
2982
-     */
2983
-    protected function _get_main_table()
2984
-    {
2985
-        foreach ($this->_tables as $table) {
2986
-            if ($table instanceof EE_Primary_Table) {
2987
-                return $table;
2988
-            }
2989
-        }
2990
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2991
-            'event_espresso'), get_class($this)));
2992
-    }
2993
-
2994
-
2995
-
2996
-    /**
2997
-     * table
2998
-     * returns EE_Primary_Table table name
2999
-     *
3000
-     * @return string
3001
-     * @throws \EE_Error
3002
-     */
3003
-    public function table()
3004
-    {
3005
-        return $this->_get_main_table()->get_table_name();
3006
-    }
3007
-
3008
-
3009
-
3010
-    /**
3011
-     * table
3012
-     * returns first EE_Secondary_Table table name
3013
-     *
3014
-     * @return string
3015
-     */
3016
-    public function second_table()
3017
-    {
3018
-        // grab second table from tables array
3019
-        $second_table = end($this->_tables);
3020
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3021
-    }
3022
-
3023
-
3024
-
3025
-    /**
3026
-     * get_table_obj_by_alias
3027
-     * returns table name given it's alias
3028
-     *
3029
-     * @param string $table_alias
3030
-     * @return EE_Primary_Table | EE_Secondary_Table
3031
-     */
3032
-    public function get_table_obj_by_alias($table_alias = '')
3033
-    {
3034
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3035
-    }
3036
-
3037
-
3038
-
3039
-    /**
3040
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3041
-     *
3042
-     * @return EE_Secondary_Table[]
3043
-     */
3044
-    protected function _get_other_tables()
3045
-    {
3046
-        $other_tables = array();
3047
-        foreach ($this->_tables as $table_alias => $table) {
3048
-            if ($table instanceof EE_Secondary_Table) {
3049
-                $other_tables[$table_alias] = $table;
3050
-            }
3051
-        }
3052
-        return $other_tables;
3053
-    }
3054
-
3055
-
3056
-
3057
-    /**
3058
-     * Finds all the fields that correspond to the given table
3059
-     *
3060
-     * @param string $table_alias , array key in EEM_Base::_tables
3061
-     * @return EE_Model_Field_Base[]
3062
-     */
3063
-    public function _get_fields_for_table($table_alias)
3064
-    {
3065
-        return $this->_fields[$table_alias];
3066
-    }
3067
-
3068
-
3069
-
3070
-    /**
3071
-     * Recurses through all the where parameters, and finds all the related models we'll need
3072
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3073
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3074
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3075
-     * related Registration, Transaction, and Payment models.
3076
-     *
3077
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3078
-     * @return EE_Model_Query_Info_Carrier
3079
-     * @throws \EE_Error
3080
-     */
3081
-    public function _extract_related_models_from_query($query_params)
3082
-    {
3083
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3084
-        if (array_key_exists(0, $query_params)) {
3085
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3086
-        }
3087
-        if (array_key_exists('group_by', $query_params)) {
3088
-            if (is_array($query_params['group_by'])) {
3089
-                $this->_extract_related_models_from_sub_params_array_values(
3090
-                    $query_params['group_by'],
3091
-                    $query_info_carrier,
3092
-                    'group_by'
3093
-                );
3094
-            } elseif (! empty ($query_params['group_by'])) {
3095
-                $this->_extract_related_model_info_from_query_param(
3096
-                    $query_params['group_by'],
3097
-                    $query_info_carrier,
3098
-                    'group_by'
3099
-                );
3100
-            }
3101
-        }
3102
-        if (array_key_exists('having', $query_params)) {
3103
-            $this->_extract_related_models_from_sub_params_array_keys(
3104
-                $query_params[0],
3105
-                $query_info_carrier,
3106
-                'having'
3107
-            );
3108
-        }
3109
-        if (array_key_exists('order_by', $query_params)) {
3110
-            if (is_array($query_params['order_by'])) {
3111
-                $this->_extract_related_models_from_sub_params_array_keys(
3112
-                    $query_params['order_by'],
3113
-                    $query_info_carrier,
3114
-                    'order_by'
3115
-                );
3116
-            } elseif (! empty($query_params['order_by'])) {
3117
-                $this->_extract_related_model_info_from_query_param(
3118
-                    $query_params['order_by'],
3119
-                    $query_info_carrier,
3120
-                    'order_by'
3121
-                );
3122
-            }
3123
-        }
3124
-        if (array_key_exists('force_join', $query_params)) {
3125
-            $this->_extract_related_models_from_sub_params_array_values(
3126
-                $query_params['force_join'],
3127
-                $query_info_carrier,
3128
-                'force_join'
3129
-            );
3130
-        }
3131
-        return $query_info_carrier;
3132
-    }
3133
-
3134
-
3135
-
3136
-    /**
3137
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3138
-     *
3139
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3140
-     *                                                      $query_params['having']
3141
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3142
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3143
-     * @throws EE_Error
3144
-     * @return \EE_Model_Query_Info_Carrier
3145
-     */
3146
-    private function _extract_related_models_from_sub_params_array_keys(
3147
-        $sub_query_params,
3148
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3149
-        $query_param_type
3150
-    ) {
3151
-        if (! empty($sub_query_params)) {
3152
-            $sub_query_params = (array)$sub_query_params;
3153
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3154
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3155
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3156
-                    $query_param_type);
3157
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3158
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3159
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3160
-                //of array('Registration.TXN_ID'=>23)
3161
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3162
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3163
-                    if (! is_array($possibly_array_of_params)) {
3164
-                        throw new EE_Error(sprintf(__("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'))",
3165
-                            "event_espresso"),
3166
-                            $param, $possibly_array_of_params));
3167
-                    } else {
3168
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3169
-                            $model_query_info_carrier, $query_param_type);
3170
-                    }
3171
-                } elseif ($query_param_type === 0 //ie WHERE
3172
-                          && is_array($possibly_array_of_params)
3173
-                          && isset($possibly_array_of_params[2])
3174
-                          && $possibly_array_of_params[2] == true
3175
-                ) {
3176
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3177
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3178
-                    //from which we should extract query parameters!
3179
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3180
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3181
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3182
-                    }
3183
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3184
-                        $model_query_info_carrier, $query_param_type);
3185
-                }
3186
-            }
3187
-        }
3188
-        return $model_query_info_carrier;
3189
-    }
3190
-
3191
-
3192
-
3193
-    /**
3194
-     * For extracting related models from forced_joins, where the array values contain the info about what
3195
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3196
-     *
3197
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3198
-     *                                                      $query_params['having']
3199
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3200
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3201
-     * @throws EE_Error
3202
-     * @return \EE_Model_Query_Info_Carrier
3203
-     */
3204
-    private function _extract_related_models_from_sub_params_array_values(
3205
-        $sub_query_params,
3206
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3207
-        $query_param_type
3208
-    ) {
3209
-        if (! empty($sub_query_params)) {
3210
-            if (! is_array($sub_query_params)) {
3211
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3212
-                    $sub_query_params));
3213
-            }
3214
-            foreach ($sub_query_params as $param) {
3215
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3216
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3217
-                    $query_param_type);
3218
-            }
3219
-        }
3220
-        return $model_query_info_carrier;
3221
-    }
3222
-
3223
-
3224
-
3225
-    /**
3226
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3227
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3228
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3229
-     * but use them in a different order. Eg, we need to know what models we are querying
3230
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3231
-     * other models before we can finalize the where clause SQL.
3232
-     *
3233
-     * @param array $query_params
3234
-     * @throws EE_Error
3235
-     * @return EE_Model_Query_Info_Carrier
3236
-     */
3237
-    public function _create_model_query_info_carrier($query_params)
3238
-    {
3239
-        if (! is_array($query_params)) {
3240
-            EE_Error::doing_it_wrong(
3241
-                'EEM_Base::_create_model_query_info_carrier',
3242
-                sprintf(
3243
-                    __(
3244
-                        '$query_params should be an array, you passed a variable of type %s',
3245
-                        'event_espresso'
3246
-                    ),
3247
-                    gettype($query_params)
3248
-                ),
3249
-                '4.6.0'
3250
-            );
3251
-            $query_params = array();
3252
-        }
3253
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3254
-        //first check if we should alter the query to account for caps or not
3255
-        //because the caps might require us to do extra joins
3256
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3257
-            $query_params[0] = $where_query_params = array_replace_recursive(
3258
-                $where_query_params,
3259
-                $this->caps_where_conditions(
3260
-                    $query_params['caps']
3261
-                )
3262
-            );
3263
-        }
3264
-        $query_object = $this->_extract_related_models_from_query($query_params);
3265
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3266
-        foreach ($where_query_params as $key => $value) {
3267
-            if (is_int($key)) {
3268
-                throw new EE_Error(
3269
-                    sprintf(
3270
-                        __(
3271
-                            "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.",
3272
-                            "event_espresso"
3273
-                        ),
3274
-                        $key,
3275
-                        var_export($value, true),
3276
-                        var_export($query_params, true),
3277
-                        get_class($this)
3278
-                    )
3279
-                );
3280
-            }
3281
-        }
3282
-        if (
3283
-            array_key_exists('default_where_conditions', $query_params)
3284
-            && ! empty($query_params['default_where_conditions'])
3285
-        ) {
3286
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3287
-        } else {
3288
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3289
-        }
3290
-        $where_query_params = array_merge(
3291
-            $this->_get_default_where_conditions_for_models_in_query(
3292
-                $query_object,
3293
-                $use_default_where_conditions,
3294
-                $where_query_params
3295
-            ),
3296
-            $where_query_params
3297
-        );
3298
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3299
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3300
-        // So we need to setup a subquery and use that for the main join.
3301
-        // Note for now this only works on the primary table for the model.
3302
-        // So for instance, you could set the limit array like this:
3303
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3304
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3305
-            $query_object->set_main_model_join_sql(
3306
-                $this->_construct_limit_join_select(
3307
-                    $query_params['on_join_limit'][0],
3308
-                    $query_params['on_join_limit'][1]
3309
-                )
3310
-            );
3311
-        }
3312
-        //set limit
3313
-        if (array_key_exists('limit', $query_params)) {
3314
-            if (is_array($query_params['limit'])) {
3315
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3316
-                    $e = sprintf(
3317
-                        __(
3318
-                            "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)",
3319
-                            "event_espresso"
3320
-                        ),
3321
-                        http_build_query($query_params['limit'])
3322
-                    );
3323
-                    throw new EE_Error($e . "|" . $e);
3324
-                }
3325
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3326
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3327
-            } elseif (! empty ($query_params['limit'])) {
3328
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3329
-            }
3330
-        }
3331
-        //set order by
3332
-        if (array_key_exists('order_by', $query_params)) {
3333
-            if (is_array($query_params['order_by'])) {
3334
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3335
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3336
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3337
-                if (array_key_exists('order', $query_params)) {
3338
-                    throw new EE_Error(
3339
-                        sprintf(
3340
-                            __(
3341
-                                "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 ",
3342
-                                "event_espresso"
3343
-                            ),
3344
-                            get_class($this),
3345
-                            implode(", ", array_keys($query_params['order_by'])),
3346
-                            implode(", ", $query_params['order_by']),
3347
-                            $query_params['order']
3348
-                        )
3349
-                    );
3350
-                }
3351
-                $this->_extract_related_models_from_sub_params_array_keys(
3352
-                    $query_params['order_by'],
3353
-                    $query_object,
3354
-                    'order_by'
3355
-                );
3356
-                //assume it's an array of fields to order by
3357
-                $order_array = array();
3358
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3359
-                    $order = $this->_extract_order($order);
3360
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3361
-                }
3362
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3363
-            } elseif (! empty ($query_params['order_by'])) {
3364
-                $this->_extract_related_model_info_from_query_param(
3365
-                    $query_params['order_by'],
3366
-                    $query_object,
3367
-                    'order',
3368
-                    $query_params['order_by']
3369
-                );
3370
-                $order = isset($query_params['order'])
3371
-                    ? $this->_extract_order($query_params['order'])
3372
-                    : 'DESC';
3373
-                $query_object->set_order_by_sql(
3374
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3375
-                );
3376
-            }
3377
-        }
3378
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3379
-        if (! array_key_exists('order_by', $query_params)
3380
-            && array_key_exists('order', $query_params)
3381
-            && ! empty($query_params['order'])
3382
-        ) {
3383
-            $pk_field = $this->get_primary_key_field();
3384
-            $order = $this->_extract_order($query_params['order']);
3385
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3386
-        }
3387
-        //set group by
3388
-        if (array_key_exists('group_by', $query_params)) {
3389
-            if (is_array($query_params['group_by'])) {
3390
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3391
-                $group_by_array = array();
3392
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3393
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3394
-                }
3395
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3396
-            } elseif (! empty ($query_params['group_by'])) {
3397
-                $query_object->set_group_by_sql(
3398
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3399
-                );
3400
-            }
3401
-        }
3402
-        //set having
3403
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3404
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3405
-        }
3406
-        //now, just verify they didn't pass anything wack
3407
-        foreach ($query_params as $query_key => $query_value) {
3408
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3409
-                throw new EE_Error(
3410
-                    sprintf(
3411
-                        __(
3412
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3413
-                            'event_espresso'
3414
-                        ),
3415
-                        $query_key,
3416
-                        get_class($this),
3417
-                        //						print_r( $this->_allowed_query_params, TRUE )
3418
-                        implode(',', $this->_allowed_query_params)
3419
-                    )
3420
-                );
3421
-            }
3422
-        }
3423
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3424
-        if (empty($main_model_join_sql)) {
3425
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3426
-        }
3427
-        return $query_object;
3428
-    }
3429
-
3430
-
3431
-
3432
-    /**
3433
-     * Gets the where conditions that should be imposed on the query based on the
3434
-     * context (eg reading frontend, backend, edit or delete).
3435
-     *
3436
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3437
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3438
-     * @throws \EE_Error
3439
-     */
3440
-    public function caps_where_conditions($context = self::caps_read)
3441
-    {
3442
-        EEM_Base::verify_is_valid_cap_context($context);
3443
-        $cap_where_conditions = array();
3444
-        $cap_restrictions = $this->caps_missing($context);
3445
-        /**
3446
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3447
-         */
3448
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3449
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3450
-                $restriction_if_no_cap->get_default_where_conditions());
3451
-        }
3452
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3453
-            $cap_restrictions);
3454
-    }
3455
-
3456
-
3457
-
3458
-    /**
3459
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3460
-     * otherwise throws an exception
3461
-     *
3462
-     * @param string $should_be_order_string
3463
-     * @return string either ASC, asc, DESC or desc
3464
-     * @throws EE_Error
3465
-     */
3466
-    private function _extract_order($should_be_order_string)
3467
-    {
3468
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3469
-            return $should_be_order_string;
3470
-        } else {
3471
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3472
-                "event_espresso"), get_class($this), $should_be_order_string));
3473
-        }
3474
-    }
3475
-
3476
-
3477
-
3478
-    /**
3479
-     * Looks at all the models which are included in this query, and asks each
3480
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3481
-     * so they can be merged
3482
-     *
3483
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3484
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3485
-     *                                                                  'none' means NO default where conditions will
3486
-     *                                                                  be used AT ALL during this query.
3487
-     *                                                                  'other_models_only' means default where
3488
-     *                                                                  conditions from other models will be used, but
3489
-     *                                                                  not for this primary model. 'all', the default,
3490
-     *                                                                  means default where conditions will apply as
3491
-     *                                                                  normal
3492
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3493
-     * @throws EE_Error
3494
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3495
-     */
3496
-    private function _get_default_where_conditions_for_models_in_query(
3497
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3498
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3499
-        $where_query_params = array()
3500
-    ) {
3501
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3502
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3503
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3504
-                "event_espresso"), $use_default_where_conditions,
3505
-                implode(", ", $allowed_used_default_where_conditions_values)));
3506
-        }
3507
-        $universal_query_params = array();
3508
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3509
-            $universal_query_params = $this->_get_default_where_conditions();
3510
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3511
-            $universal_query_params = $this->_get_minimum_where_conditions();
3512
-        }
3513
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3514
-            $related_model = $this->get_related_model_obj($model_name);
3515
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3516
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3517
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3518
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3519
-            } else {
3520
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3521
-                continue;
3522
-            }
3523
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3524
-                $related_model_universal_where_params,
3525
-                $where_query_params,
3526
-                $related_model,
3527
-                $model_relation_path
3528
-            );
3529
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3530
-                $universal_query_params,
3531
-                $overrides
3532
-            );
3533
-        }
3534
-        return $universal_query_params;
3535
-    }
3536
-
3537
-
3538
-
3539
-    /**
3540
-     * Determines whether or not we should use default where conditions for the model in question
3541
-     * (this model, or other related models).
3542
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3543
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3544
-     * We should use default where conditions on related models when they requested to use default where conditions
3545
-     * on all models, or specifically just on other related models
3546
-     * @param      $default_where_conditions_value
3547
-     * @param bool $for_this_model false means this is for OTHER related models
3548
-     * @return bool
3549
-     */
3550
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3551
-    {
3552
-        return (
3553
-                   $for_this_model
3554
-                   && in_array(
3555
-                       $default_where_conditions_value,
3556
-                       array(
3557
-                           EEM_Base::default_where_conditions_all,
3558
-                           EEM_Base::default_where_conditions_this_only,
3559
-                           EEM_Base::default_where_conditions_minimum_others,
3560
-                       ),
3561
-                       true
3562
-                   )
3563
-               )
3564
-               || (
3565
-                   ! $for_this_model
3566
-                   && in_array(
3567
-                       $default_where_conditions_value,
3568
-                       array(
3569
-                           EEM_Base::default_where_conditions_all,
3570
-                           EEM_Base::default_where_conditions_others_only,
3571
-                       ),
3572
-                       true
3573
-                   )
3574
-               );
3575
-    }
3576
-
3577
-    /**
3578
-     * Determines whether or not we should use default minimum conditions for the model in question
3579
-     * (this model, or other related models).
3580
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3581
-     * where conditions.
3582
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3583
-     * on this model or others
3584
-     * @param      $default_where_conditions_value
3585
-     * @param bool $for_this_model false means this is for OTHER related models
3586
-     * @return bool
3587
-     */
3588
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3589
-    {
3590
-        return (
3591
-                   $for_this_model
3592
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3593
-               )
3594
-               || (
3595
-                   ! $for_this_model
3596
-                   && in_array(
3597
-                       $default_where_conditions_value,
3598
-                       array(
3599
-                           EEM_Base::default_where_conditions_minimum_others,
3600
-                           EEM_Base::default_where_conditions_minimum_all,
3601
-                       ),
3602
-                       true
3603
-                   )
3604
-               );
3605
-    }
3606
-
3607
-
3608
-    /**
3609
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3610
-     * then we also add a special where condition which allows for that model's primary key
3611
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3612
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3613
-     *
3614
-     * @param array    $default_where_conditions
3615
-     * @param array    $provided_where_conditions
3616
-     * @param EEM_Base $model
3617
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3618
-     * @return array like EEM_Base::get_all's $query_params[0]
3619
-     * @throws \EE_Error
3620
-     */
3621
-    private function _override_defaults_or_make_null_friendly(
3622
-        $default_where_conditions,
3623
-        $provided_where_conditions,
3624
-        $model,
3625
-        $model_relation_path
3626
-    ) {
3627
-        $null_friendly_where_conditions = array();
3628
-        $none_overridden = true;
3629
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3630
-        foreach ($default_where_conditions as $key => $val) {
3631
-            if (isset($provided_where_conditions[$key])) {
3632
-                $none_overridden = false;
3633
-            } else {
3634
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3635
-            }
3636
-        }
3637
-        if ($none_overridden && $default_where_conditions) {
3638
-            if ($model->has_primary_key_field()) {
3639
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3640
-                                                                                . "."
3641
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3642
-            }/*else{
31
+	/**
32
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
33
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
34
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
35
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
36
+	 *
37
+	 * @var boolean
38
+	 */
39
+	private $_values_already_prepared_by_model_object = 0;
40
+
41
+	/**
42
+	 * when $_values_already_prepared_by_model_object equals this, we assume
43
+	 * the data is just like form input that needs to have the model fields'
44
+	 * prepare_for_set and prepare_for_use_in_db called on it
45
+	 */
46
+	const not_prepared_by_model_object = 0;
47
+
48
+	/**
49
+	 * when $_values_already_prepared_by_model_object equals this, we
50
+	 * assume this value is coming from a model object and doesn't need to have
51
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
52
+	 */
53
+	const prepared_by_model_object = 1;
54
+
55
+	/**
56
+	 * when $_values_already_prepared_by_model_object equals this, we assume
57
+	 * the values are already to be used in the database (ie no processing is done
58
+	 * on them by the model's fields)
59
+	 */
60
+	const prepared_for_use_in_db = 2;
61
+
62
+
63
+	protected $singular_item = 'Item';
64
+
65
+	protected $plural_item   = 'Items';
66
+
67
+	/**
68
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
69
+	 */
70
+	protected $_tables;
71
+
72
+	/**
73
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
74
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
75
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
76
+	 *
77
+	 * @var \EE_Model_Field_Base[][] $_fields
78
+	 */
79
+	protected $_fields;
80
+
81
+	/**
82
+	 * array of different kinds of relations
83
+	 *
84
+	 * @var \EE_Model_Relation_Base[] $_model_relations
85
+	 */
86
+	protected $_model_relations;
87
+
88
+	/**
89
+	 * @var \EE_Index[] $_indexes
90
+	 */
91
+	protected $_indexes = array();
92
+
93
+	/**
94
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
95
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
96
+	 * by setting the same columns as used in these queries in the query yourself.
97
+	 *
98
+	 * @var EE_Default_Where_Conditions
99
+	 */
100
+	protected $_default_where_conditions_strategy;
101
+
102
+	/**
103
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
104
+	 * This is particularly useful when you want something between 'none' and 'default'
105
+	 *
106
+	 * @var EE_Default_Where_Conditions
107
+	 */
108
+	protected $_minimum_where_conditions_strategy;
109
+
110
+	/**
111
+	 * String describing how to find the "owner" of this model's objects.
112
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
113
+	 * But when there isn't, this indicates which related model, or transiently-related model,
114
+	 * has the foreign key to the wp_users table.
115
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
116
+	 * related to events, and events have a foreign key to wp_users.
117
+	 * On EEM_Transaction, this would be 'Transaction.Event'
118
+	 *
119
+	 * @var string
120
+	 */
121
+	protected $_model_chain_to_wp_user = '';
122
+
123
+	/**
124
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
125
+	 * don't need it (particularly CPT models)
126
+	 *
127
+	 * @var bool
128
+	 */
129
+	protected $_ignore_where_strategy = false;
130
+
131
+	/**
132
+	 * String used in caps relating to this model. Eg, if the caps relating to this
133
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
134
+	 *
135
+	 * @var string. If null it hasn't been initialized yet. If false then we
136
+	 * have indicated capabilities don't apply to this
137
+	 */
138
+	protected $_caps_slug = null;
139
+
140
+	/**
141
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
142
+	 * and next-level keys are capability names, and each's value is a
143
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
144
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
145
+	 * and then each capability in the corresponding sub-array that they're missing
146
+	 * adds the where conditions onto the query.
147
+	 *
148
+	 * @var array
149
+	 */
150
+	protected $_cap_restrictions = array(
151
+		self::caps_read       => array(),
152
+		self::caps_read_admin => array(),
153
+		self::caps_edit       => array(),
154
+		self::caps_delete     => array(),
155
+	);
156
+
157
+	/**
158
+	 * Array defining which cap restriction generators to use to create default
159
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
160
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
161
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
162
+	 * automatically set this to false (not just null).
163
+	 *
164
+	 * @var EE_Restriction_Generator_Base[]
165
+	 */
166
+	protected $_cap_restriction_generators = array();
167
+
168
+	/**
169
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
170
+	 */
171
+	const caps_read       = 'read';
172
+
173
+	const caps_read_admin = 'read_admin';
174
+
175
+	const caps_edit       = 'edit';
176
+
177
+	const caps_delete     = 'delete';
178
+
179
+	/**
180
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
181
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
182
+	 * maps to 'read' because when looking for relevant permissions we're going to use
183
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
184
+	 *
185
+	 * @var array
186
+	 */
187
+	protected $_cap_contexts_to_cap_action_map = array(
188
+		self::caps_read       => 'read',
189
+		self::caps_read_admin => 'read',
190
+		self::caps_edit       => 'edit',
191
+		self::caps_delete     => 'delete',
192
+	);
193
+
194
+	/**
195
+	 * Timezone
196
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
197
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
198
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
199
+	 * EE_Datetime_Field data type will have access to it.
200
+	 *
201
+	 * @var string
202
+	 */
203
+	protected $_timezone;
204
+
205
+
206
+	/**
207
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
208
+	 * multisite.
209
+	 *
210
+	 * @var int
211
+	 */
212
+	protected static $_model_query_blog_id;
213
+
214
+	/**
215
+	 * A copy of _fields, except the array keys are the model names pointed to by
216
+	 * the field
217
+	 *
218
+	 * @var EE_Model_Field_Base[]
219
+	 */
220
+	private $_cache_foreign_key_to_fields = array();
221
+
222
+	/**
223
+	 * Cached list of all the fields on the model, indexed by their name
224
+	 *
225
+	 * @var EE_Model_Field_Base[]
226
+	 */
227
+	private $_cached_fields = null;
228
+
229
+	/**
230
+	 * Cached list of all the fields on the model, except those that are
231
+	 * marked as only pertinent to the database
232
+	 *
233
+	 * @var EE_Model_Field_Base[]
234
+	 */
235
+	private $_cached_fields_non_db_only = null;
236
+
237
+	/**
238
+	 * A cached reference to the primary key for quick lookup
239
+	 *
240
+	 * @var EE_Model_Field_Base
241
+	 */
242
+	private $_primary_key_field = null;
243
+
244
+	/**
245
+	 * Flag indicating whether this model has a primary key or not
246
+	 *
247
+	 * @var boolean
248
+	 */
249
+	protected $_has_primary_key_field = null;
250
+
251
+	/**
252
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
253
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
254
+	 * This should be true for models that deal with data that should exist independent of EE.
255
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
256
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
257
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
258
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
259
+	 * @var boolean
260
+	 */
261
+	protected $_wp_core_model = false;
262
+
263
+	/**
264
+	 *    List of valid operators that can be used for querying.
265
+	 * The keys are all operators we'll accept, the values are the real SQL
266
+	 * operators used
267
+	 *
268
+	 * @var array
269
+	 */
270
+	protected $_valid_operators = array(
271
+		'='           => '=',
272
+		'<='          => '<=',
273
+		'<'           => '<',
274
+		'>='          => '>=',
275
+		'>'           => '>',
276
+		'!='          => '!=',
277
+		'LIKE'        => 'LIKE',
278
+		'like'        => 'LIKE',
279
+		'NOT_LIKE'    => 'NOT LIKE',
280
+		'not_like'    => 'NOT LIKE',
281
+		'NOT LIKE'    => 'NOT LIKE',
282
+		'not like'    => 'NOT LIKE',
283
+		'IN'          => 'IN',
284
+		'in'          => 'IN',
285
+		'NOT_IN'      => 'NOT IN',
286
+		'not_in'      => 'NOT IN',
287
+		'NOT IN'      => 'NOT IN',
288
+		'not in'      => 'NOT IN',
289
+		'between'     => 'BETWEEN',
290
+		'BETWEEN'     => 'BETWEEN',
291
+		'IS_NOT_NULL' => 'IS NOT NULL',
292
+		'is_not_null' => 'IS NOT NULL',
293
+		'IS NOT NULL' => 'IS NOT NULL',
294
+		'is not null' => 'IS NOT NULL',
295
+		'IS_NULL'     => 'IS NULL',
296
+		'is_null'     => 'IS NULL',
297
+		'IS NULL'     => 'IS NULL',
298
+		'is null'     => 'IS NULL',
299
+		'REGEXP'      => 'REGEXP',
300
+		'regexp'      => 'REGEXP',
301
+		'NOT_REGEXP'  => 'NOT REGEXP',
302
+		'not_regexp'  => 'NOT REGEXP',
303
+		'NOT REGEXP'  => 'NOT REGEXP',
304
+		'not regexp'  => 'NOT REGEXP',
305
+	);
306
+
307
+	/**
308
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
309
+	 *
310
+	 * @var array
311
+	 */
312
+	protected $_in_style_operators = array('IN', 'NOT IN');
313
+
314
+	/**
315
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
316
+	 * '12-31-2012'"
317
+	 *
318
+	 * @var array
319
+	 */
320
+	protected $_between_style_operators = array('BETWEEN');
321
+
322
+	/**
323
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
324
+	 * @var array
325
+	 */
326
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
327
+	/**
328
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
329
+	 * on a join table.
330
+	 *
331
+	 * @var array
332
+	 */
333
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
334
+
335
+	/**
336
+	 * Allowed values for $query_params['order'] for ordering in queries
337
+	 *
338
+	 * @var array
339
+	 */
340
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
341
+
342
+	/**
343
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
344
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
345
+	 *
346
+	 * @var array
347
+	 */
348
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
349
+
350
+	/**
351
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
352
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
353
+	 *
354
+	 * @var array
355
+	 */
356
+	private $_allowed_query_params = array(
357
+		0,
358
+		'limit',
359
+		'order_by',
360
+		'group_by',
361
+		'having',
362
+		'force_join',
363
+		'order',
364
+		'on_join_limit',
365
+		'default_where_conditions',
366
+		'caps',
367
+	);
368
+
369
+	/**
370
+	 * All the data types that can be used in $wpdb->prepare statements.
371
+	 *
372
+	 * @var array
373
+	 */
374
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
375
+
376
+	/**
377
+	 *    EE_Registry Object
378
+	 *
379
+	 * @var    object
380
+	 * @access    protected
381
+	 */
382
+	protected $EE = null;
383
+
384
+
385
+	/**
386
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
387
+	 *
388
+	 * @var int
389
+	 */
390
+	protected $_show_next_x_db_queries = 0;
391
+
392
+	/**
393
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
394
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
395
+	 *
396
+	 * @var array
397
+	 */
398
+	protected $_custom_selections = array();
399
+
400
+	/**
401
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
402
+	 * caches every model object we've fetched from the DB on this request
403
+	 *
404
+	 * @var array
405
+	 */
406
+	protected $_entity_map;
407
+
408
+	/**
409
+	 * @var Loader $loader
410
+	 */
411
+	private static $loader;
412
+
413
+
414
+	/**
415
+	 * constant used to show EEM_Base has not yet verified the db on this http request
416
+	 */
417
+	const db_verified_none = 0;
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
421
+	 * but not the addons' dbs
422
+	 */
423
+	const db_verified_core = 1;
424
+
425
+	/**
426
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
427
+	 * the EE core db too)
428
+	 */
429
+	const db_verified_addons = 2;
430
+
431
+	/**
432
+	 * indicates whether an EEM_Base child has already re-verified the DB
433
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
434
+	 * looking like EEM_Base::db_verified_*
435
+	 *
436
+	 * @var int - 0 = none, 1 = core, 2 = addons
437
+	 */
438
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
439
+
440
+	/**
441
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
442
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
443
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
444
+	 */
445
+	const default_where_conditions_all = 'all';
446
+
447
+	/**
448
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
449
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
450
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
451
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
452
+	 *        models which share tables with other models, this can return data for the wrong model.
453
+	 */
454
+	const default_where_conditions_this_only = 'this_model_only';
455
+
456
+	/**
457
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
458
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
459
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
460
+	 */
461
+	const default_where_conditions_others_only = 'other_models_only';
462
+
463
+	/**
464
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
465
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
466
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
467
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
468
+	 *        (regardless of whether those events and venues are trashed)
469
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
470
+	 *        events.
471
+	 */
472
+	const default_where_conditions_minimum_all = 'minimum';
473
+
474
+	/**
475
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
476
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
477
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
478
+	 *        not)
479
+	 */
480
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
481
+
482
+	/**
483
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
484
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
485
+	 *        it's possible it will return table entries for other models. You should use
486
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
487
+	 */
488
+	const default_where_conditions_none = 'none';
489
+
490
+
491
+
492
+	/**
493
+	 * About all child constructors:
494
+	 * they should define the _tables, _fields and _model_relations arrays.
495
+	 * Should ALWAYS be called after child constructor.
496
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
497
+	 * finalizes constructing all the object's attributes.
498
+	 * Generally, rather than requiring a child to code
499
+	 * $this->_tables = array(
500
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
501
+	 *        ...);
502
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
503
+	 * each EE_Table has a function to set the table's alias after the constructor, using
504
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
505
+	 * do something similar.
506
+	 *
507
+	 * @param null $timezone
508
+	 * @throws \EE_Error
509
+	 */
510
+	protected function __construct($timezone = null)
511
+	{
512
+		// check that the model has not been loaded too soon
513
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
514
+			throw new EE_Error (
515
+				sprintf(
516
+					__('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.',
517
+						'event_espresso'),
518
+					get_class($this)
519
+				)
520
+			);
521
+		}
522
+		/**
523
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
524
+		 */
525
+		if (empty(EEM_Base::$_model_query_blog_id)) {
526
+			EEM_Base::set_model_query_blog_id();
527
+		}
528
+		/**
529
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
530
+		 * just use EE_Register_Model_Extension
531
+		 *
532
+		 * @var EE_Table_Base[] $_tables
533
+		 */
534
+		$this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
535
+		foreach ($this->_tables as $table_alias => $table_obj) {
536
+			/** @var $table_obj EE_Table_Base */
537
+			$table_obj->_construct_finalize_with_alias($table_alias);
538
+			if ($table_obj instanceof EE_Secondary_Table) {
539
+				/** @var $table_obj EE_Secondary_Table */
540
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
541
+			}
542
+		}
543
+		/**
544
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
545
+		 * EE_Register_Model_Extension
546
+		 *
547
+		 * @param EE_Model_Field_Base[] $_fields
548
+		 */
549
+		$this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
550
+		$this->_invalidate_field_caches();
551
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
552
+			if (! array_key_exists($table_alias, $this->_tables)) {
553
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
554
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
555
+			}
556
+			foreach ($fields_for_table as $field_name => $field_obj) {
557
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
558
+				//primary key field base has a slightly different _construct_finalize
559
+				/** @var $field_obj EE_Model_Field_Base */
560
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
561
+			}
562
+		}
563
+		// everything is related to Extra_Meta
564
+		if (get_class($this) !== 'EEM_Extra_Meta') {
565
+			//make extra meta related to everything, but don't block deleting things just
566
+			//because they have related extra meta info. For now just orphan those extra meta
567
+			//in the future we should automatically delete them
568
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
569
+		}
570
+		//and change logs
571
+		if (get_class($this) !== 'EEM_Change_Log') {
572
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
573
+		}
574
+		/**
575
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
576
+		 * EE_Register_Model_Extension
577
+		 *
578
+		 * @param EE_Model_Relation_Base[] $_model_relations
579
+		 */
580
+		$this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
581
+			$this->_model_relations);
582
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
583
+			/** @var $relation_obj EE_Model_Relation_Base */
584
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
585
+		}
586
+		foreach ($this->_indexes as $index_name => $index_obj) {
587
+			/** @var $index_obj EE_Index */
588
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
589
+		}
590
+		$this->set_timezone($timezone);
591
+		//finalize default where condition strategy, or set default
592
+		if (! $this->_default_where_conditions_strategy) {
593
+			//nothing was set during child constructor, so set default
594
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
595
+		}
596
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
597
+		if (! $this->_minimum_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
602
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
603
+		//to indicate to NOT set it, set it to the logical default
604
+		if ($this->_caps_slug === null) {
605
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
606
+		}
607
+		//initialize the standard cap restriction generators if none were specified by the child constructor
608
+		if ($this->_cap_restriction_generators !== false) {
609
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
610
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
611
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
612
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
613
+						new EE_Restriction_Generator_Protected(),
614
+						$cap_context,
615
+						$this
616
+					);
617
+				}
618
+			}
619
+		}
620
+		//if there are cap restriction generators, use them to make the default cap restrictions
621
+		if ($this->_cap_restriction_generators !== false) {
622
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
623
+				if (! $generator_object) {
624
+					continue;
625
+				}
626
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
627
+					throw new EE_Error(
628
+						sprintf(
629
+							__('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.',
630
+								'event_espresso'),
631
+							$context,
632
+							$this->get_this_model_name()
633
+						)
634
+					);
635
+				}
636
+				$action = $this->cap_action_for_context($context);
637
+				if (! $generator_object->construction_finalized()) {
638
+					$generator_object->_construct_finalize($this, $action);
639
+				}
640
+			}
641
+		}
642
+		do_action('AHEE__' . get_class($this) . '__construct__end');
643
+	}
644
+
645
+
646
+
647
+	/**
648
+	 * Used to set the $_model_query_blog_id static property.
649
+	 *
650
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
651
+	 *                      value for get_current_blog_id() will be used.
652
+	 */
653
+	public static function set_model_query_blog_id($blog_id = 0)
654
+	{
655
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
656
+	}
657
+
658
+
659
+
660
+	/**
661
+	 * Returns whatever is set as the internal $model_query_blog_id.
662
+	 *
663
+	 * @return int
664
+	 */
665
+	public static function get_model_query_blog_id()
666
+	{
667
+		return EEM_Base::$_model_query_blog_id;
668
+	}
669
+
670
+
671
+
672
+	/**
673
+	 *        This function is a singleton method used to instantiate the Espresso_model object
674
+	 *
675
+	 * @access public
676
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
677
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
678
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
679
+	 *                         timezone in the 'timezone_string' wp option)
680
+	 * @return static (as in the concrete child class)
681
+	 */
682
+	public static function instance($timezone = null)
683
+	{
684
+		// check if instance of Espresso_model already exists
685
+		if (! static::$_instance instanceof static) {
686
+			// instantiate Espresso_model
687
+			static::$_instance = new static($timezone, self::getLoader());
688
+		}
689
+		//we might have a timezone set, let set_timezone decide what to do with it
690
+		static::$_instance->set_timezone($timezone);
691
+		// Espresso_model object
692
+		return static::$_instance;
693
+	}
694
+
695
+
696
+
697
+	/**
698
+	 * resets the model and returns it
699
+	 *
700
+	 * @param null | string $timezone
701
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
702
+	 * all its properties reset; if it wasn't instantiated, returns null)
703
+	 */
704
+	public static function reset($timezone = null)
705
+	{
706
+		if (static::$_instance instanceof EEM_Base) {
707
+			//let's try to NOT swap out the current instance for a new one
708
+			//because if someone has a reference to it, we can't remove their reference
709
+			//so it's best to keep using the same reference, but change the original object
710
+			//reset all its properties to their original values as defined in the class
711
+			$r = new ReflectionClass(get_class(static::$_instance));
712
+			$static_properties = $r->getStaticProperties();
713
+			foreach ($r->getDefaultProperties() as $property => $value) {
714
+				//don't set instance to null like it was originally,
715
+				//but it's static anyways, and we're ignoring static properties (for now at least)
716
+				if (! isset($static_properties[$property])) {
717
+					static::$_instance->{$property} = $value;
718
+				}
719
+			}
720
+			//and then directly call its constructor again, like we would if we
721
+			//were creating a new one
722
+			static::$_instance->__construct($timezone, self::getLoader());
723
+			return self::instance();
724
+		}
725
+		return null;
726
+	}
727
+
728
+
729
+
730
+	private static function getLoader()
731
+	{
732
+		if(! self::$loader instanceof Loader) {
733
+			self::$loader = new Loader();
734
+		}
735
+		return self::$loader;
736
+	}
737
+
738
+	/**
739
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
740
+	 *
741
+	 * @param  boolean $translated return localized strings or JUST the array.
742
+	 * @return array
743
+	 * @throws \EE_Error
744
+	 */
745
+	public function status_array($translated = false)
746
+	{
747
+		if (! array_key_exists('Status', $this->_model_relations)) {
748
+			return array();
749
+		}
750
+		$model_name = $this->get_this_model_name();
751
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
752
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
753
+		$status_array = array();
754
+		foreach ($stati as $status) {
755
+			$status_array[$status->ID()] = $status->get('STS_code');
756
+		}
757
+		return $translated
758
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
759
+			: $status_array;
760
+	}
761
+
762
+
763
+
764
+	/**
765
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
766
+	 *
767
+	 * @param array $query_params             {
768
+	 * @var array $0 (where) array {
769
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
770
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
771
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
772
+	 *                                        conditions based on related models (and even
773
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
774
+	 *                                        name. Eg,
775
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
776
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
777
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
778
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
779
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
780
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
781
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
782
+	 *                                        to Venues (even when each of those models actually consisted of two
783
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
784
+	 *                                        just having
785
+	 *                                        "Venue.VNU_ID", you could have
786
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
787
+	 *                                        events are related to Registrations, which are related to Attendees). You
788
+	 *                                        can take it even further with
789
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
790
+	 *                                        (from the default of '='), change the value to an numerically-indexed
791
+	 *                                        array, where the first item in the list is the operator. eg: array(
792
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
793
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
794
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
795
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
796
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
797
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
798
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
799
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
800
+	 *                                        the value is a field, simply provide a third array item (true) to the
801
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
802
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
803
+	 *                                        Note: you can also use related model field names like you would any other
804
+	 *                                        field name. eg:
805
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
806
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
807
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
808
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
809
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
810
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
811
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
812
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
813
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
814
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
815
+	 *                                        "stick" until you specify an AND. eg
816
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
817
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
818
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
819
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
820
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
821
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
822
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
823
+	 *                                        too, eg:
824
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
825
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
826
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
827
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
828
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
829
+	 *                                        the OFFSET, the 2nd is the LIMIT
830
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
831
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
832
+	 *                                        following format array('on_join_limit'
833
+	 *                                        => array( 'table_alias', array(1,2) ) ).
834
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
835
+	 *                                        values are either 'ASC' or 'DESC'.
836
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
837
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
838
+	 *                                        DESC..." respectively. Like the
839
+	 *                                        'where' conditions, these fields can be on related models. Eg
840
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
841
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
842
+	 *                                        Attendee, Price, Datetime, etc.)
843
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
844
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
845
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
846
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
847
+	 *                                        order by the primary key. Eg,
848
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
849
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
850
+	 *                                        DTT_EVT_start) or
851
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
852
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
853
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
854
+	 *                                        'group_by'=>'VNU_ID', or
855
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
856
+	 *                                        if no
857
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
858
+	 *                                        model's primary key (or combined primary keys). This avoids some
859
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
860
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
861
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
862
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
863
+	 *                                        results)
864
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
865
+	 *                                        array where values are models to be joined in the query.Eg
866
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
867
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
868
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
869
+	 *                                        related models which belongs to the current model
870
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
871
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
872
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
873
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
874
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
875
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
876
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
877
+	 *                                        this model's default where conditions added to the query, use
878
+	 *                                        'this_model_only'. If you want to use all default where conditions
879
+	 *                                        (default), set to 'all'.
880
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
881
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
882
+	 *                                        everything? Or should we only show the current user items they should be
883
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
884
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
885
+	 *                                        }
886
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
887
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
888
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
889
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
890
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
891
+	 *                                        array( array(
892
+	 *                                        'OR'=>array(
893
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
894
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
895
+	 *                                        )
896
+	 *                                        ),
897
+	 *                                        'limit'=>10,
898
+	 *                                        'group_by'=>'TXN_ID'
899
+	 *                                        ));
900
+	 *                                        get all the answers to the question titled "shirt size" for event with id
901
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
902
+	 *                                        'Question.QST_display_text'=>'shirt size',
903
+	 *                                        'Registration.Event.EVT_ID'=>12
904
+	 *                                        ),
905
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
906
+	 *                                        ));
907
+	 * @throws \EE_Error
908
+	 */
909
+	public function get_all($query_params = array())
910
+	{
911
+		if (isset($query_params['limit'])
912
+			&& ! isset($query_params['group_by'])
913
+		) {
914
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
915
+		}
916
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
917
+	}
918
+
919
+
920
+
921
+	/**
922
+	 * Modifies the query parameters so we only get back model objects
923
+	 * that "belong" to the current user
924
+	 *
925
+	 * @param array $query_params @see EEM_Base::get_all()
926
+	 * @return array like EEM_Base::get_all
927
+	 */
928
+	public function alter_query_params_to_only_include_mine($query_params = array())
929
+	{
930
+		$wp_user_field_name = $this->wp_user_field_name();
931
+		if ($wp_user_field_name) {
932
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
933
+		}
934
+		return $query_params;
935
+	}
936
+
937
+
938
+
939
+	/**
940
+	 * Returns the name of the field's name that points to the WP_User table
941
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
942
+	 * foreign key to the WP_User table)
943
+	 *
944
+	 * @return string|boolean string on success, boolean false when there is no
945
+	 * foreign key to the WP_User table
946
+	 */
947
+	public function wp_user_field_name()
948
+	{
949
+		try {
950
+			if (! empty($this->_model_chain_to_wp_user)) {
951
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
952
+				$last_model_name = end($models_to_follow_to_wp_users);
953
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
954
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
955
+			} else {
956
+				$model_with_fk_to_wp_users = $this;
957
+				$model_chain_to_wp_user = '';
958
+			}
959
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
960
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
961
+		} catch (EE_Error $e) {
962
+			return false;
963
+		}
964
+	}
965
+
966
+
967
+
968
+	/**
969
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
970
+	 * (or transiently-related model) has a foreign key to the wp_users table;
971
+	 * useful for finding if model objects of this type are 'owned' by the current user.
972
+	 * This is an empty string when the foreign key is on this model and when it isn't,
973
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
974
+	 * (or transiently-related model)
975
+	 *
976
+	 * @return string
977
+	 */
978
+	public function model_chain_to_wp_user()
979
+	{
980
+		return $this->_model_chain_to_wp_user;
981
+	}
982
+
983
+
984
+
985
+	/**
986
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
987
+	 * like how registrations don't have a foreign key to wp_users, but the
988
+	 * events they are for are), or is unrelated to wp users.
989
+	 * generally available
990
+	 *
991
+	 * @return boolean
992
+	 */
993
+	public function is_owned()
994
+	{
995
+		if ($this->model_chain_to_wp_user()) {
996
+			return true;
997
+		} else {
998
+			try {
999
+				$this->get_foreign_key_to('WP_User');
1000
+				return true;
1001
+			} catch (EE_Error $e) {
1002
+				return false;
1003
+			}
1004
+		}
1005
+	}
1006
+
1007
+
1008
+
1009
+	/**
1010
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1011
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1012
+	 * the model)
1013
+	 *
1014
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1015
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1016
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1017
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1018
+	 *                                  override this and set the select to "*", or a specific column name, like
1019
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1020
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1021
+	 *                                  the aliases used to refer to this selection, and values are to be
1022
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1023
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1024
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1025
+	 * @throws \EE_Error
1026
+	 */
1027
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1028
+	{
1029
+		// remember the custom selections, if any, and type cast as array
1030
+		// (unless $columns_to_select is an object, then just set as an empty array)
1031
+		// Note: (array) 'some string' === array( 'some string' )
1032
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1033
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1034
+		$select_expressions = $columns_to_select !== null
1035
+			? $this->_construct_select_from_input($columns_to_select)
1036
+			: $this->_construct_default_select_sql($model_query_info);
1037
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1038
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1039
+	}
1040
+
1041
+
1042
+
1043
+	/**
1044
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1045
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1046
+	 * take care of joins, field preparation etc.
1047
+	 *
1048
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1049
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1050
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1051
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1052
+	 *                                  override this and set the select to "*", or a specific column name, like
1053
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1054
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1055
+	 *                                  the aliases used to refer to this selection, and values are to be
1056
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1057
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1058
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1059
+	 * @throws \EE_Error
1060
+	 */
1061
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1062
+	{
1063
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1064
+	}
1065
+
1066
+
1067
+
1068
+	/**
1069
+	 * For creating a custom select statement
1070
+	 *
1071
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1072
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1073
+	 *                                 SQL, and 1=>is the datatype
1074
+	 * @throws EE_Error
1075
+	 * @return string
1076
+	 */
1077
+	private function _construct_select_from_input($columns_to_select)
1078
+	{
1079
+		if (is_array($columns_to_select)) {
1080
+			$select_sql_array = array();
1081
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1082
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1083
+					throw new EE_Error(
1084
+						sprintf(
1085
+							__(
1086
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1087
+								"event_espresso"
1088
+							),
1089
+							$selection_and_datatype,
1090
+							$alias
1091
+						)
1092
+					);
1093
+				}
1094
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1095
+					throw new EE_Error(
1096
+						sprintf(
1097
+							__(
1098
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1099
+								"event_espresso"
1100
+							),
1101
+							$selection_and_datatype[1],
1102
+							$selection_and_datatype[0],
1103
+							$alias,
1104
+							implode(",", $this->_valid_wpdb_data_types)
1105
+						)
1106
+					);
1107
+				}
1108
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1109
+			}
1110
+			$columns_to_select_string = implode(", ", $select_sql_array);
1111
+		} else {
1112
+			$columns_to_select_string = $columns_to_select;
1113
+		}
1114
+		return $columns_to_select_string;
1115
+	}
1116
+
1117
+
1118
+
1119
+	/**
1120
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1121
+	 *
1122
+	 * @return string
1123
+	 * @throws \EE_Error
1124
+	 */
1125
+	public function primary_key_name()
1126
+	{
1127
+		return $this->get_primary_key_field()->get_name();
1128
+	}
1129
+
1130
+
1131
+
1132
+	/**
1133
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1134
+	 * If there is no primary key on this model, $id is treated as primary key string
1135
+	 *
1136
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1137
+	 * @return EE_Base_Class
1138
+	 */
1139
+	public function get_one_by_ID($id)
1140
+	{
1141
+		if ($this->get_from_entity_map($id)) {
1142
+			return $this->get_from_entity_map($id);
1143
+		}
1144
+		return $this->get_one(
1145
+			$this->alter_query_params_to_restrict_by_ID(
1146
+				$id,
1147
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1148
+			)
1149
+		);
1150
+	}
1151
+
1152
+
1153
+
1154
+	/**
1155
+	 * Alters query parameters to only get items with this ID are returned.
1156
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1157
+	 * or could just be a simple primary key ID
1158
+	 *
1159
+	 * @param int   $id
1160
+	 * @param array $query_params
1161
+	 * @return array of normal query params, @see EEM_Base::get_all
1162
+	 * @throws \EE_Error
1163
+	 */
1164
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1165
+	{
1166
+		if (! isset($query_params[0])) {
1167
+			$query_params[0] = array();
1168
+		}
1169
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1170
+		if ($conditions_from_id === null) {
1171
+			$query_params[0][$this->primary_key_name()] = $id;
1172
+		} else {
1173
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1174
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1175
+		}
1176
+		return $query_params;
1177
+	}
1178
+
1179
+
1180
+
1181
+	/**
1182
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1183
+	 * array. If no item is found, null is returned.
1184
+	 *
1185
+	 * @param array $query_params like EEM_Base's $query_params variable.
1186
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1187
+	 * @throws \EE_Error
1188
+	 */
1189
+	public function get_one($query_params = array())
1190
+	{
1191
+		if (! is_array($query_params)) {
1192
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1193
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1194
+					gettype($query_params)), '4.6.0');
1195
+			$query_params = array();
1196
+		}
1197
+		$query_params['limit'] = 1;
1198
+		$items = $this->get_all($query_params);
1199
+		if (empty($items)) {
1200
+			return null;
1201
+		} else {
1202
+			return array_shift($items);
1203
+		}
1204
+	}
1205
+
1206
+
1207
+
1208
+	/**
1209
+	 * Returns the next x number of items in sequence from the given value as
1210
+	 * found in the database matching the given query conditions.
1211
+	 *
1212
+	 * @param mixed $current_field_value    Value used for the reference point.
1213
+	 * @param null  $field_to_order_by      What field is used for the
1214
+	 *                                      reference point.
1215
+	 * @param int   $limit                  How many to return.
1216
+	 * @param array $query_params           Extra conditions on the query.
1217
+	 * @param null  $columns_to_select      If left null, then an array of
1218
+	 *                                      EE_Base_Class objects is returned,
1219
+	 *                                      otherwise you can indicate just the
1220
+	 *                                      columns you want returned.
1221
+	 * @return EE_Base_Class[]|array
1222
+	 * @throws \EE_Error
1223
+	 */
1224
+	public function next_x(
1225
+		$current_field_value,
1226
+		$field_to_order_by = null,
1227
+		$limit = 1,
1228
+		$query_params = array(),
1229
+		$columns_to_select = null
1230
+	) {
1231
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1232
+			$columns_to_select);
1233
+	}
1234
+
1235
+
1236
+
1237
+	/**
1238
+	 * Returns the previous x number of items in sequence from the given value
1239
+	 * as found in the database matching the given query conditions.
1240
+	 *
1241
+	 * @param mixed $current_field_value    Value used for the reference point.
1242
+	 * @param null  $field_to_order_by      What field is used for the
1243
+	 *                                      reference point.
1244
+	 * @param int   $limit                  How many to return.
1245
+	 * @param array $query_params           Extra conditions on the query.
1246
+	 * @param null  $columns_to_select      If left null, then an array of
1247
+	 *                                      EE_Base_Class objects is returned,
1248
+	 *                                      otherwise you can indicate just the
1249
+	 *                                      columns you want returned.
1250
+	 * @return EE_Base_Class[]|array
1251
+	 * @throws \EE_Error
1252
+	 */
1253
+	public function previous_x(
1254
+		$current_field_value,
1255
+		$field_to_order_by = null,
1256
+		$limit = 1,
1257
+		$query_params = array(),
1258
+		$columns_to_select = null
1259
+	) {
1260
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1261
+			$columns_to_select);
1262
+	}
1263
+
1264
+
1265
+
1266
+	/**
1267
+	 * Returns the next item in sequence from the given value as found in the
1268
+	 * database matching the given query conditions.
1269
+	 *
1270
+	 * @param mixed $current_field_value    Value used for the reference point.
1271
+	 * @param null  $field_to_order_by      What field is used for the
1272
+	 *                                      reference point.
1273
+	 * @param array $query_params           Extra conditions on the query.
1274
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1275
+	 *                                      object is returned, otherwise you
1276
+	 *                                      can indicate just the columns you
1277
+	 *                                      want and a single array indexed by
1278
+	 *                                      the columns will be returned.
1279
+	 * @return EE_Base_Class|null|array()
1280
+	 * @throws \EE_Error
1281
+	 */
1282
+	public function next(
1283
+		$current_field_value,
1284
+		$field_to_order_by = null,
1285
+		$query_params = array(),
1286
+		$columns_to_select = null
1287
+	) {
1288
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1289
+			$columns_to_select);
1290
+		return empty($results) ? null : reset($results);
1291
+	}
1292
+
1293
+
1294
+
1295
+	/**
1296
+	 * Returns the previous item in sequence from the given value as found in
1297
+	 * the database matching the given query conditions.
1298
+	 *
1299
+	 * @param mixed $current_field_value    Value used for the reference point.
1300
+	 * @param null  $field_to_order_by      What field is used for the
1301
+	 *                                      reference point.
1302
+	 * @param array $query_params           Extra conditions on the query.
1303
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1304
+	 *                                      object is returned, otherwise you
1305
+	 *                                      can indicate just the columns you
1306
+	 *                                      want and a single array indexed by
1307
+	 *                                      the columns will be returned.
1308
+	 * @return EE_Base_Class|null|array()
1309
+	 * @throws EE_Error
1310
+	 */
1311
+	public function previous(
1312
+		$current_field_value,
1313
+		$field_to_order_by = null,
1314
+		$query_params = array(),
1315
+		$columns_to_select = null
1316
+	) {
1317
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1318
+			$columns_to_select);
1319
+		return empty($results) ? null : reset($results);
1320
+	}
1321
+
1322
+
1323
+
1324
+	/**
1325
+	 * Returns the a consecutive number of items in sequence from the given
1326
+	 * value as found in the database matching the given query conditions.
1327
+	 *
1328
+	 * @param mixed  $current_field_value   Value used for the reference point.
1329
+	 * @param string $operand               What operand is used for the sequence.
1330
+	 * @param string $field_to_order_by     What field is used for the reference point.
1331
+	 * @param int    $limit                 How many to return.
1332
+	 * @param array  $query_params          Extra conditions on the query.
1333
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1334
+	 *                                      otherwise you can indicate just the columns you want returned.
1335
+	 * @return EE_Base_Class[]|array
1336
+	 * @throws EE_Error
1337
+	 */
1338
+	protected function _get_consecutive(
1339
+		$current_field_value,
1340
+		$operand = '>',
1341
+		$field_to_order_by = null,
1342
+		$limit = 1,
1343
+		$query_params = array(),
1344
+		$columns_to_select = null
1345
+	) {
1346
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1347
+		if (empty($field_to_order_by)) {
1348
+			if ($this->has_primary_key_field()) {
1349
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1350
+			} else {
1351
+				if (WP_DEBUG) {
1352
+					throw new EE_Error(__('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).',
1353
+						'event_espresso'));
1354
+				}
1355
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1356
+				return array();
1357
+			}
1358
+		}
1359
+		if (! is_array($query_params)) {
1360
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1361
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1362
+					gettype($query_params)), '4.6.0');
1363
+			$query_params = array();
1364
+		}
1365
+		//let's add the where query param for consecutive look up.
1366
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1367
+		$query_params['limit'] = $limit;
1368
+		//set direction
1369
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1370
+		$query_params['order_by'] = $operand === '>'
1371
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1372
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1373
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1374
+		if (empty($columns_to_select)) {
1375
+			return $this->get_all($query_params);
1376
+		} else {
1377
+			//getting just the fields
1378
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1379
+		}
1380
+	}
1381
+
1382
+
1383
+
1384
+	/**
1385
+	 * This sets the _timezone property after model object has been instantiated.
1386
+	 *
1387
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1388
+	 */
1389
+	public function set_timezone($timezone)
1390
+	{
1391
+		if ($timezone !== null) {
1392
+			$this->_timezone = $timezone;
1393
+		}
1394
+		//note we need to loop through relations and set the timezone on those objects as well.
1395
+		foreach ($this->_model_relations as $relation) {
1396
+			$relation->set_timezone($timezone);
1397
+		}
1398
+		//and finally we do the same for any datetime fields
1399
+		foreach ($this->_fields as $field) {
1400
+			if ($field instanceof EE_Datetime_Field) {
1401
+				$field->set_timezone($timezone);
1402
+			}
1403
+		}
1404
+	}
1405
+
1406
+
1407
+
1408
+	/**
1409
+	 * This just returns whatever is set for the current timezone.
1410
+	 *
1411
+	 * @access public
1412
+	 * @return string
1413
+	 */
1414
+	public function get_timezone()
1415
+	{
1416
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1417
+		if (empty($this->_timezone)) {
1418
+			foreach ($this->_fields as $field) {
1419
+				if ($field instanceof EE_Datetime_Field) {
1420
+					$this->set_timezone($field->get_timezone());
1421
+					break;
1422
+				}
1423
+			}
1424
+		}
1425
+		//if timezone STILL empty then return the default timezone for the site.
1426
+		if (empty($this->_timezone)) {
1427
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1428
+		}
1429
+		return $this->_timezone;
1430
+	}
1431
+
1432
+
1433
+
1434
+	/**
1435
+	 * This returns the date formats set for the given field name and also ensures that
1436
+	 * $this->_timezone property is set correctly.
1437
+	 *
1438
+	 * @since 4.6.x
1439
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1440
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1441
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1442
+	 * @return array formats in an array with the date format first, and the time format last.
1443
+	 */
1444
+	public function get_formats_for($field_name, $pretty = false)
1445
+	{
1446
+		$field_settings = $this->field_settings_for($field_name);
1447
+		//if not a valid EE_Datetime_Field then throw error
1448
+		if (! $field_settings instanceof EE_Datetime_Field) {
1449
+			throw new EE_Error(sprintf(__('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.',
1450
+				'event_espresso'), $field_name));
1451
+		}
1452
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1453
+		//the field.
1454
+		$this->_timezone = $field_settings->get_timezone();
1455
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1456
+	}
1457
+
1458
+
1459
+
1460
+	/**
1461
+	 * This returns the current time in a format setup for a query on this model.
1462
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1463
+	 * it will return:
1464
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1465
+	 *  NOW
1466
+	 *  - or a unix timestamp (equivalent to time())
1467
+	 *
1468
+	 * @since 4.6.x
1469
+	 * @param string $field_name       The field the current time is needed for.
1470
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1471
+	 *                                 formatted string matching the set format for the field in the set timezone will
1472
+	 *                                 be returned.
1473
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1474
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1475
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1476
+	 *                                 exception is triggered.
1477
+	 */
1478
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1479
+	{
1480
+		$formats = $this->get_formats_for($field_name);
1481
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1482
+		if ($timestamp) {
1483
+			return $DateTime->format('U');
1484
+		}
1485
+		//not returning timestamp, so return formatted string in timezone.
1486
+		switch ($what) {
1487
+			case 'time' :
1488
+				return $DateTime->format($formats[1]);
1489
+				break;
1490
+			case 'date' :
1491
+				return $DateTime->format($formats[0]);
1492
+				break;
1493
+			default :
1494
+				return $DateTime->format(implode(' ', $formats));
1495
+				break;
1496
+		}
1497
+	}
1498
+
1499
+
1500
+
1501
+	/**
1502
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1503
+	 * for the model are.  Returns a DateTime object.
1504
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1505
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1506
+	 * ignored.
1507
+	 *
1508
+	 * @param string $field_name      The field being setup.
1509
+	 * @param string $timestring      The date time string being used.
1510
+	 * @param string $incoming_format The format for the time string.
1511
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1512
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1513
+	 *                                format is
1514
+	 *                                'U', this is ignored.
1515
+	 * @return DateTime
1516
+	 * @throws \EE_Error
1517
+	 */
1518
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1519
+	{
1520
+		//just using this to ensure the timezone is set correctly internally
1521
+		$this->get_formats_for($field_name);
1522
+		//load EEH_DTT_Helper
1523
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1524
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1525
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1526
+	}
1527
+
1528
+
1529
+
1530
+	/**
1531
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1532
+	 *
1533
+	 * @return EE_Table_Base[]
1534
+	 */
1535
+	public function get_tables()
1536
+	{
1537
+		return $this->_tables;
1538
+	}
1539
+
1540
+
1541
+
1542
+	/**
1543
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1544
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1545
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1546
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1547
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1548
+	 * model object with EVT_ID = 1
1549
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1550
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1551
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1552
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1553
+	 * are not specified)
1554
+	 *
1555
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1556
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1557
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1558
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1559
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1560
+	 *                                         ID=34, we'd use this method as follows:
1561
+	 *                                         EEM_Transaction::instance()->update(
1562
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1563
+	 *                                         array(array('TXN_ID'=>34)));
1564
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1565
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1566
+	 *                                         consider updating Question's QST_admin_label field is of type
1567
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1568
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1569
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1570
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1571
+	 *                                         TRUE, it is assumed that you've already called
1572
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1573
+	 *                                         malicious javascript. However, if
1574
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1575
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1576
+	 *                                         and every other field, before insertion. We provide this parameter
1577
+	 *                                         because model objects perform their prepare_for_set function on all
1578
+	 *                                         their values, and so don't need to be called again (and in many cases,
1579
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1580
+	 *                                         prepare_for_set method...)
1581
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1582
+	 *                                         in this model's entity map according to $fields_n_values that match
1583
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1584
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1585
+	 *                                         could get out-of-sync with the database
1586
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1587
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1588
+	 *                                         bad)
1589
+	 * @throws \EE_Error
1590
+	 */
1591
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1592
+	{
1593
+		if (! is_array($query_params)) {
1594
+			EE_Error::doing_it_wrong('EEM_Base::update',
1595
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1596
+					gettype($query_params)), '4.6.0');
1597
+			$query_params = array();
1598
+		}
1599
+		/**
1600
+		 * Action called before a model update call has been made.
1601
+		 *
1602
+		 * @param EEM_Base $model
1603
+		 * @param array    $fields_n_values the updated fields and their new values
1604
+		 * @param array    $query_params    @see EEM_Base::get_all()
1605
+		 */
1606
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1607
+		/**
1608
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1609
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1610
+		 *
1611
+		 * @param array    $fields_n_values fields and their new values
1612
+		 * @param EEM_Base $model           the model being queried
1613
+		 * @param array    $query_params    see EEM_Base::get_all()
1614
+		 */
1615
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1616
+			$query_params);
1617
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1618
+		//to do that, for each table, verify that it's PK isn't null.
1619
+		$tables = $this->get_tables();
1620
+		//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
1621
+		//NOTE: we should make this code more efficient by NOT querying twice
1622
+		//before the real update, but that needs to first go through ALPHA testing
1623
+		//as it's dangerous. says Mike August 8 2014
1624
+		//we want to make sure the default_where strategy is ignored
1625
+		$this->_ignore_where_strategy = true;
1626
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1627
+		foreach ($wpdb_select_results as $wpdb_result) {
1628
+			// type cast stdClass as array
1629
+			$wpdb_result = (array)$wpdb_result;
1630
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1631
+			if ($this->has_primary_key_field()) {
1632
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1633
+			} else {
1634
+				//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)
1635
+				$main_table_pk_value = null;
1636
+			}
1637
+			//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
1638
+			//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
1639
+			if (count($tables) > 1) {
1640
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1641
+				//in that table, and so we'll want to insert one
1642
+				foreach ($tables as $table_obj) {
1643
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1644
+					//if there is no private key for this table on the results, it means there's no entry
1645
+					//in this table, right? so insert a row in the current table, using any fields available
1646
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1647
+						   && $wpdb_result[$this_table_pk_column])
1648
+					) {
1649
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1650
+							$main_table_pk_value);
1651
+						//if we died here, report the error
1652
+						if (! $success) {
1653
+							return false;
1654
+						}
1655
+					}
1656
+				}
1657
+			}
1658
+			//				//and now check that if we have cached any models by that ID on the model, that
1659
+			//				//they also get updated properly
1660
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1661
+			//				if( $model_object ){
1662
+			//					foreach( $fields_n_values as $field => $value ){
1663
+			//						$model_object->set($field, $value);
1664
+			//let's make sure default_where strategy is followed now
1665
+			$this->_ignore_where_strategy = false;
1666
+		}
1667
+		//if we want to keep model objects in sync, AND
1668
+		//if this wasn't called from a model object (to update itself)
1669
+		//then we want to make sure we keep all the existing
1670
+		//model objects in sync with the db
1671
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1672
+			if ($this->has_primary_key_field()) {
1673
+				$model_objs_affected_ids = $this->get_col($query_params);
1674
+			} else {
1675
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1676
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1677
+				$model_objs_affected_ids = array();
1678
+				foreach ($models_affected_key_columns as $row) {
1679
+					$combined_index_key = $this->get_index_primary_key_string($row);
1680
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1681
+				}
1682
+			}
1683
+			if (! $model_objs_affected_ids) {
1684
+				//wait wait wait- if nothing was affected let's stop here
1685
+				return 0;
1686
+			}
1687
+			foreach ($model_objs_affected_ids as $id) {
1688
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1689
+				if ($model_obj_in_entity_map) {
1690
+					foreach ($fields_n_values as $field => $new_value) {
1691
+						$model_obj_in_entity_map->set($field, $new_value);
1692
+					}
1693
+				}
1694
+			}
1695
+			//if there is a primary key on this model, we can now do a slight optimization
1696
+			if ($this->has_primary_key_field()) {
1697
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1698
+				$query_params = array(
1699
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1700
+					'limit'                    => count($model_objs_affected_ids),
1701
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1702
+				);
1703
+			}
1704
+		}
1705
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1706
+		$SQL = "UPDATE "
1707
+			   . $model_query_info->get_full_join_sql()
1708
+			   . " SET "
1709
+			   . $this->_construct_update_sql($fields_n_values)
1710
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1711
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1712
+		/**
1713
+		 * Action called after a model update call has been made.
1714
+		 *
1715
+		 * @param EEM_Base $model
1716
+		 * @param array    $fields_n_values the updated fields and their new values
1717
+		 * @param array    $query_params    @see EEM_Base::get_all()
1718
+		 * @param int      $rows_affected
1719
+		 */
1720
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1721
+		return $rows_affected;//how many supposedly got updated
1722
+	}
1723
+
1724
+
1725
+
1726
+	/**
1727
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1728
+	 * are teh values of the field specified (or by default the primary key field)
1729
+	 * that matched the query params. Note that you should pass the name of the
1730
+	 * model FIELD, not the database table's column name.
1731
+	 *
1732
+	 * @param array  $query_params @see EEM_Base::get_all()
1733
+	 * @param string $field_to_select
1734
+	 * @return array just like $wpdb->get_col()
1735
+	 * @throws \EE_Error
1736
+	 */
1737
+	public function get_col($query_params = array(), $field_to_select = null)
1738
+	{
1739
+		if ($field_to_select) {
1740
+			$field = $this->field_settings_for($field_to_select);
1741
+		} elseif ($this->has_primary_key_field()) {
1742
+			$field = $this->get_primary_key_field();
1743
+		} else {
1744
+			//no primary key, just grab the first column
1745
+			$field = reset($this->field_settings());
1746
+		}
1747
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1748
+		$select_expressions = $field->get_qualified_column();
1749
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1750
+		return $this->_do_wpdb_query('get_col', array($SQL));
1751
+	}
1752
+
1753
+
1754
+
1755
+	/**
1756
+	 * Returns a single column value for a single row from the database
1757
+	 *
1758
+	 * @param array  $query_params    @see EEM_Base::get_all()
1759
+	 * @param string $field_to_select @see EEM_Base::get_col()
1760
+	 * @return string
1761
+	 * @throws \EE_Error
1762
+	 */
1763
+	public function get_var($query_params = array(), $field_to_select = null)
1764
+	{
1765
+		$query_params['limit'] = 1;
1766
+		$col = $this->get_col($query_params, $field_to_select);
1767
+		if (! empty($col)) {
1768
+			return reset($col);
1769
+		} else {
1770
+			return null;
1771
+		}
1772
+	}
1773
+
1774
+
1775
+
1776
+	/**
1777
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1778
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1779
+	 * injection, but currently no further filtering is done
1780
+	 *
1781
+	 * @global      $wpdb
1782
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1783
+	 *                               be updated to in the DB
1784
+	 * @return string of SQL
1785
+	 * @throws \EE_Error
1786
+	 */
1787
+	public function _construct_update_sql($fields_n_values)
1788
+	{
1789
+		/** @type WPDB $wpdb */
1790
+		global $wpdb;
1791
+		$cols_n_values = array();
1792
+		foreach ($fields_n_values as $field_name => $value) {
1793
+			$field_obj = $this->field_settings_for($field_name);
1794
+			//if the value is NULL, we want to assign the value to that.
1795
+			//wpdb->prepare doesn't really handle that properly
1796
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1797
+			$value_sql = $prepared_value === null ? 'NULL'
1798
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1799
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1800
+		}
1801
+		return implode(",", $cols_n_values);
1802
+	}
1803
+
1804
+
1805
+
1806
+	/**
1807
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1808
+	 * Performs a HARD delete, meaning the database row should always be removed,
1809
+	 * not just have a flag field on it switched
1810
+	 * Wrapper for EEM_Base::delete_permanently()
1811
+	 *
1812
+	 * @param mixed $id
1813
+	 * @param boolean $allow_blocking
1814
+	 * @return int the number of rows deleted
1815
+	 * @throws \EE_Error
1816
+	 */
1817
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1818
+	{
1819
+		return $this->delete_permanently(
1820
+			array(
1821
+				array($this->get_primary_key_field()->get_name() => $id),
1822
+				'limit' => 1,
1823
+			),
1824
+			$allow_blocking
1825
+		);
1826
+	}
1827
+
1828
+
1829
+
1830
+	/**
1831
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1832
+	 * Wrapper for EEM_Base::delete()
1833
+	 *
1834
+	 * @param mixed $id
1835
+	 * @param boolean $allow_blocking
1836
+	 * @return int the number of rows deleted
1837
+	 * @throws \EE_Error
1838
+	 */
1839
+	public function delete_by_ID($id, $allow_blocking = true)
1840
+	{
1841
+		return $this->delete(
1842
+			array(
1843
+				array($this->get_primary_key_field()->get_name() => $id),
1844
+				'limit' => 1,
1845
+			),
1846
+			$allow_blocking
1847
+		);
1848
+	}
1849
+
1850
+
1851
+
1852
+	/**
1853
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1854
+	 * meaning if the model has a field that indicates its been "trashed" or
1855
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1856
+	 *
1857
+	 * @see EEM_Base::delete_permanently
1858
+	 * @param array   $query_params
1859
+	 * @param boolean $allow_blocking
1860
+	 * @return int how many rows got deleted
1861
+	 * @throws \EE_Error
1862
+	 */
1863
+	public function delete($query_params, $allow_blocking = true)
1864
+	{
1865
+		return $this->delete_permanently($query_params, $allow_blocking);
1866
+	}
1867
+
1868
+
1869
+
1870
+	/**
1871
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1872
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1873
+	 * as archived, not actually deleted
1874
+	 *
1875
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1876
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1877
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1878
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1879
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1880
+	 *                                DB
1881
+	 * @return int how many rows got deleted
1882
+	 * @throws \EE_Error
1883
+	 */
1884
+	public function delete_permanently($query_params, $allow_blocking = true)
1885
+	{
1886
+		/**
1887
+		 * Action called just before performing a real deletion query. You can use the
1888
+		 * model and its $query_params to find exactly which items will be deleted
1889
+		 *
1890
+		 * @param EEM_Base $model
1891
+		 * @param array    $query_params   @see EEM_Base::get_all()
1892
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1893
+		 *                                 to block (prevent) this deletion
1894
+		 */
1895
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1896
+		//some MySQL databases may be running safe mode, which may restrict
1897
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1898
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1899
+		//to delete them
1900
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1901
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1902
+		if ($deletion_where) {
1903
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1904
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1905
+			$table_aliases = array_keys($this->_tables);
1906
+			$SQL = "DELETE "
1907
+				   . implode(", ", $table_aliases)
1908
+				   . " FROM "
1909
+				   . $model_query_info->get_full_join_sql()
1910
+				   . " WHERE "
1911
+				   . $deletion_where;
1912
+			//		/echo "delete sql:$SQL";
1913
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1914
+		} else {
1915
+			$rows_deleted = 0;
1916
+		}
1917
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1918
+		if ($this->has_primary_key_field()) {
1919
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1920
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1921
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1922
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1923
+				}
1924
+			}
1925
+		}
1926
+		/**
1927
+		 * Action called just after performing a real deletion query. Although at this point the
1928
+		 * items should have been deleted
1929
+		 *
1930
+		 * @param EEM_Base $model
1931
+		 * @param array    $query_params @see EEM_Base::get_all()
1932
+		 * @param int      $rows_deleted
1933
+		 */
1934
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1935
+		return $rows_deleted;//how many supposedly got deleted
1936
+	}
1937
+
1938
+
1939
+
1940
+	/**
1941
+	 * Checks all the relations that throw error messages when there are blocking related objects
1942
+	 * for related model objects. If there are any related model objects on those relations,
1943
+	 * adds an EE_Error, and return true
1944
+	 *
1945
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1946
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1947
+	 *                                                 should be ignored when determining whether there are related
1948
+	 *                                                 model objects which block this model object's deletion. Useful
1949
+	 *                                                 if you know A is related to B and are considering deleting A,
1950
+	 *                                                 but want to see if A has any other objects blocking its deletion
1951
+	 *                                                 before removing the relation between A and B
1952
+	 * @return boolean
1953
+	 * @throws \EE_Error
1954
+	 */
1955
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1956
+	{
1957
+		//first, if $ignore_this_model_obj was supplied, get its model
1958
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1959
+			$ignored_model = $ignore_this_model_obj->get_model();
1960
+		} else {
1961
+			$ignored_model = null;
1962
+		}
1963
+		//now check all the relations of $this_model_obj_or_id and see if there
1964
+		//are any related model objects blocking it?
1965
+		$is_blocked = false;
1966
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1967
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1968
+				//if $ignore_this_model_obj was supplied, then for the query
1969
+				//on that model needs to be told to ignore $ignore_this_model_obj
1970
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1971
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1972
+						array(
1973
+							$ignored_model->get_primary_key_field()->get_name() => array(
1974
+								'!=',
1975
+								$ignore_this_model_obj->ID(),
1976
+							),
1977
+						),
1978
+					));
1979
+				} else {
1980
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1981
+				}
1982
+				if ($related_model_objects) {
1983
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1984
+					$is_blocked = true;
1985
+				}
1986
+			}
1987
+		}
1988
+		return $is_blocked;
1989
+	}
1990
+
1991
+
1992
+
1993
+	/**
1994
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1995
+	 * well.
1996
+	 *
1997
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1998
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1999
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
2000
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
2001
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
2002
+	 *                                      easily corrupt your DB
2003
+	 * @throws EE_Error
2004
+	 * @return string    everything that comes after the WHERE statement.
2005
+	 */
2006
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2007
+	{
2008
+		if ($this->has_primary_key_field()) {
2009
+			$primary_table = $this->_get_main_table();
2010
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2011
+			$other_tables = $this->_get_other_tables();
2012
+			/**
2013
+			 * @var EE_Primary_Key_Field_Base[] $other_tables_pk_fields  keys are table aliases
2014
+			 */
2015
+			$other_tables_pk_fields = array();
2016
+			/**
2017
+			 * @var EE_Primary_Key_Field_Base[] $other_tables_fk_fields EE_Foreign_Key_Field_Base[] keys are table aliases
2018
+			 */
2019
+			$other_tables_fk_fields = array();
2020
+			foreach($other_tables as $other_table_alias => $other_table_obj){
2021
+				$other_tables_pk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_pk_column());
2022
+				$other_tables_fk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_fk_column());
2023
+			}
2024
+			$deletes = $query = array();
2025
+			foreach ($objects_for_deletion as $delete_object) {
2026
+				//before we mark this object for deletion,
2027
+				//make sure there's no related objects blocking its deletion (if we're checking)
2028
+				if (
2029
+					$allow_blocking
2030
+					&& $this->delete_is_blocked_by_related_models(
2031
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
2032
+					)
2033
+				) {
2034
+					continue;
2035
+				}
2036
+				//primary table deletes
2037
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2038
+
2039
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2040
+						$delete_object[$primary_table->get_fully_qualified_pk_column()],
2041
+						$primary_table_pk_field
2042
+					);
2043
+				}
2044
+				//other tables
2045
+				if (! empty($other_tables)) {
2046
+					foreach ($other_tables as $other_table_alias => $other_table_obj) {
2047
+						$other_table_pk_field = $other_tables_pk_fields[$other_table_alias];
2048
+						$other_table_fk_field = $other_tables_fk_fields[$other_table_alias];
2049
+						//first check if we've got the foreign key column here.
2050
+						if (isset($delete_object[$other_table_obj->get_fully_qualified_fk_column()])) {
2051
+							$deletes[$other_table_obj->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2052
+								$delete_object[$other_table_obj->get_fully_qualified_fk_column()],
2053
+								$other_table_fk_field
2054
+							);
2055
+						}
2056
+						// wait! it's entirely possible that we'll have a the primary key
2057
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2058
+						if (isset($delete_object[$other_table_obj->get_fully_qualified_pk_column()])) {
2059
+							$deletes[$other_table_obj->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2060
+								$delete_object[$other_table_obj->get_fully_qualified_pk_column()],
2061
+								$other_table_pk_field
2062
+							);
2063
+						}
2064
+						// finally, it is possible that the fk for this table is found
2065
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2066
+						if (isset($delete_object[$other_table_obj->get_fully_qualified_pk_on_fk_table()])) {
2067
+							$deletes[$other_table_obj->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2068
+								$delete_object[$other_table_obj->get_fully_qualified_pk_column()],
2069
+								$other_table_pk_field
2070
+							);
2071
+						}
2072
+					}
2073
+				}
2074
+			}
2075
+			//we should have deletes now, so let's just go through and setup the where statement
2076
+			foreach ($deletes as $column => $values) {
2077
+				//make sure we have unique $values;
2078
+				$values = array_unique($values);
2079
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2080
+			}
2081
+			return ! empty($query) ? implode(' AND ', $query) : '';
2082
+		}
2083
+		$combined_primary_key_fields = $this->get_combined_primary_key_fields();
2084
+		if (count($combined_primary_key_fields) > 1) {
2085
+			$ways_to_identify_a_row = array();
2086
+			//note: because there's no primary key, that means nothing else  can be pointing to this model, right?
2087
+			foreach ($objects_for_deletion as $delete_object) {
2088
+				$combined_primary_key_row_values = array();
2089
+				foreach ($combined_primary_key_fields as $field_in_combined_primary_key) {
2090
+					if ($field_in_combined_primary_key instanceof EE_Model_Field_Base) {
2091
+						$combined_primary_key_row_values[] = $field_in_combined_primary_key->get_qualified_column()
2092
+														   . "="
2093
+														   . $delete_object[$field_in_combined_primary_key->get_qualified_column()];
2094
+					}
2095
+				}
2096
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $combined_primary_key_row_values) . ")";
2097
+			}
2098
+			return implode(" OR ", $ways_to_identify_a_row);
2099
+		} else {
2100
+			//so there's no primary key and no combined key...
2101
+			//sorry, can't help you
2102
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2103
+				"event_espresso"), get_class($this)));
2104
+		}
2105
+	}
2106
+
2107
+
2108
+	/**
2109
+	 * Gets the model field by the fully qualified name
2110
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2111
+	 * @return EE_Model_Field_Base
2112
+	 */
2113
+	public function get_field_by_column($qualified_column_name)
2114
+	{
2115
+	   foreach($this->field_settings(true) as $field_name => $field_obj){
2116
+		   if($field_obj->get_qualified_column() === $qualified_column_name){
2117
+			   return $field_obj;
2118
+		   }
2119
+	   }
2120
+		throw new EE_Error(
2121
+			sprintf(
2122
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2123
+				$this->get_this_model_name(),
2124
+				$qualified_column_name
2125
+			)
2126
+		);
2127
+	}
2128
+
2129
+
2130
+
2131
+	/**
2132
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2133
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2134
+	 * column
2135
+	 *
2136
+	 * @param array  $query_params   like EEM_Base::get_all's
2137
+	 * @param string $field_to_count field on model to count by (not column name)
2138
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2139
+	 *                               that by the setting $distinct to TRUE;
2140
+	 * @return int
2141
+	 * @throws \EE_Error
2142
+	 */
2143
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2144
+	{
2145
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2146
+		if ($field_to_count) {
2147
+			$field_obj = $this->field_settings_for($field_to_count);
2148
+			$column_to_count = $field_obj->get_qualified_column();
2149
+		} elseif ($this->has_primary_key_field()) {
2150
+			$pk_field_obj = $this->get_primary_key_field();
2151
+			$column_to_count = $pk_field_obj->get_qualified_column();
2152
+		} else {
2153
+			//there's no primary key
2154
+			//if we're counting distinct items, and there's no primary key,
2155
+			//we need to list out the columns for distinction;
2156
+			//otherwise we can just use star
2157
+			if ($distinct) {
2158
+				$columns_to_use = array();
2159
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2160
+					$columns_to_use[] = $field_obj->get_qualified_column();
2161
+				}
2162
+				$column_to_count = implode(',', $columns_to_use);
2163
+			} else {
2164
+				$column_to_count = '*';
2165
+			}
2166
+		}
2167
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2168
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2169
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2170
+	}
2171
+
2172
+
2173
+
2174
+	/**
2175
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2176
+	 *
2177
+	 * @param array  $query_params like EEM_Base::get_all
2178
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2179
+	 * @return float
2180
+	 * @throws \EE_Error
2181
+	 */
2182
+	public function sum($query_params, $field_to_sum = null)
2183
+	{
2184
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2185
+		if ($field_to_sum) {
2186
+			$field_obj = $this->field_settings_for($field_to_sum);
2187
+		} else {
2188
+			$field_obj = $this->get_primary_key_field();
2189
+		}
2190
+		$column_to_count = $field_obj->get_qualified_column();
2191
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2192
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2193
+		$data_type = $field_obj->get_wpdb_data_type();
2194
+		if ($data_type === '%d' || $data_type === '%s') {
2195
+			return (float)$return_value;
2196
+		} else {//must be %f
2197
+			return (float)$return_value;
2198
+		}
2199
+	}
2200
+
2201
+
2202
+
2203
+	/**
2204
+	 * Just calls the specified method on $wpdb with the given arguments
2205
+	 * Consolidates a little extra error handling code
2206
+	 *
2207
+	 * @param string $wpdb_method
2208
+	 * @param array  $arguments_to_provide
2209
+	 * @throws EE_Error
2210
+	 * @global wpdb  $wpdb
2211
+	 * @return mixed
2212
+	 */
2213
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2214
+	{
2215
+		//if we're in maintenance mode level 2, DON'T run any queries
2216
+		//because level 2 indicates the database needs updating and
2217
+		//is probably out of sync with the code
2218
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2219
+			throw new EE_Error(sprintf(__("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.",
2220
+				"event_espresso")));
2221
+		}
2222
+		/** @type WPDB $wpdb */
2223
+		global $wpdb;
2224
+		if (! method_exists($wpdb, $wpdb_method)) {
2225
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2226
+				'event_espresso'), $wpdb_method));
2227
+		}
2228
+		if (WP_DEBUG) {
2229
+			$old_show_errors_value = $wpdb->show_errors;
2230
+			$wpdb->show_errors(false);
2231
+		}
2232
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2233
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2234
+		if (WP_DEBUG) {
2235
+			$wpdb->show_errors($old_show_errors_value);
2236
+			if (! empty($wpdb->last_error)) {
2237
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2238
+			} elseif ($result === false) {
2239
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2240
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2241
+			}
2242
+		} elseif ($result === false) {
2243
+			EE_Error::add_error(
2244
+				sprintf(
2245
+					__('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"',
2246
+						'event_espresso'),
2247
+					$wpdb_method,
2248
+					var_export($arguments_to_provide, true),
2249
+					$wpdb->last_error
2250
+				),
2251
+				__FILE__,
2252
+				__FUNCTION__,
2253
+				__LINE__
2254
+			);
2255
+		}
2256
+		return $result;
2257
+	}
2258
+
2259
+
2260
+
2261
+	/**
2262
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2263
+	 * and if there's an error tries to verify the DB is correct. Uses
2264
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2265
+	 * we should try to fix the EE core db, the addons, or just give up
2266
+	 *
2267
+	 * @param string $wpdb_method
2268
+	 * @param array  $arguments_to_provide
2269
+	 * @return mixed
2270
+	 */
2271
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2272
+	{
2273
+		/** @type WPDB $wpdb */
2274
+		global $wpdb;
2275
+		$wpdb->last_error = null;
2276
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2277
+		// was there an error running the query? but we don't care on new activations
2278
+		// (we're going to setup the DB anyway on new activations)
2279
+		if (($result === false || ! empty($wpdb->last_error))
2280
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2281
+		) {
2282
+			switch (EEM_Base::$_db_verification_level) {
2283
+				case EEM_Base::db_verified_none :
2284
+					// let's double-check core's DB
2285
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2286
+					break;
2287
+				case EEM_Base::db_verified_core :
2288
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2289
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2290
+					break;
2291
+				case EEM_Base::db_verified_addons :
2292
+					// ummmm... you in trouble
2293
+					return $result;
2294
+					break;
2295
+			}
2296
+			if (! empty($error_message)) {
2297
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2298
+				trigger_error($error_message);
2299
+			}
2300
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2301
+		}
2302
+		return $result;
2303
+	}
2304
+
2305
+
2306
+
2307
+	/**
2308
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2309
+	 * EEM_Base::$_db_verification_level
2310
+	 *
2311
+	 * @param string $wpdb_method
2312
+	 * @param array  $arguments_to_provide
2313
+	 * @return string
2314
+	 */
2315
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2316
+	{
2317
+		/** @type WPDB $wpdb */
2318
+		global $wpdb;
2319
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2320
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2321
+		$error_message = sprintf(
2322
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2323
+				'event_espresso'),
2324
+			$wpdb->last_error,
2325
+			$wpdb_method,
2326
+			wp_json_encode($arguments_to_provide)
2327
+		);
2328
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2329
+		return $error_message;
2330
+	}
2331
+
2332
+
2333
+
2334
+	/**
2335
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2336
+	 * EEM_Base::$_db_verification_level
2337
+	 *
2338
+	 * @param $wpdb_method
2339
+	 * @param $arguments_to_provide
2340
+	 * @return string
2341
+	 */
2342
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2343
+	{
2344
+		/** @type WPDB $wpdb */
2345
+		global $wpdb;
2346
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2347
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2348
+		$error_message = sprintf(
2349
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2350
+				'event_espresso'),
2351
+			$wpdb->last_error,
2352
+			$wpdb_method,
2353
+			wp_json_encode($arguments_to_provide)
2354
+		);
2355
+		EE_System::instance()->initialize_addons();
2356
+		return $error_message;
2357
+	}
2358
+
2359
+
2360
+
2361
+	/**
2362
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2363
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2364
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2365
+	 * ..."
2366
+	 *
2367
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2368
+	 * @return string
2369
+	 */
2370
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2371
+	{
2372
+		return " FROM " . $model_query_info->get_full_join_sql() .
2373
+			   $model_query_info->get_where_sql() .
2374
+			   $model_query_info->get_group_by_sql() .
2375
+			   $model_query_info->get_having_sql() .
2376
+			   $model_query_info->get_order_by_sql() .
2377
+			   $model_query_info->get_limit_sql();
2378
+	}
2379
+
2380
+
2381
+
2382
+	/**
2383
+	 * Set to easily debug the next X queries ran from this model.
2384
+	 *
2385
+	 * @param int $count
2386
+	 */
2387
+	public function show_next_x_db_queries($count = 1)
2388
+	{
2389
+		$this->_show_next_x_db_queries = $count;
2390
+	}
2391
+
2392
+
2393
+
2394
+	/**
2395
+	 * @param $sql_query
2396
+	 */
2397
+	public function show_db_query_if_previously_requested($sql_query)
2398
+	{
2399
+		if ($this->_show_next_x_db_queries > 0) {
2400
+			echo $sql_query;
2401
+			$this->_show_next_x_db_queries--;
2402
+		}
2403
+	}
2404
+
2405
+
2406
+
2407
+	/**
2408
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2409
+	 * There are the 3 cases:
2410
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2411
+	 * $otherModelObject has no ID, it is first saved.
2412
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2413
+	 * has no ID, it is first saved.
2414
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2415
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2416
+	 * join table
2417
+	 *
2418
+	 * @param        EE_Base_Class                     /int $thisModelObject
2419
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2420
+	 * @param string $relationName                     , key in EEM_Base::_relations
2421
+	 *                                                 an attendee to a group, you also want to specify which role they
2422
+	 *                                                 will have in that group. So you would use this parameter to
2423
+	 *                                                 specify array('role-column-name'=>'role-id')
2424
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2425
+	 *                                                 to for relation to methods that allow you to further specify
2426
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2427
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2428
+	 *                                                 because these will be inserted in any new rows created as well.
2429
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2430
+	 * @throws \EE_Error
2431
+	 */
2432
+	public function add_relationship_to(
2433
+		$id_or_obj,
2434
+		$other_model_id_or_obj,
2435
+		$relationName,
2436
+		$extra_join_model_fields_n_values = array()
2437
+	) {
2438
+		$relation_obj = $this->related_settings_for($relationName);
2439
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2440
+	}
2441
+
2442
+
2443
+
2444
+	/**
2445
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2446
+	 * There are the 3 cases:
2447
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2448
+	 * error
2449
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2450
+	 * an error
2451
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2452
+	 *
2453
+	 * @param        EE_Base_Class /int $id_or_obj
2454
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2455
+	 * @param string $relationName key in EEM_Base::_relations
2456
+	 * @return boolean of success
2457
+	 * @throws \EE_Error
2458
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2459
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2460
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2461
+	 *                             because these will be inserted in any new rows created as well.
2462
+	 */
2463
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2464
+	{
2465
+		$relation_obj = $this->related_settings_for($relationName);
2466
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2467
+	}
2468
+
2469
+
2470
+
2471
+	/**
2472
+	 * @param mixed           $id_or_obj
2473
+	 * @param string          $relationName
2474
+	 * @param array           $where_query_params
2475
+	 * @param EE_Base_Class[] objects to which relations were removed
2476
+	 * @return \EE_Base_Class[]
2477
+	 * @throws \EE_Error
2478
+	 */
2479
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2480
+	{
2481
+		$relation_obj = $this->related_settings_for($relationName);
2482
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2483
+	}
2484
+
2485
+
2486
+
2487
+	/**
2488
+	 * Gets all the related items of the specified $model_name, using $query_params.
2489
+	 * Note: by default, we remove the "default query params"
2490
+	 * because we want to get even deleted items etc.
2491
+	 *
2492
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2493
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2494
+	 * @param array  $query_params like EEM_Base::get_all
2495
+	 * @return EE_Base_Class[]
2496
+	 * @throws \EE_Error
2497
+	 */
2498
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2499
+	{
2500
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2501
+		$relation_settings = $this->related_settings_for($model_name);
2502
+		return $relation_settings->get_all_related($model_obj, $query_params);
2503
+	}
2504
+
2505
+
2506
+
2507
+	/**
2508
+	 * Deletes all the model objects across the relation indicated by $model_name
2509
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2510
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2511
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2512
+	 *
2513
+	 * @param EE_Base_Class|int|string $id_or_obj
2514
+	 * @param string                   $model_name
2515
+	 * @param array                    $query_params
2516
+	 * @return int how many deleted
2517
+	 * @throws \EE_Error
2518
+	 */
2519
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2520
+	{
2521
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2522
+		$relation_settings = $this->related_settings_for($model_name);
2523
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2524
+	}
2525
+
2526
+
2527
+
2528
+	/**
2529
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2530
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2531
+	 * the model objects can't be hard deleted because of blocking related model objects,
2532
+	 * just does a soft-delete on them instead.
2533
+	 *
2534
+	 * @param EE_Base_Class|int|string $id_or_obj
2535
+	 * @param string                   $model_name
2536
+	 * @param array                    $query_params
2537
+	 * @return int how many deleted
2538
+	 * @throws \EE_Error
2539
+	 */
2540
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2541
+	{
2542
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2543
+		$relation_settings = $this->related_settings_for($model_name);
2544
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2545
+	}
2546
+
2547
+
2548
+
2549
+	/**
2550
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2551
+	 * unless otherwise specified in the $query_params
2552
+	 *
2553
+	 * @param        int             /EE_Base_Class $id_or_obj
2554
+	 * @param string $model_name     like 'Event', or 'Registration'
2555
+	 * @param array  $query_params   like EEM_Base::get_all's
2556
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2557
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2558
+	 *                               that by the setting $distinct to TRUE;
2559
+	 * @return int
2560
+	 * @throws \EE_Error
2561
+	 */
2562
+	public function count_related(
2563
+		$id_or_obj,
2564
+		$model_name,
2565
+		$query_params = array(),
2566
+		$field_to_count = null,
2567
+		$distinct = false
2568
+	) {
2569
+		$related_model = $this->get_related_model_obj($model_name);
2570
+		//we're just going to use the query params on the related model's normal get_all query,
2571
+		//except add a condition to say to match the current mod
2572
+		if (! isset($query_params['default_where_conditions'])) {
2573
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2574
+		}
2575
+		$this_model_name = $this->get_this_model_name();
2576
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2577
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2578
+		return $related_model->count($query_params, $field_to_count, $distinct);
2579
+	}
2580
+
2581
+
2582
+
2583
+	/**
2584
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2585
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2586
+	 *
2587
+	 * @param        int           /EE_Base_Class $id_or_obj
2588
+	 * @param string $model_name   like 'Event', or 'Registration'
2589
+	 * @param array  $query_params like EEM_Base::get_all's
2590
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2591
+	 * @return float
2592
+	 * @throws \EE_Error
2593
+	 */
2594
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2595
+	{
2596
+		$related_model = $this->get_related_model_obj($model_name);
2597
+		if (! is_array($query_params)) {
2598
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2599
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2600
+					gettype($query_params)), '4.6.0');
2601
+			$query_params = array();
2602
+		}
2603
+		//we're just going to use the query params on the related model's normal get_all query,
2604
+		//except add a condition to say to match the current mod
2605
+		if (! isset($query_params['default_where_conditions'])) {
2606
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2607
+		}
2608
+		$this_model_name = $this->get_this_model_name();
2609
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2610
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2611
+		return $related_model->sum($query_params, $field_to_sum);
2612
+	}
2613
+
2614
+
2615
+
2616
+	/**
2617
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2618
+	 * $modelObject
2619
+	 *
2620
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2621
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2622
+	 * @param array               $query_params     like EEM_Base::get_all's
2623
+	 * @return EE_Base_Class
2624
+	 * @throws \EE_Error
2625
+	 */
2626
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2627
+	{
2628
+		$query_params['limit'] = 1;
2629
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2630
+		if ($results) {
2631
+			return array_shift($results);
2632
+		} else {
2633
+			return null;
2634
+		}
2635
+	}
2636
+
2637
+
2638
+
2639
+	/**
2640
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2641
+	 *
2642
+	 * @return string
2643
+	 */
2644
+	public function get_this_model_name()
2645
+	{
2646
+		return str_replace("EEM_", "", get_class($this));
2647
+	}
2648
+
2649
+
2650
+
2651
+	/**
2652
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2653
+	 *
2654
+	 * @return EE_Any_Foreign_Model_Name_Field
2655
+	 * @throws EE_Error
2656
+	 */
2657
+	public function get_field_containing_related_model_name()
2658
+	{
2659
+		foreach ($this->field_settings(true) as $field) {
2660
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2661
+				$field_with_model_name = $field;
2662
+			}
2663
+		}
2664
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2665
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2666
+				$this->get_this_model_name()));
2667
+		}
2668
+		return $field_with_model_name;
2669
+	}
2670
+
2671
+
2672
+
2673
+	/**
2674
+	 * Inserts a new entry into the database, for each table.
2675
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2676
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2677
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2678
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2679
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2680
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2681
+	 *
2682
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2683
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2684
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2685
+	 *                              of EEM_Base)
2686
+	 * @return int new primary key on main table that got inserted
2687
+	 * @throws EE_Error
2688
+	 */
2689
+	public function insert($field_n_values)
2690
+	{
2691
+		/**
2692
+		 * Filters the fields and their values before inserting an item using the models
2693
+		 *
2694
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2695
+		 * @param EEM_Base $model           the model used
2696
+		 */
2697
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2698
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2699
+			$main_table = $this->_get_main_table();
2700
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2701
+			if ($new_id !== false) {
2702
+				foreach ($this->_get_other_tables() as $other_table) {
2703
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2704
+				}
2705
+			}
2706
+			/**
2707
+			 * Done just after attempting to insert a new model object
2708
+			 *
2709
+			 * @param EEM_Base   $model           used
2710
+			 * @param array      $fields_n_values fields and their values
2711
+			 * @param int|string the              ID of the newly-inserted model object
2712
+			 */
2713
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2714
+			return $new_id;
2715
+		} else {
2716
+			return false;
2717
+		}
2718
+	}
2719
+
2720
+
2721
+
2722
+	/**
2723
+	 * Checks that the result would satisfy the unique indexes on this model
2724
+	 *
2725
+	 * @param array  $field_n_values
2726
+	 * @param string $action
2727
+	 * @return boolean
2728
+	 * @throws \EE_Error
2729
+	 */
2730
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2731
+	{
2732
+		foreach ($this->unique_indexes() as $index_name => $index) {
2733
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2734
+			if ($this->exists(array($uniqueness_where_params))) {
2735
+				EE_Error::add_error(
2736
+					sprintf(
2737
+						__(
2738
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2739
+							"event_espresso"
2740
+						),
2741
+						$action,
2742
+						$this->_get_class_name(),
2743
+						$index_name,
2744
+						implode(",", $index->field_names()),
2745
+						http_build_query($uniqueness_where_params)
2746
+					),
2747
+					__FILE__,
2748
+					__FUNCTION__,
2749
+					__LINE__
2750
+				);
2751
+				return false;
2752
+			}
2753
+		}
2754
+		return true;
2755
+	}
2756
+
2757
+
2758
+
2759
+	/**
2760
+	 * Checks the database for an item that conflicts (ie, if this item were
2761
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2762
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2763
+	 * can be either an EE_Base_Class or an array of fields n values
2764
+	 *
2765
+	 * @param EE_Base_Class|array $obj_or_fields_array
2766
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2767
+	 *                                                 when looking for conflicts
2768
+	 *                                                 (ie, if false, we ignore the model object's primary key
2769
+	 *                                                 when finding "conflicts". If true, it's also considered).
2770
+	 *                                                 Only works for INT primary key,
2771
+	 *                                                 STRING primary keys cannot be ignored
2772
+	 * @throws EE_Error
2773
+	 * @return EE_Base_Class|array
2774
+	 */
2775
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2776
+	{
2777
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2778
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2779
+		} elseif (is_array($obj_or_fields_array)) {
2780
+			$fields_n_values = $obj_or_fields_array;
2781
+		} else {
2782
+			throw new EE_Error(
2783
+				sprintf(
2784
+					__(
2785
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2786
+						"event_espresso"
2787
+					),
2788
+					get_class($this),
2789
+					$obj_or_fields_array
2790
+				)
2791
+			);
2792
+		}
2793
+		$query_params = array();
2794
+		if ($this->has_primary_key_field()
2795
+			&& ($include_primary_key
2796
+				|| $this->get_primary_key_field()
2797
+				   instanceof
2798
+				   EE_Primary_Key_String_Field)
2799
+			&& isset($fields_n_values[$this->primary_key_name()])
2800
+		) {
2801
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2802
+		}
2803
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2804
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2805
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2806
+		}
2807
+		//if there is nothing to base this search on, then we shouldn't find anything
2808
+		if (empty($query_params)) {
2809
+			return array();
2810
+		} else {
2811
+			return $this->get_one($query_params);
2812
+		}
2813
+	}
2814
+
2815
+
2816
+
2817
+	/**
2818
+	 * Like count, but is optimized and returns a boolean instead of an int
2819
+	 *
2820
+	 * @param array $query_params
2821
+	 * @return boolean
2822
+	 * @throws \EE_Error
2823
+	 */
2824
+	public function exists($query_params)
2825
+	{
2826
+		$query_params['limit'] = 1;
2827
+		return $this->count($query_params) > 0;
2828
+	}
2829
+
2830
+
2831
+
2832
+	/**
2833
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2834
+	 *
2835
+	 * @param int|string $id
2836
+	 * @return boolean
2837
+	 * @throws \EE_Error
2838
+	 */
2839
+	public function exists_by_ID($id)
2840
+	{
2841
+		return $this->exists(
2842
+			array(
2843
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2844
+				array(
2845
+					$this->primary_key_name() => $id,
2846
+				),
2847
+			)
2848
+		);
2849
+	}
2850
+
2851
+
2852
+
2853
+	/**
2854
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2855
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2856
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2857
+	 * on the main table)
2858
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2859
+	 * cases where we want to call it directly rather than via insert().
2860
+	 *
2861
+	 * @access   protected
2862
+	 * @param EE_Table_Base $table
2863
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2864
+	 *                                       float
2865
+	 * @param int           $new_id          for now we assume only int keys
2866
+	 * @throws EE_Error
2867
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2868
+	 * @return int ID of new row inserted, or FALSE on failure
2869
+	 */
2870
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2871
+	{
2872
+		global $wpdb;
2873
+		$insertion_col_n_values = array();
2874
+		$format_for_insertion = array();
2875
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2876
+		foreach ($fields_on_table as $field_name => $field_obj) {
2877
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2878
+			if ($field_obj->is_auto_increment()) {
2879
+				continue;
2880
+			}
2881
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2882
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2883
+			if ($prepared_value !== null) {
2884
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2885
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2886
+			}
2887
+		}
2888
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2889
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2890
+			//so add the fk to the main table as a column
2891
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2892
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2893
+		}
2894
+		//insert the new entry
2895
+		$result = $this->_do_wpdb_query('insert',
2896
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2897
+		if ($result === false) {
2898
+			return false;
2899
+		}
2900
+		//ok, now what do we return for the ID of the newly-inserted thing?
2901
+		if ($this->has_primary_key_field()) {
2902
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2903
+				return $wpdb->insert_id;
2904
+			} else {
2905
+				//it's not an auto-increment primary key, so
2906
+				//it must have been supplied
2907
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2908
+			}
2909
+		} else {
2910
+			//we can't return a  primary key because there is none. instead return
2911
+			//a unique string indicating this model
2912
+			return $this->get_index_primary_key_string($fields_n_values);
2913
+		}
2914
+	}
2915
+
2916
+
2917
+
2918
+	/**
2919
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2920
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2921
+	 * and there is no default, we pass it along. WPDB will take care of it)
2922
+	 *
2923
+	 * @param EE_Model_Field_Base $field_obj
2924
+	 * @param array               $fields_n_values
2925
+	 * @return mixed string|int|float depending on what the table column will be expecting
2926
+	 * @throws \EE_Error
2927
+	 */
2928
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2929
+	{
2930
+		//if this field doesn't allow nullable, don't allow it
2931
+		if (! $field_obj->is_nullable()
2932
+			&& (
2933
+				! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2934
+		) {
2935
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2936
+		}
2937
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2938
+			: null;
2939
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2940
+	}
2941
+
2942
+
2943
+
2944
+	/**
2945
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2946
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2947
+	 * the field's prepare_for_set() method.
2948
+	 *
2949
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2950
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2951
+	 *                                   top of file)
2952
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2953
+	 *                                   $value is a custom selection
2954
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2955
+	 */
2956
+	private function _prepare_value_for_use_in_db($value, $field)
2957
+	{
2958
+		if ($field && $field instanceof EE_Model_Field_Base) {
2959
+			switch ($this->_values_already_prepared_by_model_object) {
2960
+				/** @noinspection PhpMissingBreakStatementInspection */
2961
+				case self::not_prepared_by_model_object:
2962
+					$value = $field->prepare_for_set($value);
2963
+				//purposefully left out "return"
2964
+				case self::prepared_by_model_object:
2965
+					$value = $field->prepare_for_use_in_db($value);
2966
+				case self::prepared_for_use_in_db:
2967
+					//leave the value alone
2968
+			}
2969
+			return $value;
2970
+		} else {
2971
+			return $value;
2972
+		}
2973
+	}
2974
+
2975
+
2976
+
2977
+	/**
2978
+	 * Returns the main table on this model
2979
+	 *
2980
+	 * @return EE_Primary_Table
2981
+	 * @throws EE_Error
2982
+	 */
2983
+	protected function _get_main_table()
2984
+	{
2985
+		foreach ($this->_tables as $table) {
2986
+			if ($table instanceof EE_Primary_Table) {
2987
+				return $table;
2988
+			}
2989
+		}
2990
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2991
+			'event_espresso'), get_class($this)));
2992
+	}
2993
+
2994
+
2995
+
2996
+	/**
2997
+	 * table
2998
+	 * returns EE_Primary_Table table name
2999
+	 *
3000
+	 * @return string
3001
+	 * @throws \EE_Error
3002
+	 */
3003
+	public function table()
3004
+	{
3005
+		return $this->_get_main_table()->get_table_name();
3006
+	}
3007
+
3008
+
3009
+
3010
+	/**
3011
+	 * table
3012
+	 * returns first EE_Secondary_Table table name
3013
+	 *
3014
+	 * @return string
3015
+	 */
3016
+	public function second_table()
3017
+	{
3018
+		// grab second table from tables array
3019
+		$second_table = end($this->_tables);
3020
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3021
+	}
3022
+
3023
+
3024
+
3025
+	/**
3026
+	 * get_table_obj_by_alias
3027
+	 * returns table name given it's alias
3028
+	 *
3029
+	 * @param string $table_alias
3030
+	 * @return EE_Primary_Table | EE_Secondary_Table
3031
+	 */
3032
+	public function get_table_obj_by_alias($table_alias = '')
3033
+	{
3034
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3035
+	}
3036
+
3037
+
3038
+
3039
+	/**
3040
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3041
+	 *
3042
+	 * @return EE_Secondary_Table[]
3043
+	 */
3044
+	protected function _get_other_tables()
3045
+	{
3046
+		$other_tables = array();
3047
+		foreach ($this->_tables as $table_alias => $table) {
3048
+			if ($table instanceof EE_Secondary_Table) {
3049
+				$other_tables[$table_alias] = $table;
3050
+			}
3051
+		}
3052
+		return $other_tables;
3053
+	}
3054
+
3055
+
3056
+
3057
+	/**
3058
+	 * Finds all the fields that correspond to the given table
3059
+	 *
3060
+	 * @param string $table_alias , array key in EEM_Base::_tables
3061
+	 * @return EE_Model_Field_Base[]
3062
+	 */
3063
+	public function _get_fields_for_table($table_alias)
3064
+	{
3065
+		return $this->_fields[$table_alias];
3066
+	}
3067
+
3068
+
3069
+
3070
+	/**
3071
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3072
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3073
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3074
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3075
+	 * related Registration, Transaction, and Payment models.
3076
+	 *
3077
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3078
+	 * @return EE_Model_Query_Info_Carrier
3079
+	 * @throws \EE_Error
3080
+	 */
3081
+	public function _extract_related_models_from_query($query_params)
3082
+	{
3083
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3084
+		if (array_key_exists(0, $query_params)) {
3085
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3086
+		}
3087
+		if (array_key_exists('group_by', $query_params)) {
3088
+			if (is_array($query_params['group_by'])) {
3089
+				$this->_extract_related_models_from_sub_params_array_values(
3090
+					$query_params['group_by'],
3091
+					$query_info_carrier,
3092
+					'group_by'
3093
+				);
3094
+			} elseif (! empty ($query_params['group_by'])) {
3095
+				$this->_extract_related_model_info_from_query_param(
3096
+					$query_params['group_by'],
3097
+					$query_info_carrier,
3098
+					'group_by'
3099
+				);
3100
+			}
3101
+		}
3102
+		if (array_key_exists('having', $query_params)) {
3103
+			$this->_extract_related_models_from_sub_params_array_keys(
3104
+				$query_params[0],
3105
+				$query_info_carrier,
3106
+				'having'
3107
+			);
3108
+		}
3109
+		if (array_key_exists('order_by', $query_params)) {
3110
+			if (is_array($query_params['order_by'])) {
3111
+				$this->_extract_related_models_from_sub_params_array_keys(
3112
+					$query_params['order_by'],
3113
+					$query_info_carrier,
3114
+					'order_by'
3115
+				);
3116
+			} elseif (! empty($query_params['order_by'])) {
3117
+				$this->_extract_related_model_info_from_query_param(
3118
+					$query_params['order_by'],
3119
+					$query_info_carrier,
3120
+					'order_by'
3121
+				);
3122
+			}
3123
+		}
3124
+		if (array_key_exists('force_join', $query_params)) {
3125
+			$this->_extract_related_models_from_sub_params_array_values(
3126
+				$query_params['force_join'],
3127
+				$query_info_carrier,
3128
+				'force_join'
3129
+			);
3130
+		}
3131
+		return $query_info_carrier;
3132
+	}
3133
+
3134
+
3135
+
3136
+	/**
3137
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3138
+	 *
3139
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3140
+	 *                                                      $query_params['having']
3141
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3142
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3143
+	 * @throws EE_Error
3144
+	 * @return \EE_Model_Query_Info_Carrier
3145
+	 */
3146
+	private function _extract_related_models_from_sub_params_array_keys(
3147
+		$sub_query_params,
3148
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3149
+		$query_param_type
3150
+	) {
3151
+		if (! empty($sub_query_params)) {
3152
+			$sub_query_params = (array)$sub_query_params;
3153
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3154
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3155
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3156
+					$query_param_type);
3157
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3158
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3159
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3160
+				//of array('Registration.TXN_ID'=>23)
3161
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3162
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3163
+					if (! is_array($possibly_array_of_params)) {
3164
+						throw new EE_Error(sprintf(__("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'))",
3165
+							"event_espresso"),
3166
+							$param, $possibly_array_of_params));
3167
+					} else {
3168
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3169
+							$model_query_info_carrier, $query_param_type);
3170
+					}
3171
+				} elseif ($query_param_type === 0 //ie WHERE
3172
+						  && is_array($possibly_array_of_params)
3173
+						  && isset($possibly_array_of_params[2])
3174
+						  && $possibly_array_of_params[2] == true
3175
+				) {
3176
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3177
+					//indicating that $possible_array_of_params[1] is actually a field name,
3178
+					//from which we should extract query parameters!
3179
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3180
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3181
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3182
+					}
3183
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3184
+						$model_query_info_carrier, $query_param_type);
3185
+				}
3186
+			}
3187
+		}
3188
+		return $model_query_info_carrier;
3189
+	}
3190
+
3191
+
3192
+
3193
+	/**
3194
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3195
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3196
+	 *
3197
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3198
+	 *                                                      $query_params['having']
3199
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3200
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3201
+	 * @throws EE_Error
3202
+	 * @return \EE_Model_Query_Info_Carrier
3203
+	 */
3204
+	private function _extract_related_models_from_sub_params_array_values(
3205
+		$sub_query_params,
3206
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3207
+		$query_param_type
3208
+	) {
3209
+		if (! empty($sub_query_params)) {
3210
+			if (! is_array($sub_query_params)) {
3211
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3212
+					$sub_query_params));
3213
+			}
3214
+			foreach ($sub_query_params as $param) {
3215
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3216
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3217
+					$query_param_type);
3218
+			}
3219
+		}
3220
+		return $model_query_info_carrier;
3221
+	}
3222
+
3223
+
3224
+
3225
+	/**
3226
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3227
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3228
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3229
+	 * but use them in a different order. Eg, we need to know what models we are querying
3230
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3231
+	 * other models before we can finalize the where clause SQL.
3232
+	 *
3233
+	 * @param array $query_params
3234
+	 * @throws EE_Error
3235
+	 * @return EE_Model_Query_Info_Carrier
3236
+	 */
3237
+	public function _create_model_query_info_carrier($query_params)
3238
+	{
3239
+		if (! is_array($query_params)) {
3240
+			EE_Error::doing_it_wrong(
3241
+				'EEM_Base::_create_model_query_info_carrier',
3242
+				sprintf(
3243
+					__(
3244
+						'$query_params should be an array, you passed a variable of type %s',
3245
+						'event_espresso'
3246
+					),
3247
+					gettype($query_params)
3248
+				),
3249
+				'4.6.0'
3250
+			);
3251
+			$query_params = array();
3252
+		}
3253
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3254
+		//first check if we should alter the query to account for caps or not
3255
+		//because the caps might require us to do extra joins
3256
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3257
+			$query_params[0] = $where_query_params = array_replace_recursive(
3258
+				$where_query_params,
3259
+				$this->caps_where_conditions(
3260
+					$query_params['caps']
3261
+				)
3262
+			);
3263
+		}
3264
+		$query_object = $this->_extract_related_models_from_query($query_params);
3265
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3266
+		foreach ($where_query_params as $key => $value) {
3267
+			if (is_int($key)) {
3268
+				throw new EE_Error(
3269
+					sprintf(
3270
+						__(
3271
+							"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.",
3272
+							"event_espresso"
3273
+						),
3274
+						$key,
3275
+						var_export($value, true),
3276
+						var_export($query_params, true),
3277
+						get_class($this)
3278
+					)
3279
+				);
3280
+			}
3281
+		}
3282
+		if (
3283
+			array_key_exists('default_where_conditions', $query_params)
3284
+			&& ! empty($query_params['default_where_conditions'])
3285
+		) {
3286
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3287
+		} else {
3288
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3289
+		}
3290
+		$where_query_params = array_merge(
3291
+			$this->_get_default_where_conditions_for_models_in_query(
3292
+				$query_object,
3293
+				$use_default_where_conditions,
3294
+				$where_query_params
3295
+			),
3296
+			$where_query_params
3297
+		);
3298
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3299
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3300
+		// So we need to setup a subquery and use that for the main join.
3301
+		// Note for now this only works on the primary table for the model.
3302
+		// So for instance, you could set the limit array like this:
3303
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3304
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3305
+			$query_object->set_main_model_join_sql(
3306
+				$this->_construct_limit_join_select(
3307
+					$query_params['on_join_limit'][0],
3308
+					$query_params['on_join_limit'][1]
3309
+				)
3310
+			);
3311
+		}
3312
+		//set limit
3313
+		if (array_key_exists('limit', $query_params)) {
3314
+			if (is_array($query_params['limit'])) {
3315
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3316
+					$e = sprintf(
3317
+						__(
3318
+							"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)",
3319
+							"event_espresso"
3320
+						),
3321
+						http_build_query($query_params['limit'])
3322
+					);
3323
+					throw new EE_Error($e . "|" . $e);
3324
+				}
3325
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3326
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3327
+			} elseif (! empty ($query_params['limit'])) {
3328
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3329
+			}
3330
+		}
3331
+		//set order by
3332
+		if (array_key_exists('order_by', $query_params)) {
3333
+			if (is_array($query_params['order_by'])) {
3334
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3335
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3336
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3337
+				if (array_key_exists('order', $query_params)) {
3338
+					throw new EE_Error(
3339
+						sprintf(
3340
+							__(
3341
+								"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 ",
3342
+								"event_espresso"
3343
+							),
3344
+							get_class($this),
3345
+							implode(", ", array_keys($query_params['order_by'])),
3346
+							implode(", ", $query_params['order_by']),
3347
+							$query_params['order']
3348
+						)
3349
+					);
3350
+				}
3351
+				$this->_extract_related_models_from_sub_params_array_keys(
3352
+					$query_params['order_by'],
3353
+					$query_object,
3354
+					'order_by'
3355
+				);
3356
+				//assume it's an array of fields to order by
3357
+				$order_array = array();
3358
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3359
+					$order = $this->_extract_order($order);
3360
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3361
+				}
3362
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3363
+			} elseif (! empty ($query_params['order_by'])) {
3364
+				$this->_extract_related_model_info_from_query_param(
3365
+					$query_params['order_by'],
3366
+					$query_object,
3367
+					'order',
3368
+					$query_params['order_by']
3369
+				);
3370
+				$order = isset($query_params['order'])
3371
+					? $this->_extract_order($query_params['order'])
3372
+					: 'DESC';
3373
+				$query_object->set_order_by_sql(
3374
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3375
+				);
3376
+			}
3377
+		}
3378
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3379
+		if (! array_key_exists('order_by', $query_params)
3380
+			&& array_key_exists('order', $query_params)
3381
+			&& ! empty($query_params['order'])
3382
+		) {
3383
+			$pk_field = $this->get_primary_key_field();
3384
+			$order = $this->_extract_order($query_params['order']);
3385
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3386
+		}
3387
+		//set group by
3388
+		if (array_key_exists('group_by', $query_params)) {
3389
+			if (is_array($query_params['group_by'])) {
3390
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3391
+				$group_by_array = array();
3392
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3393
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3394
+				}
3395
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3396
+			} elseif (! empty ($query_params['group_by'])) {
3397
+				$query_object->set_group_by_sql(
3398
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3399
+				);
3400
+			}
3401
+		}
3402
+		//set having
3403
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3404
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3405
+		}
3406
+		//now, just verify they didn't pass anything wack
3407
+		foreach ($query_params as $query_key => $query_value) {
3408
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3409
+				throw new EE_Error(
3410
+					sprintf(
3411
+						__(
3412
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3413
+							'event_espresso'
3414
+						),
3415
+						$query_key,
3416
+						get_class($this),
3417
+						//						print_r( $this->_allowed_query_params, TRUE )
3418
+						implode(',', $this->_allowed_query_params)
3419
+					)
3420
+				);
3421
+			}
3422
+		}
3423
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3424
+		if (empty($main_model_join_sql)) {
3425
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3426
+		}
3427
+		return $query_object;
3428
+	}
3429
+
3430
+
3431
+
3432
+	/**
3433
+	 * Gets the where conditions that should be imposed on the query based on the
3434
+	 * context (eg reading frontend, backend, edit or delete).
3435
+	 *
3436
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3437
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3438
+	 * @throws \EE_Error
3439
+	 */
3440
+	public function caps_where_conditions($context = self::caps_read)
3441
+	{
3442
+		EEM_Base::verify_is_valid_cap_context($context);
3443
+		$cap_where_conditions = array();
3444
+		$cap_restrictions = $this->caps_missing($context);
3445
+		/**
3446
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3447
+		 */
3448
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3449
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3450
+				$restriction_if_no_cap->get_default_where_conditions());
3451
+		}
3452
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3453
+			$cap_restrictions);
3454
+	}
3455
+
3456
+
3457
+
3458
+	/**
3459
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3460
+	 * otherwise throws an exception
3461
+	 *
3462
+	 * @param string $should_be_order_string
3463
+	 * @return string either ASC, asc, DESC or desc
3464
+	 * @throws EE_Error
3465
+	 */
3466
+	private function _extract_order($should_be_order_string)
3467
+	{
3468
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3469
+			return $should_be_order_string;
3470
+		} else {
3471
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3472
+				"event_espresso"), get_class($this), $should_be_order_string));
3473
+		}
3474
+	}
3475
+
3476
+
3477
+
3478
+	/**
3479
+	 * Looks at all the models which are included in this query, and asks each
3480
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3481
+	 * so they can be merged
3482
+	 *
3483
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3484
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3485
+	 *                                                                  'none' means NO default where conditions will
3486
+	 *                                                                  be used AT ALL during this query.
3487
+	 *                                                                  'other_models_only' means default where
3488
+	 *                                                                  conditions from other models will be used, but
3489
+	 *                                                                  not for this primary model. 'all', the default,
3490
+	 *                                                                  means default where conditions will apply as
3491
+	 *                                                                  normal
3492
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3493
+	 * @throws EE_Error
3494
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3495
+	 */
3496
+	private function _get_default_where_conditions_for_models_in_query(
3497
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3498
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3499
+		$where_query_params = array()
3500
+	) {
3501
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3502
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3503
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3504
+				"event_espresso"), $use_default_where_conditions,
3505
+				implode(", ", $allowed_used_default_where_conditions_values)));
3506
+		}
3507
+		$universal_query_params = array();
3508
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3509
+			$universal_query_params = $this->_get_default_where_conditions();
3510
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3511
+			$universal_query_params = $this->_get_minimum_where_conditions();
3512
+		}
3513
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3514
+			$related_model = $this->get_related_model_obj($model_name);
3515
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3516
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3517
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3518
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3519
+			} else {
3520
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3521
+				continue;
3522
+			}
3523
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3524
+				$related_model_universal_where_params,
3525
+				$where_query_params,
3526
+				$related_model,
3527
+				$model_relation_path
3528
+			);
3529
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3530
+				$universal_query_params,
3531
+				$overrides
3532
+			);
3533
+		}
3534
+		return $universal_query_params;
3535
+	}
3536
+
3537
+
3538
+
3539
+	/**
3540
+	 * Determines whether or not we should use default where conditions for the model in question
3541
+	 * (this model, or other related models).
3542
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3543
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3544
+	 * We should use default where conditions on related models when they requested to use default where conditions
3545
+	 * on all models, or specifically just on other related models
3546
+	 * @param      $default_where_conditions_value
3547
+	 * @param bool $for_this_model false means this is for OTHER related models
3548
+	 * @return bool
3549
+	 */
3550
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3551
+	{
3552
+		return (
3553
+				   $for_this_model
3554
+				   && in_array(
3555
+					   $default_where_conditions_value,
3556
+					   array(
3557
+						   EEM_Base::default_where_conditions_all,
3558
+						   EEM_Base::default_where_conditions_this_only,
3559
+						   EEM_Base::default_where_conditions_minimum_others,
3560
+					   ),
3561
+					   true
3562
+				   )
3563
+			   )
3564
+			   || (
3565
+				   ! $for_this_model
3566
+				   && in_array(
3567
+					   $default_where_conditions_value,
3568
+					   array(
3569
+						   EEM_Base::default_where_conditions_all,
3570
+						   EEM_Base::default_where_conditions_others_only,
3571
+					   ),
3572
+					   true
3573
+				   )
3574
+			   );
3575
+	}
3576
+
3577
+	/**
3578
+	 * Determines whether or not we should use default minimum conditions for the model in question
3579
+	 * (this model, or other related models).
3580
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3581
+	 * where conditions.
3582
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3583
+	 * on this model or others
3584
+	 * @param      $default_where_conditions_value
3585
+	 * @param bool $for_this_model false means this is for OTHER related models
3586
+	 * @return bool
3587
+	 */
3588
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3589
+	{
3590
+		return (
3591
+				   $for_this_model
3592
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3593
+			   )
3594
+			   || (
3595
+				   ! $for_this_model
3596
+				   && in_array(
3597
+					   $default_where_conditions_value,
3598
+					   array(
3599
+						   EEM_Base::default_where_conditions_minimum_others,
3600
+						   EEM_Base::default_where_conditions_minimum_all,
3601
+					   ),
3602
+					   true
3603
+				   )
3604
+			   );
3605
+	}
3606
+
3607
+
3608
+	/**
3609
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3610
+	 * then we also add a special where condition which allows for that model's primary key
3611
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3612
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3613
+	 *
3614
+	 * @param array    $default_where_conditions
3615
+	 * @param array    $provided_where_conditions
3616
+	 * @param EEM_Base $model
3617
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3618
+	 * @return array like EEM_Base::get_all's $query_params[0]
3619
+	 * @throws \EE_Error
3620
+	 */
3621
+	private function _override_defaults_or_make_null_friendly(
3622
+		$default_where_conditions,
3623
+		$provided_where_conditions,
3624
+		$model,
3625
+		$model_relation_path
3626
+	) {
3627
+		$null_friendly_where_conditions = array();
3628
+		$none_overridden = true;
3629
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3630
+		foreach ($default_where_conditions as $key => $val) {
3631
+			if (isset($provided_where_conditions[$key])) {
3632
+				$none_overridden = false;
3633
+			} else {
3634
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3635
+			}
3636
+		}
3637
+		if ($none_overridden && $default_where_conditions) {
3638
+			if ($model->has_primary_key_field()) {
3639
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3640
+																				. "."
3641
+																				. $model->primary_key_name()] = array('IS NULL');
3642
+			}/*else{
3643 3643
 				//@todo NO PK, use other defaults
3644 3644
 			}*/
3645
-        }
3646
-        return $null_friendly_where_conditions;
3647
-    }
3648
-
3649
-
3650
-
3651
-    /**
3652
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3653
-     * default where conditions on all get_all, update, and delete queries done by this model.
3654
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3655
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3656
-     *
3657
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3658
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3659
-     */
3660
-    private function _get_default_where_conditions($model_relation_path = null)
3661
-    {
3662
-        if ($this->_ignore_where_strategy) {
3663
-            return array();
3664
-        }
3665
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3666
-    }
3667
-
3668
-
3669
-
3670
-    /**
3671
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3672
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3673
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3674
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3675
-     * Similar to _get_default_where_conditions
3676
-     *
3677
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3678
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3679
-     */
3680
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3681
-    {
3682
-        if ($this->_ignore_where_strategy) {
3683
-            return array();
3684
-        }
3685
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3686
-    }
3687
-
3688
-
3689
-
3690
-    /**
3691
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3692
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3693
-     *
3694
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3695
-     * @return string
3696
-     * @throws \EE_Error
3697
-     */
3698
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3699
-    {
3700
-        $selects = $this->_get_columns_to_select_for_this_model();
3701
-        foreach (
3702
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3703
-            $name_of_other_model_included
3704
-        ) {
3705
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3706
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3707
-            foreach ($other_model_selects as $key => $value) {
3708
-                $selects[] = $value;
3709
-            }
3710
-        }
3711
-        return implode(", ", $selects);
3712
-    }
3713
-
3714
-
3715
-
3716
-    /**
3717
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3718
-     * So that's going to be the columns for all the fields on the model
3719
-     *
3720
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3721
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3722
-     */
3723
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3724
-    {
3725
-        $fields = $this->field_settings();
3726
-        $selects = array();
3727
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3728
-            $this->get_this_model_name());
3729
-        foreach ($fields as $field_obj) {
3730
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3731
-                         . $field_obj->get_table_alias()
3732
-                         . "."
3733
-                         . $field_obj->get_table_column()
3734
-                         . " AS '"
3735
-                         . $table_alias_with_model_relation_chain_prefix
3736
-                         . $field_obj->get_table_alias()
3737
-                         . "."
3738
-                         . $field_obj->get_table_column()
3739
-                         . "'";
3740
-        }
3741
-        //make sure we are also getting the PKs of each table
3742
-        $tables = $this->get_tables();
3743
-        if (count($tables) > 1) {
3744
-            foreach ($tables as $table_obj) {
3745
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3746
-                                       . $table_obj->get_fully_qualified_pk_column();
3747
-                if (! in_array($qualified_pk_column, $selects)) {
3748
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3749
-                }
3750
-            }
3751
-        }
3752
-        return $selects;
3753
-    }
3754
-
3755
-
3756
-
3757
-    /**
3758
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3759
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3760
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3761
-     * SQL for joining, and the data types
3762
-     *
3763
-     * @param null|string                 $original_query_param
3764
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3765
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3766
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3767
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3768
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3769
-     *                                                          or 'Registration's
3770
-     * @param string                      $original_query_param what it originally was (eg
3771
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3772
-     *                                                          matches $query_param
3773
-     * @throws EE_Error
3774
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3775
-     */
3776
-    private function _extract_related_model_info_from_query_param(
3777
-        $query_param,
3778
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3779
-        $query_param_type,
3780
-        $original_query_param = null
3781
-    ) {
3782
-        if ($original_query_param === null) {
3783
-            $original_query_param = $query_param;
3784
-        }
3785
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3786
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3787
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3788
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3789
-        //check to see if we have a field on this model
3790
-        $this_model_fields = $this->field_settings(true);
3791
-        if (array_key_exists($query_param, $this_model_fields)) {
3792
-            if ($allow_fields) {
3793
-                return;
3794
-            } else {
3795
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3796
-                    "event_espresso"),
3797
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3798
-            }
3799
-        } //check if this is a special logic query param
3800
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3801
-            if ($allow_logic_query_params) {
3802
-                return;
3803
-            } else {
3804
-                throw new EE_Error(
3805
-                    sprintf(
3806
-                        __('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',
3807
-                            'event_espresso'),
3808
-                        implode('", "', $this->_logic_query_param_keys),
3809
-                        $query_param,
3810
-                        get_class($this),
3811
-                        '<br />',
3812
-                        "\t"
3813
-                        . ' $passed_in_query_info = <pre>'
3814
-                        . print_r($passed_in_query_info, true)
3815
-                        . '</pre>'
3816
-                        . "\n\t"
3817
-                        . ' $query_param_type = '
3818
-                        . $query_param_type
3819
-                        . "\n\t"
3820
-                        . ' $original_query_param = '
3821
-                        . $original_query_param
3822
-                    )
3823
-                );
3824
-            }
3825
-        } //check if it's a custom selection
3826
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3827
-            return;
3828
-        }
3829
-        //check if has a model name at the beginning
3830
-        //and
3831
-        //check if it's a field on a related model
3832
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3833
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3834
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3835
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3836
-                if ($query_param === '') {
3837
-                    //nothing left to $query_param
3838
-                    //we should actually end in a field name, not a model like this!
3839
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3840
-                        "event_espresso"),
3841
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3842
-                } else {
3843
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3844
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3845
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3846
-                    return;
3847
-                }
3848
-            } elseif ($query_param === $valid_related_model_name) {
3849
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3850
-                return;
3851
-            }
3852
-        }
3853
-        //ok so $query_param didn't start with a model name
3854
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3855
-        //it's wack, that's what it is
3856
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3857
-            "event_espresso"),
3858
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3859
-    }
3860
-
3861
-
3862
-
3863
-    /**
3864
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3865
-     * and store it on $passed_in_query_info
3866
-     *
3867
-     * @param string                      $model_name
3868
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3869
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3870
-     *                                                          model and $model_name. Eg, if we are querying Event,
3871
-     *                                                          and are adding a join to 'Payment' with the original
3872
-     *                                                          query param key
3873
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3874
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3875
-     *                                                          Payment wants to add default query params so that it
3876
-     *                                                          will know what models to prepend onto its default query
3877
-     *                                                          params or in case it wants to rename tables (in case
3878
-     *                                                          there are multiple joins to the same table)
3879
-     * @return void
3880
-     * @throws \EE_Error
3881
-     */
3882
-    private function _add_join_to_model(
3883
-        $model_name,
3884
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3885
-        $original_query_param
3886
-    ) {
3887
-        $relation_obj = $this->related_settings_for($model_name);
3888
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3889
-        //check if the relation is HABTM, because then we're essentially doing two joins
3890
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3891
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3892
-            $join_model_obj = $relation_obj->get_join_model();
3893
-            //replace the model specified with the join model for this relation chain, whi
3894
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3895
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3896
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3897
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3898
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3899
-            $passed_in_query_info->merge($new_query_info);
3900
-        }
3901
-        //now just join to the other table pointed to by the relation object, and add its data types
3902
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3903
-            array($model_relation_chain => $model_name),
3904
-            $relation_obj->get_join_statement($model_relation_chain));
3905
-        $passed_in_query_info->merge($new_query_info);
3906
-    }
3907
-
3908
-
3909
-
3910
-    /**
3911
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3912
-     *
3913
-     * @param array $where_params like EEM_Base::get_all
3914
-     * @return string of SQL
3915
-     * @throws \EE_Error
3916
-     */
3917
-    private function _construct_where_clause($where_params)
3918
-    {
3919
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3920
-        if ($SQL) {
3921
-            return " WHERE " . $SQL;
3922
-        } else {
3923
-            return '';
3924
-        }
3925
-    }
3926
-
3927
-
3928
-
3929
-    /**
3930
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3931
-     * and should be passed HAVING parameters, not WHERE parameters
3932
-     *
3933
-     * @param array $having_params
3934
-     * @return string
3935
-     * @throws \EE_Error
3936
-     */
3937
-    private function _construct_having_clause($having_params)
3938
-    {
3939
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3940
-        if ($SQL) {
3941
-            return " HAVING " . $SQL;
3942
-        } else {
3943
-            return '';
3944
-        }
3945
-    }
3946
-
3947
-
3948
-    /**
3949
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3950
-     * Event_Meta.meta_value = 'foo'))"
3951
-     *
3952
-     * @param array  $where_params see EEM_Base::get_all for documentation
3953
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3954
-     * @throws EE_Error
3955
-     * @return string of SQL
3956
-     */
3957
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3958
-    {
3959
-        $where_clauses = array();
3960
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3961
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3962
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3963
-                switch ($query_param) {
3964
-                    case 'not':
3965
-                    case 'NOT':
3966
-                        $where_clauses[] = "! ("
3967
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3968
-                                $glue)
3969
-                                           . ")";
3970
-                        break;
3971
-                    case 'and':
3972
-                    case 'AND':
3973
-                        $where_clauses[] = " ("
3974
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3975
-                                ' AND ')
3976
-                                           . ")";
3977
-                        break;
3978
-                    case 'or':
3979
-                    case 'OR':
3980
-                        $where_clauses[] = " ("
3981
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3982
-                                ' OR ')
3983
-                                           . ")";
3984
-                        break;
3985
-                }
3986
-            } else {
3987
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3988
-                //if it's not a normal field, maybe it's a custom selection?
3989
-                if (! $field_obj) {
3990
-                    if (isset($this->_custom_selections[$query_param][1])) {
3991
-                        $field_obj = $this->_custom_selections[$query_param][1];
3992
-                    } else {
3993
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3994
-                            "event_espresso"), $query_param));
3995
-                    }
3996
-                }
3997
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3998
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3999
-            }
4000
-        }
4001
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4002
-    }
4003
-
4004
-
4005
-
4006
-    /**
4007
-     * Takes the input parameter and extract the table name (alias) and column name
4008
-     *
4009
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4010
-     * @throws EE_Error
4011
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4012
-     */
4013
-    private function _deduce_column_name_from_query_param($query_param)
4014
-    {
4015
-        $field = $this->_deduce_field_from_query_param($query_param);
4016
-        if ($field) {
4017
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4018
-                $query_param);
4019
-            return $table_alias_prefix . $field->get_qualified_column();
4020
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4021
-            //maybe it's custom selection item?
4022
-            //if so, just use it as the "column name"
4023
-            return $query_param;
4024
-        } else {
4025
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4026
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4027
-        }
4028
-    }
4029
-
4030
-
4031
-
4032
-    /**
4033
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4034
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4035
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4036
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4037
-     *
4038
-     * @param string $condition_query_param_key
4039
-     * @return string
4040
-     */
4041
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4042
-    {
4043
-        $pos_of_star = strpos($condition_query_param_key, '*');
4044
-        if ($pos_of_star === false) {
4045
-            return $condition_query_param_key;
4046
-        } else {
4047
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4048
-            return $condition_query_param_sans_star;
4049
-        }
4050
-    }
4051
-
4052
-
4053
-
4054
-    /**
4055
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4056
-     *
4057
-     * @param                            mixed      array | string    $op_and_value
4058
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4059
-     * @throws EE_Error
4060
-     * @return string
4061
-     */
4062
-    private function _construct_op_and_value($op_and_value, $field_obj)
4063
-    {
4064
-        if (is_array($op_and_value)) {
4065
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4066
-            if (! $operator) {
4067
-                $php_array_like_string = array();
4068
-                foreach ($op_and_value as $key => $value) {
4069
-                    $php_array_like_string[] = "$key=>$value";
4070
-                }
4071
-                throw new EE_Error(
4072
-                    sprintf(
4073
-                        __(
4074
-                            "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))",
4075
-                            "event_espresso"
4076
-                        ),
4077
-                        implode(",", $php_array_like_string)
4078
-                    )
4079
-                );
4080
-            }
4081
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4082
-        } else {
4083
-            $operator = '=';
4084
-            $value = $op_and_value;
4085
-        }
4086
-        //check to see if the value is actually another field
4087
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4088
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4089
-        } elseif (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4090
-            //in this case, the value should be an array, or at least a comma-separated list
4091
-            //it will need to handle a little differently
4092
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4093
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4094
-            return $operator . SP . $cleaned_value;
4095
-        } elseif (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4096
-            //the value should be an array with count of two.
4097
-            if (count($value) !== 2) {
4098
-                throw new EE_Error(
4099
-                    sprintf(
4100
-                        __(
4101
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4102
-                            'event_espresso'
4103
-                        ),
4104
-                        "BETWEEN"
4105
-                    )
4106
-                );
4107
-            }
4108
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4109
-            return $operator . SP . $cleaned_value;
4110
-        } elseif (in_array($operator, $this->valid_null_style_operators())) {
4111
-            if ($value !== null) {
4112
-                throw new EE_Error(
4113
-                    sprintf(
4114
-                        __(
4115
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4116
-                            "event_espresso"
4117
-                        ),
4118
-                        $value,
4119
-                        $operator
4120
-                    )
4121
-                );
4122
-            }
4123
-            return $operator;
4124
-        } elseif (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4125
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4126
-            //remove other junk. So just treat it as a string.
4127
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4128
-        } elseif (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4129
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4130
-        } elseif (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4131
-            throw new EE_Error(
4132
-                sprintf(
4133
-                    __(
4134
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4135
-                        'event_espresso'
4136
-                    ),
4137
-                    $operator,
4138
-                    $operator
4139
-                )
4140
-            );
4141
-        } elseif (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4142
-            throw new EE_Error(
4143
-                sprintf(
4144
-                    __(
4145
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4146
-                        'event_espresso'
4147
-                    ),
4148
-                    $operator,
4149
-                    $operator
4150
-                )
4151
-            );
4152
-        } else {
4153
-            throw new EE_Error(
4154
-                sprintf(
4155
-                    __(
4156
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4157
-                        "event_espresso"
4158
-                    ),
4159
-                    http_build_query($op_and_value)
4160
-                )
4161
-            );
4162
-        }
4163
-    }
4164
-
4165
-
4166
-
4167
-    /**
4168
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4169
-     *
4170
-     * @param array                      $values
4171
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4172
-     *                                              '%s'
4173
-     * @return string
4174
-     * @throws \EE_Error
4175
-     */
4176
-    public function _construct_between_value($values, $field_obj)
4177
-    {
4178
-        $cleaned_values = array();
4179
-        foreach ($values as $value) {
4180
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4181
-        }
4182
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4183
-    }
4184
-
4185
-
4186
-
4187
-    /**
4188
-     * Takes an array or a comma-separated list of $values and cleans them
4189
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4190
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4191
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4192
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4193
-     *
4194
-     * @param mixed                      $values    array or comma-separated string
4195
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4196
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4197
-     * @throws \EE_Error
4198
-     */
4199
-    public function _construct_in_value($values, $field_obj)
4200
-    {
4201
-        //check if the value is a CSV list
4202
-        if (is_string($values)) {
4203
-            //in which case, turn it into an array
4204
-            $values = explode(",", $values);
4205
-        }
4206
-        $cleaned_values = array();
4207
-        foreach ($values as $value) {
4208
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4209
-        }
4210
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4211
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4212
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4213
-        if (empty($cleaned_values)) {
4214
-            $all_fields = $this->field_settings();
4215
-            $a_field = array_shift($all_fields);
4216
-            $main_table = $this->_get_main_table();
4217
-            $cleaned_values[] = "SELECT "
4218
-                                . $a_field->get_table_column()
4219
-                                . " FROM "
4220
-                                . $main_table->get_table_name()
4221
-                                . " WHERE FALSE";
4222
-        }
4223
-        return "(" . implode(",", $cleaned_values) . ")";
4224
-    }
4225
-
4226
-
4227
-
4228
-    /**
4229
-     * @param mixed                      $value
4230
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4231
-     * @throws EE_Error
4232
-     * @return false|null|string
4233
-     */
4234
-    private function _wpdb_prepare_using_field($value, $field_obj)
4235
-    {
4236
-        /** @type WPDB $wpdb */
4237
-        global $wpdb;
4238
-        if ($field_obj instanceof EE_Model_Field_Base) {
4239
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4240
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4241
-        } else {//$field_obj should really just be a data type
4242
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4243
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4244
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4245
-            }
4246
-            return $wpdb->prepare($field_obj, $value);
4247
-        }
4248
-    }
4249
-
4250
-
4251
-
4252
-    /**
4253
-     * Takes the input parameter and finds the model field that it indicates.
4254
-     *
4255
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4256
-     * @throws EE_Error
4257
-     * @return EE_Model_Field_Base
4258
-     */
4259
-    protected function _deduce_field_from_query_param($query_param_name)
4260
-    {
4261
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4262
-        //which will help us find the database table and column
4263
-        $query_param_parts = explode(".", $query_param_name);
4264
-        if (empty($query_param_parts)) {
4265
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4266
-                'event_espresso'), $query_param_name));
4267
-        }
4268
-        $number_of_parts = count($query_param_parts);
4269
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4270
-        if ($number_of_parts === 1) {
4271
-            $field_name = $last_query_param_part;
4272
-            $model_obj = $this;
4273
-        } else {// $number_of_parts >= 2
4274
-            //the last part is the column name, and there are only 2parts. therefore...
4275
-            $field_name = $last_query_param_part;
4276
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4277
-        }
4278
-        try {
4279
-            return $model_obj->field_settings_for($field_name);
4280
-        } catch (EE_Error $e) {
4281
-            return null;
4282
-        }
4283
-    }
4284
-
4285
-
4286
-
4287
-    /**
4288
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4289
-     * alias and column which corresponds to it
4290
-     *
4291
-     * @param string $field_name
4292
-     * @throws EE_Error
4293
-     * @return string
4294
-     */
4295
-    public function _get_qualified_column_for_field($field_name)
4296
-    {
4297
-        $all_fields = $this->field_settings();
4298
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4299
-        if ($field) {
4300
-            return $field->get_qualified_column();
4301
-        } else {
4302
-            throw new EE_Error(sprintf(__("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.",
4303
-                'event_espresso'), $field_name, get_class($this)));
4304
-        }
4305
-    }
4306
-
4307
-
4308
-
4309
-    /**
4310
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4311
-     * Example usage:
4312
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4313
-     *      array(),
4314
-     *      ARRAY_A,
4315
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4316
-     *  );
4317
-     * is equivalent to
4318
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4319
-     * and
4320
-     *  EEM_Event::instance()->get_all_wpdb_results(
4321
-     *      array(
4322
-     *          array(
4323
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4324
-     *          ),
4325
-     *          ARRAY_A,
4326
-     *          implode(
4327
-     *              ', ',
4328
-     *              array_merge(
4329
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4330
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4331
-     *              )
4332
-     *          )
4333
-     *      )
4334
-     *  );
4335
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4336
-     *
4337
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4338
-     *                                            and the one whose fields you are selecting for example: when querying
4339
-     *                                            tickets model and selecting fields from the tickets model you would
4340
-     *                                            leave this parameter empty, because no models are needed to join
4341
-     *                                            between the queried model and the selected one. Likewise when
4342
-     *                                            querying the datetime model and selecting fields from the tickets
4343
-     *                                            model, it would also be left empty, because there is a direct
4344
-     *                                            relation from datetimes to tickets, so no model is needed to join
4345
-     *                                            them together. However, when querying from the event model and
4346
-     *                                            selecting fields from the ticket model, you should provide the string
4347
-     *                                            'Datetime', indicating that the event model must first join to the
4348
-     *                                            datetime model in order to find its relation to ticket model.
4349
-     *                                            Also, when querying from the venue model and selecting fields from
4350
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4351
-     *                                            indicating you need to join the venue model to the event model,
4352
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4353
-     *                                            This string is used to deduce the prefix that gets added onto the
4354
-     *                                            models' tables qualified columns
4355
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4356
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4357
-     *                                            qualified column names
4358
-     * @return array|string
4359
-     */
4360
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4361
-    {
4362
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4363
-        $qualified_columns = array();
4364
-        foreach ($this->field_settings() as $field_name => $field) {
4365
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4366
-        }
4367
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4368
-    }
4369
-
4370
-
4371
-
4372
-    /**
4373
-     * constructs the select use on special limit joins
4374
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4375
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4376
-     * (as that is typically where the limits would be set).
4377
-     *
4378
-     * @param  string       $table_alias The table the select is being built for
4379
-     * @param  mixed|string $limit       The limit for this select
4380
-     * @return string                The final select join element for the query.
4381
-     */
4382
-    public function _construct_limit_join_select($table_alias, $limit)
4383
-    {
4384
-        $SQL = '';
4385
-        foreach ($this->_tables as $table_obj) {
4386
-            if ($table_obj instanceof EE_Primary_Table) {
4387
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4388
-                    ? $table_obj->get_select_join_limit($limit)
4389
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4390
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4391
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4392
-                    ? $table_obj->get_select_join_limit_join($limit)
4393
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4394
-            }
4395
-        }
4396
-        return $SQL;
4397
-    }
4398
-
4399
-
4400
-
4401
-    /**
4402
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4403
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4404
-     *
4405
-     * @return string SQL
4406
-     * @throws \EE_Error
4407
-     */
4408
-    public function _construct_internal_join()
4409
-    {
4410
-        $SQL = $this->_get_main_table()->get_table_sql();
4411
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4412
-        return $SQL;
4413
-    }
4414
-
4415
-
4416
-
4417
-    /**
4418
-     * Constructs the SQL for joining all the tables on this model.
4419
-     * Normally $alias should be the primary table's alias, but in cases where
4420
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4421
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4422
-     * alias, this will construct SQL like:
4423
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4424
-     * With $alias being a secondary table's alias, this will construct SQL like:
4425
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4426
-     *
4427
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4428
-     * @return string
4429
-     */
4430
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4431
-    {
4432
-        $SQL = '';
4433
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4434
-        foreach ($this->_tables as $table_obj) {
4435
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4436
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4437
-                    //so we're joining to this table, meaning the table is already in
4438
-                    //the FROM statement, BUT the primary table isn't. So we want
4439
-                    //to add the inverse join sql
4440
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4441
-                } else {
4442
-                    //just add a regular JOIN to this table from the primary table
4443
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4444
-                }
4445
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4446
-        }
4447
-        return $SQL;
4448
-    }
4449
-
4450
-
4451
-
4452
-    /**
4453
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4454
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4455
-     * their data type (eg, '%s', '%d', etc)
4456
-     *
4457
-     * @return array
4458
-     */
4459
-    public function _get_data_types()
4460
-    {
4461
-        $data_types = array();
4462
-        foreach ($this->field_settings() as $field_obj) {
4463
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4464
-            /** @var $field_obj EE_Model_Field_Base */
4465
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4466
-        }
4467
-        return $data_types;
4468
-    }
4469
-
4470
-
4471
-
4472
-    /**
4473
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4474
-     *
4475
-     * @param string $model_name
4476
-     * @throws EE_Error
4477
-     * @return EEM_Base
4478
-     */
4479
-    public function get_related_model_obj($model_name)
4480
-    {
4481
-        $model_classname = "EEM_" . $model_name;
4482
-        if (! class_exists($model_classname)) {
4483
-            throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4484
-                'event_espresso'), $model_name, $model_classname));
4485
-        }
4486
-        return call_user_func($model_classname . "::instance");
4487
-    }
4488
-
4489
-
4490
-
4491
-    /**
4492
-     * Returns the array of EE_ModelRelations for this model.
4493
-     *
4494
-     * @return EE_Model_Relation_Base[]
4495
-     */
4496
-    public function relation_settings()
4497
-    {
4498
-        return $this->_model_relations;
4499
-    }
4500
-
4501
-
4502
-
4503
-    /**
4504
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4505
-     * because without THOSE models, this model probably doesn't have much purpose.
4506
-     * (Eg, without an event, datetimes have little purpose.)
4507
-     *
4508
-     * @return EE_Belongs_To_Relation[]
4509
-     */
4510
-    public function belongs_to_relations()
4511
-    {
4512
-        $belongs_to_relations = array();
4513
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4514
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4515
-                $belongs_to_relations[$model_name] = $relation_obj;
4516
-            }
4517
-        }
4518
-        return $belongs_to_relations;
4519
-    }
4520
-
4521
-
4522
-
4523
-    /**
4524
-     * Returns the specified EE_Model_Relation, or throws an exception
4525
-     *
4526
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4527
-     * @throws EE_Error
4528
-     * @return EE_Model_Relation_Base
4529
-     */
4530
-    public function related_settings_for($relation_name)
4531
-    {
4532
-        $relatedModels = $this->relation_settings();
4533
-        if (! array_key_exists($relation_name, $relatedModels)) {
4534
-            throw new EE_Error(
4535
-                sprintf(
4536
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4537
-                        'event_espresso'),
4538
-                    $relation_name,
4539
-                    $this->_get_class_name(),
4540
-                    implode(', ', array_keys($relatedModels))
4541
-                )
4542
-            );
4543
-        }
4544
-        return $relatedModels[$relation_name];
4545
-    }
4546
-
4547
-
4548
-
4549
-    /**
4550
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4551
-     * fields
4552
-     *
4553
-     * @param string $fieldName
4554
-     * @param boolean $include_db_only_fields
4555
-     * @throws EE_Error
4556
-     * @return EE_Model_Field_Base
4557
-     */
4558
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4559
-    {
4560
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4561
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4562
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4563
-                get_class($this)));
4564
-        }
4565
-        return $fieldSettings[$fieldName];
4566
-    }
4567
-
4568
-
4569
-
4570
-    /**
4571
-     * Checks if this field exists on this model
4572
-     *
4573
-     * @param string $fieldName a key in the model's _field_settings array
4574
-     * @return boolean
4575
-     */
4576
-    public function has_field($fieldName)
4577
-    {
4578
-        $fieldSettings = $this->field_settings(true);
4579
-        if (isset($fieldSettings[$fieldName])) {
4580
-            return true;
4581
-        } else {
4582
-            return false;
4583
-        }
4584
-    }
4585
-
4586
-
4587
-
4588
-    /**
4589
-     * Returns whether or not this model has a relation to the specified model
4590
-     *
4591
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4592
-     * @return boolean
4593
-     */
4594
-    public function has_relation($relation_name)
4595
-    {
4596
-        $relations = $this->relation_settings();
4597
-        if (isset($relations[$relation_name])) {
4598
-            return true;
4599
-        } else {
4600
-            return false;
4601
-        }
4602
-    }
4603
-
4604
-
4605
-
4606
-    /**
4607
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4608
-     * Eg, on EE_Answer that would be ANS_ID field object
4609
-     *
4610
-     * @param $field_obj
4611
-     * @return boolean
4612
-     */
4613
-    public function is_primary_key_field($field_obj)
4614
-    {
4615
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4616
-    }
4617
-
4618
-
4619
-
4620
-    /**
4621
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4622
-     * Eg, on EE_Answer that would be ANS_ID field object
4623
-     *
4624
-     * @return EE_Model_Field_Base
4625
-     * @throws EE_Error
4626
-     */
4627
-    public function get_primary_key_field()
4628
-    {
4629
-        if ($this->_primary_key_field === null) {
4630
-            foreach ($this->field_settings(true) as $field_obj) {
4631
-                if ($this->is_primary_key_field($field_obj)) {
4632
-                    $this->_primary_key_field = $field_obj;
4633
-                    break;
4634
-                }
4635
-            }
4636
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4637
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4638
-                    get_class($this)));
4639
-            }
4640
-        }
4641
-        return $this->_primary_key_field;
4642
-    }
4643
-
4644
-
4645
-
4646
-    /**
4647
-     * Returns whether or not not there is a primary key on this model.
4648
-     * Internally does some caching.
4649
-     *
4650
-     * @return boolean
4651
-     */
4652
-    public function has_primary_key_field()
4653
-    {
4654
-        if ($this->_has_primary_key_field === null) {
4655
-            try {
4656
-                $this->get_primary_key_field();
4657
-                $this->_has_primary_key_field = true;
4658
-            } catch (EE_Error $e) {
4659
-                $this->_has_primary_key_field = false;
4660
-            }
4661
-        }
4662
-        return $this->_has_primary_key_field;
4663
-    }
4664
-
4665
-
4666
-
4667
-    /**
4668
-     * Finds the first field of type $field_class_name.
4669
-     *
4670
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4671
-     *                                 EE_Foreign_Key_Field, etc
4672
-     * @return EE_Model_Field_Base or null if none is found
4673
-     */
4674
-    public function get_a_field_of_type($field_class_name)
4675
-    {
4676
-        foreach ($this->field_settings() as $field) {
4677
-            if ($field instanceof $field_class_name) {
4678
-                return $field;
4679
-            }
4680
-        }
4681
-        return null;
4682
-    }
4683
-
4684
-
4685
-
4686
-    /**
4687
-     * Gets a foreign key field pointing to model.
4688
-     *
4689
-     * @param string $model_name eg Event, Registration, not EEM_Event
4690
-     * @return EE_Foreign_Key_Field_Base
4691
-     * @throws EE_Error
4692
-     */
4693
-    public function get_foreign_key_to($model_name)
4694
-    {
4695
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4696
-            foreach ($this->field_settings() as $field) {
4697
-                if (
4698
-                    $field instanceof EE_Foreign_Key_Field_Base
4699
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4700
-                ) {
4701
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4702
-                    break;
4703
-                }
4704
-            }
4705
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4706
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4707
-                    'event_espresso'), $model_name, get_class($this)));
4708
-            }
4709
-        }
4710
-        return $this->_cache_foreign_key_to_fields[$model_name];
4711
-    }
4712
-
4713
-
4714
-
4715
-    /**
4716
-     * Gets the actual table for the table alias
4717
-     *
4718
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4719
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4720
-     *                            Either one works
4721
-     * @return EE_Table_Base
4722
-     */
4723
-    public function get_table_for_alias($table_alias)
4724
-    {
4725
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4726
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4727
-    }
4728
-
4729
-
4730
-
4731
-    /**
4732
-     * Returns a flat array of all field son this model, instead of organizing them
4733
-     * by table_alias as they are in the constructor.
4734
-     *
4735
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4736
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4737
-     */
4738
-    public function field_settings($include_db_only_fields = false)
4739
-    {
4740
-        if ($include_db_only_fields) {
4741
-            if ($this->_cached_fields === null) {
4742
-                $this->_cached_fields = array();
4743
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4744
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4745
-                        $this->_cached_fields[$field_name] = $field_obj;
4746
-                    }
4747
-                }
4748
-            }
4749
-            return $this->_cached_fields;
4750
-        } else {
4751
-            if ($this->_cached_fields_non_db_only === null) {
4752
-                $this->_cached_fields_non_db_only = array();
4753
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4754
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4755
-                        /** @var $field_obj EE_Model_Field_Base */
4756
-                        if (! $field_obj->is_db_only_field()) {
4757
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4758
-                        }
4759
-                    }
4760
-                }
4761
-            }
4762
-            return $this->_cached_fields_non_db_only;
4763
-        }
4764
-    }
4765
-
4766
-
4767
-
4768
-    /**
4769
-     *        cycle though array of attendees and create objects out of each item
4770
-     *
4771
-     * @access        private
4772
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4773
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4774
-     *                           numerically indexed)
4775
-     * @throws \EE_Error
4776
-     */
4777
-    protected function _create_objects($rows = array())
4778
-    {
4779
-        $array_of_objects = array();
4780
-        if (empty($rows)) {
4781
-            return array();
4782
-        }
4783
-        $count_if_model_has_no_primary_key = 0;
4784
-        $has_primary_key = $this->has_primary_key_field();
4785
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4786
-        foreach ((array)$rows as $row) {
4787
-            if (empty($row)) {
4788
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4789
-                return array();
4790
-            }
4791
-            //check if we've already set this object in the results array,
4792
-            //in which case there's no need to process it further (again)
4793
-            if ($has_primary_key) {
4794
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4795
-                    $row,
4796
-                    $primary_key_field->get_qualified_column(),
4797
-                    $primary_key_field->get_table_column()
4798
-                );
4799
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4800
-                    continue;
4801
-                }
4802
-            }
4803
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4804
-            if (! $classInstance) {
4805
-                throw new EE_Error(
4806
-                    sprintf(
4807
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4808
-                        $this->get_this_model_name(),
4809
-                        http_build_query($row)
4810
-                    )
4811
-                );
4812
-            }
4813
-            //set the timezone on the instantiated objects
4814
-            $classInstance->set_timezone($this->_timezone);
4815
-            //make sure if there is any timezone setting present that we set the timezone for the object
4816
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4817
-            $array_of_objects[$key] = $classInstance;
4818
-            //also, for all the relations of type BelongsTo, see if we can cache
4819
-            //those related models
4820
-            //(we could do this for other relations too, but if there are conditions
4821
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4822
-            //so it requires a little more thought than just caching them immediately...)
4823
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4824
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4825
-                    //check if this model's INFO is present. If so, cache it on the model
4826
-                    $other_model = $relation_obj->get_other_model();
4827
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4828
-                    //if we managed to make a model object from the results, cache it on the main model object
4829
-                    if ($other_model_obj_maybe) {
4830
-                        //set timezone on these other model objects if they are present
4831
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4832
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4833
-                    }
4834
-                }
4835
-            }
4836
-        }
4837
-        return $array_of_objects;
4838
-    }
4839
-
4840
-
4841
-
4842
-    /**
4843
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4844
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4845
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4846
-     * object (as set in the model_field!).
4847
-     *
4848
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4849
-     */
4850
-    public function create_default_object()
4851
-    {
4852
-        $this_model_fields_and_values = array();
4853
-        //setup the row using default values;
4854
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4855
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4856
-        }
4857
-        $className = $this->_get_class_name();
4858
-        $classInstance = EE_Registry::instance()
4859
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4860
-        return $classInstance;
4861
-    }
4862
-
4863
-
4864
-
4865
-    /**
4866
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4867
-     *                             or an stdClass where each property is the name of a column,
4868
-     * @return EE_Base_Class
4869
-     * @throws \EE_Error
4870
-     */
4871
-    public function instantiate_class_from_array_or_object($cols_n_values)
4872
-    {
4873
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4874
-            $cols_n_values = get_object_vars($cols_n_values);
4875
-        }
4876
-        $primary_key = null;
4877
-        //make sure the array only has keys that are fields/columns on this model
4878
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4879
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4880
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4881
-        }
4882
-        $className = $this->_get_class_name();
4883
-        //check we actually found results that we can use to build our model object
4884
-        //if not, return null
4885
-        if ($this->has_primary_key_field()) {
4886
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4887
-                return null;
4888
-            }
4889
-        } else if ($this->unique_indexes()) {
4890
-            $first_column = reset($this_model_fields_n_values);
4891
-            if (empty($first_column)) {
4892
-                return null;
4893
-            }
4894
-        }
4895
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4896
-        if ($primary_key) {
4897
-            $classInstance = $this->get_from_entity_map($primary_key);
4898
-            if (! $classInstance) {
4899
-                $classInstance = EE_Registry::instance()
4900
-                                            ->load_class($className,
4901
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4902
-                // add this new object to the entity map
4903
-                $classInstance = $this->add_to_entity_map($classInstance);
4904
-            }
4905
-        } else {
4906
-            $classInstance = EE_Registry::instance()
4907
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4908
-                                            true, false);
4909
-        }
4910
-        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4911
-        $this->set_timezone($classInstance->get_timezone());
4912
-        return $classInstance;
4913
-    }
4914
-
4915
-
4916
-
4917
-    /**
4918
-     * Gets the model object from the  entity map if it exists
4919
-     *
4920
-     * @param int|string $id the ID of the model object
4921
-     * @return EE_Base_Class
4922
-     */
4923
-    public function get_from_entity_map($id)
4924
-    {
4925
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4926
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4927
-    }
4928
-
4929
-
4930
-
4931
-    /**
4932
-     * add_to_entity_map
4933
-     * Adds the object to the model's entity mappings
4934
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4935
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4936
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4937
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4938
-     *        then this method should be called immediately after the update query
4939
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4940
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4941
-     *
4942
-     * @param    EE_Base_Class $object
4943
-     * @throws EE_Error
4944
-     * @return \EE_Base_Class
4945
-     */
4946
-    public function add_to_entity_map(EE_Base_Class $object)
4947
-    {
4948
-        $className = $this->_get_class_name();
4949
-        if (! $object instanceof $className) {
4950
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4951
-                is_object($object) ? get_class($object) : $object, $className));
4952
-        }
4953
-        /** @var $object EE_Base_Class */
4954
-        if (! $object->ID()) {
4955
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4956
-                "event_espresso"), get_class($this)));
4957
-        }
4958
-        // double check it's not already there
4959
-        $classInstance = $this->get_from_entity_map($object->ID());
4960
-        if ($classInstance) {
4961
-            return $classInstance;
4962
-        } else {
4963
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4964
-            return $object;
4965
-        }
4966
-    }
4967
-
4968
-
4969
-
4970
-    /**
4971
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4972
-     * if no identifier is provided, then the entire entity map is emptied
4973
-     *
4974
-     * @param int|string $id the ID of the model object
4975
-     * @return boolean
4976
-     */
4977
-    public function clear_entity_map($id = null)
4978
-    {
4979
-        if (empty($id)) {
4980
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4981
-            return true;
4982
-        }
4983
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4984
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4985
-            return true;
4986
-        }
4987
-        return false;
4988
-    }
4989
-
4990
-
4991
-
4992
-    /**
4993
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4994
-     * Given an array where keys are column (or column alias) names and values,
4995
-     * returns an array of their corresponding field names and database values
4996
-     *
4997
-     * @param array $cols_n_values
4998
-     * @return array
4999
-     */
5000
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5001
-    {
5002
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5003
-    }
5004
-
5005
-
5006
-
5007
-    /**
5008
-     * _deduce_fields_n_values_from_cols_n_values
5009
-     * Given an array where keys are column (or column alias) names and values,
5010
-     * returns an array of their corresponding field names and database values
5011
-     *
5012
-     * @param string $cols_n_values
5013
-     * @return array
5014
-     */
5015
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5016
-    {
5017
-        $this_model_fields_n_values = array();
5018
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5019
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5020
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5021
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5022
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5023
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5024
-                    if (! $field_obj->is_db_only_field()) {
5025
-                        //prepare field as if its coming from db
5026
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5027
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5028
-                    }
5029
-                }
5030
-            } else {
5031
-                //the table's rows existed. Use their values
5032
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5033
-                    if (! $field_obj->is_db_only_field()) {
5034
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5035
-                            $cols_n_values, $field_obj->get_qualified_column(),
5036
-                            $field_obj->get_table_column()
5037
-                        );
5038
-                    }
5039
-                }
5040
-            }
5041
-        }
5042
-        return $this_model_fields_n_values;
5043
-    }
5044
-
5045
-
5046
-
5047
-    /**
5048
-     * @param $cols_n_values
5049
-     * @param $qualified_column
5050
-     * @param $regular_column
5051
-     * @return null
5052
-     */
5053
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5054
-    {
5055
-        $value = null;
5056
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5057
-        //does the field on the model relate to this column retrieved from the db?
5058
-        //or is it a db-only field? (not relating to the model)
5059
-        if (isset($cols_n_values[$qualified_column])) {
5060
-            $value = $cols_n_values[$qualified_column];
5061
-        } elseif (isset($cols_n_values[$regular_column])) {
5062
-            $value = $cols_n_values[$regular_column];
5063
-        }
5064
-        return $value;
5065
-    }
5066
-
5067
-
5068
-
5069
-    /**
5070
-     * refresh_entity_map_from_db
5071
-     * Makes sure the model object in the entity map at $id assumes the values
5072
-     * of the database (opposite of EE_base_Class::save())
5073
-     *
5074
-     * @param int|string $id
5075
-     * @return EE_Base_Class
5076
-     * @throws \EE_Error
5077
-     */
5078
-    public function refresh_entity_map_from_db($id)
5079
-    {
5080
-        $obj_in_map = $this->get_from_entity_map($id);
5081
-        if ($obj_in_map) {
5082
-            $wpdb_results = $this->_get_all_wpdb_results(
5083
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5084
-            );
5085
-            if ($wpdb_results && is_array($wpdb_results)) {
5086
-                $one_row = reset($wpdb_results);
5087
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5088
-                    $obj_in_map->set_from_db($field_name, $db_value);
5089
-                }
5090
-                //clear the cache of related model objects
5091
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5092
-                    $obj_in_map->clear_cache($relation_name, null, true);
5093
-                }
5094
-            }
5095
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5096
-            return $obj_in_map;
5097
-        } else {
5098
-            return $this->get_one_by_ID($id);
5099
-        }
5100
-    }
5101
-
5102
-
5103
-
5104
-    /**
5105
-     * refresh_entity_map_with
5106
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5107
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5108
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5109
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5110
-     *
5111
-     * @param int|string    $id
5112
-     * @param EE_Base_Class $replacing_model_obj
5113
-     * @return \EE_Base_Class
5114
-     * @throws \EE_Error
5115
-     */
5116
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5117
-    {
5118
-        $obj_in_map = $this->get_from_entity_map($id);
5119
-        if ($obj_in_map) {
5120
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5121
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5122
-                    $obj_in_map->set($field_name, $value);
5123
-                }
5124
-                //make the model object in the entity map's cache match the $replacing_model_obj
5125
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5126
-                    $obj_in_map->clear_cache($relation_name, null, true);
5127
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5128
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5129
-                    }
5130
-                }
5131
-            }
5132
-            return $obj_in_map;
5133
-        } else {
5134
-            $this->add_to_entity_map($replacing_model_obj);
5135
-            return $replacing_model_obj;
5136
-        }
5137
-    }
5138
-
5139
-
5140
-
5141
-    /**
5142
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5143
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5144
-     * require_once($this->_getClassName().".class.php");
5145
-     *
5146
-     * @return string
5147
-     */
5148
-    private function _get_class_name()
5149
-    {
5150
-        return "EE_" . $this->get_this_model_name();
5151
-    }
5152
-
5153
-
5154
-
5155
-    /**
5156
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5157
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5158
-     * it would be 'Events'.
5159
-     *
5160
-     * @param int $quantity
5161
-     * @return string
5162
-     */
5163
-    public function item_name($quantity = 1)
5164
-    {
5165
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5166
-    }
5167
-
5168
-
5169
-
5170
-    /**
5171
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5172
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5173
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5174
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5175
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5176
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5177
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5178
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5179
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5180
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5181
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5182
-     *        return $previousReturnValue.$returnString;
5183
-     * }
5184
-     * require('EEM_Answer.model.php');
5185
-     * $answer=EEM_Answer::instance();
5186
-     * echo $answer->my_callback('monkeys',100);
5187
-     * //will output "you called my_callback! and passed args:monkeys,100"
5188
-     *
5189
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5190
-     * @param array  $args       array of original arguments passed to the function
5191
-     * @throws EE_Error
5192
-     * @return mixed whatever the plugin which calls add_filter decides
5193
-     */
5194
-    public function __call($methodName, $args)
5195
-    {
5196
-        $className = get_class($this);
5197
-        $tagName = "FHEE__{$className}__{$methodName}";
5198
-        if (! has_filter($tagName)) {
5199
-            throw new EE_Error(
5200
-                sprintf(
5201
-                    __('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 );',
5202
-                        'event_espresso'),
5203
-                    $methodName,
5204
-                    $className,
5205
-                    $tagName,
5206
-                    '<br />'
5207
-                )
5208
-            );
5209
-        }
5210
-        return apply_filters($tagName, null, $this, $args);
5211
-    }
5212
-
5213
-
5214
-
5215
-    /**
5216
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5217
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5218
-     *
5219
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5220
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5221
-     *                                                       the object's class name
5222
-     *                                                       or object's ID
5223
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5224
-     *                                                       exists in the database. If it does not, we add it
5225
-     * @throws EE_Error
5226
-     * @return EE_Base_Class
5227
-     */
5228
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5229
-    {
5230
-        $className = $this->_get_class_name();
5231
-        if ($base_class_obj_or_id instanceof $className) {
5232
-            $model_object = $base_class_obj_or_id;
5233
-        } else {
5234
-            $primary_key_field = $this->get_primary_key_field();
5235
-            if (
5236
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5237
-                && (
5238
-                    is_int($base_class_obj_or_id)
5239
-                    || is_string($base_class_obj_or_id)
5240
-                )
5241
-            ) {
5242
-                // assume it's an ID.
5243
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5244
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5245
-            } else if (
5246
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5247
-                && is_string($base_class_obj_or_id)
5248
-            ) {
5249
-                // assume its a string representation of the object
5250
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5251
-            } else {
5252
-                throw new EE_Error(
5253
-                    sprintf(
5254
-                        __(
5255
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5256
-                            'event_espresso'
5257
-                        ),
5258
-                        $base_class_obj_or_id,
5259
-                        $this->_get_class_name(),
5260
-                        print_r($base_class_obj_or_id, true)
5261
-                    )
5262
-                );
5263
-            }
5264
-        }
5265
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5266
-            $model_object->save();
5267
-        }
5268
-        return $model_object;
5269
-    }
5270
-
5271
-
5272
-
5273
-    /**
5274
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5275
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5276
-     * returns it ID.
5277
-     *
5278
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5279
-     * @return int|string depending on the type of this model object's ID
5280
-     * @throws EE_Error
5281
-     */
5282
-    public function ensure_is_ID($base_class_obj_or_id)
5283
-    {
5284
-        $className = $this->_get_class_name();
5285
-        if ($base_class_obj_or_id instanceof $className) {
5286
-            /** @var $base_class_obj_or_id EE_Base_Class */
5287
-            $id = $base_class_obj_or_id->ID();
5288
-        } elseif (is_int($base_class_obj_or_id)) {
5289
-            //assume it's an ID
5290
-            $id = $base_class_obj_or_id;
5291
-        } elseif (is_string($base_class_obj_or_id)) {
5292
-            //assume its a string representation of the object
5293
-            $id = $base_class_obj_or_id;
5294
-        } else {
5295
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5296
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5297
-                print_r($base_class_obj_or_id, true)));
5298
-        }
5299
-        return $id;
5300
-    }
5301
-
5302
-
5303
-
5304
-    /**
5305
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5306
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5307
-     * been sanitized and converted into the appropriate domain.
5308
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5309
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5310
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5311
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5312
-     * $EVT = EEM_Event::instance(); $old_setting =
5313
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5314
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5315
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5316
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5317
-     *
5318
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5319
-     * @return void
5320
-     */
5321
-    public function assume_values_already_prepared_by_model_object(
5322
-        $values_already_prepared = self::not_prepared_by_model_object
5323
-    ) {
5324
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5325
-    }
5326
-
5327
-
5328
-
5329
-    /**
5330
-     * Read comments for assume_values_already_prepared_by_model_object()
5331
-     *
5332
-     * @return int
5333
-     */
5334
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5335
-    {
5336
-        return $this->_values_already_prepared_by_model_object;
5337
-    }
5338
-
5339
-
5340
-
5341
-    /**
5342
-     * Gets all the indexes on this model
5343
-     *
5344
-     * @return EE_Index[]
5345
-     */
5346
-    public function indexes()
5347
-    {
5348
-        return $this->_indexes;
5349
-    }
5350
-
5351
-
5352
-
5353
-    /**
5354
-     * Gets all the Unique Indexes on this model
5355
-     *
5356
-     * @return EE_Unique_Index[]
5357
-     */
5358
-    public function unique_indexes()
5359
-    {
5360
-        $unique_indexes = array();
5361
-        foreach ($this->_indexes as $name => $index) {
5362
-            if ($index instanceof EE_Unique_Index) {
5363
-                $unique_indexes [$name] = $index;
5364
-            }
5365
-        }
5366
-        return $unique_indexes;
5367
-    }
5368
-
5369
-
5370
-
5371
-    /**
5372
-     * Gets all the fields which, when combined, make the primary key.
5373
-     * This is usually just an array with 1 element (the primary key), but in cases
5374
-     * where there is no primary key, it's a combination of fields as defined
5375
-     * on a primary index
5376
-     *
5377
-     * @return EE_Model_Field_Base[] indexed by the field's name
5378
-     * @throws \EE_Error
5379
-     */
5380
-    public function get_combined_primary_key_fields()
5381
-    {
5382
-        foreach ($this->indexes() as $index) {
5383
-            if ($index instanceof EE_Primary_Key_Index) {
5384
-                return $index->fields();
5385
-            }
5386
-        }
5387
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5388
-    }
5389
-
5390
-
5391
-
5392
-    /**
5393
-     * Used to build a primary key string (when the model has no primary key),
5394
-     * which can be used a unique string to identify this model object.
5395
-     *
5396
-     * @param array $cols_n_values keys are field names, values are their values
5397
-     * @return string
5398
-     * @throws \EE_Error
5399
-     */
5400
-    public function get_index_primary_key_string($cols_n_values)
5401
-    {
5402
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5403
-            $this->get_combined_primary_key_fields());
5404
-        return http_build_query($cols_n_values_for_primary_key_index);
5405
-    }
5406
-
5407
-
5408
-
5409
-    /**
5410
-     * Gets the field values from the primary key string
5411
-     *
5412
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5413
-     * @param string $index_primary_key_string
5414
-     * @return null|array
5415
-     * @throws \EE_Error
5416
-     */
5417
-    public function parse_index_primary_key_string($index_primary_key_string)
5418
-    {
5419
-        $key_fields = $this->get_combined_primary_key_fields();
5420
-        //check all of them are in the $id
5421
-        $key_vals_in_combined_pk = array();
5422
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5423
-        foreach ($key_fields as $key_field_name => $field_obj) {
5424
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5425
-                return null;
5426
-            }
5427
-        }
5428
-        return $key_vals_in_combined_pk;
5429
-    }
5430
-
5431
-
5432
-
5433
-    /**
5434
-     * verifies that an array of key-value pairs for model fields has a key
5435
-     * for each field comprising the primary key index
5436
-     *
5437
-     * @param array $key_vals
5438
-     * @return boolean
5439
-     * @throws \EE_Error
5440
-     */
5441
-    public function has_all_combined_primary_key_fields($key_vals)
5442
-    {
5443
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5444
-        foreach ($keys_it_should_have as $key) {
5445
-            if (! isset($key_vals[$key])) {
5446
-                return false;
5447
-            }
5448
-        }
5449
-        return true;
5450
-    }
5451
-
5452
-
5453
-
5454
-    /**
5455
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5456
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5457
-     *
5458
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5459
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5460
-     * @throws EE_Error
5461
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5462
-     *                                                              indexed)
5463
-     */
5464
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5465
-    {
5466
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5467
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5468
-        } elseif (is_array($model_object_or_attributes_array)) {
5469
-            $attributes_array = $model_object_or_attributes_array;
5470
-        } else {
5471
-            throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5472
-                "event_espresso"), $model_object_or_attributes_array));
5473
-        }
5474
-        //even copies obviously won't have the same ID, so remove the primary key
5475
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5476
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5477
-            unset($attributes_array[$this->primary_key_name()]);
5478
-        }
5479
-        if (isset($query_params[0])) {
5480
-            $query_params[0] = array_merge($attributes_array, $query_params);
5481
-        } else {
5482
-            $query_params[0] = $attributes_array;
5483
-        }
5484
-        return $this->get_all($query_params);
5485
-    }
5486
-
5487
-
5488
-
5489
-    /**
5490
-     * Gets the first copy we find. See get_all_copies for more details
5491
-     *
5492
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5493
-     * @param array $query_params
5494
-     * @return EE_Base_Class
5495
-     * @throws \EE_Error
5496
-     */
5497
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5498
-    {
5499
-        if (! is_array($query_params)) {
5500
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5501
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5502
-                    gettype($query_params)), '4.6.0');
5503
-            $query_params = array();
5504
-        }
5505
-        $query_params['limit'] = 1;
5506
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5507
-        if (is_array($copies)) {
5508
-            return array_shift($copies);
5509
-        } else {
5510
-            return null;
5511
-        }
5512
-    }
5513
-
5514
-
5515
-
5516
-    /**
5517
-     * Updates the item with the specified id. Ignores default query parameters because
5518
-     * we have specified the ID, and its assumed we KNOW what we're doing
5519
-     *
5520
-     * @param array      $fields_n_values keys are field names, values are their new values
5521
-     * @param int|string $id              the value of the primary key to update
5522
-     * @return int number of rows updated
5523
-     * @throws \EE_Error
5524
-     */
5525
-    public function update_by_ID($fields_n_values, $id)
5526
-    {
5527
-        $query_params = array(
5528
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5529
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5530
-        );
5531
-        return $this->update($fields_n_values, $query_params);
5532
-    }
5533
-
5534
-
5535
-
5536
-    /**
5537
-     * Changes an operator which was supplied to the models into one usable in SQL
5538
-     *
5539
-     * @param string $operator_supplied
5540
-     * @return string an operator which can be used in SQL
5541
-     * @throws EE_Error
5542
-     */
5543
-    private function _prepare_operator_for_sql($operator_supplied)
5544
-    {
5545
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5546
-            : null;
5547
-        if ($sql_operator) {
5548
-            return $sql_operator;
5549
-        } else {
5550
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5551
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5552
-        }
5553
-    }
5554
-
5555
-
5556
-
5557
-    /**
5558
-     * Gets the valid operators
5559
-     * @return array keys are accepted strings, values are the SQL they are converted to
5560
-     */
5561
-    public function valid_operators(){
5562
-        return $this->_valid_operators;
5563
-    }
5564
-
5565
-
5566
-
5567
-    /**
5568
-     * Gets the between-style operators (take 2 arguments).
5569
-     * @return array keys are accepted strings, values are the SQL they are converted to
5570
-     */
5571
-    public function valid_between_style_operators()
5572
-    {
5573
-        return array_intersect(
5574
-            $this->valid_operators(),
5575
-            $this->_between_style_operators
5576
-        );
5577
-    }
5578
-
5579
-    /**
5580
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5581
-     * @return array keys are accepted strings, values are the SQL they are converted to
5582
-     */
5583
-    public function valid_like_style_operators()
5584
-    {
5585
-        return array_intersect(
5586
-            $this->valid_operators(),
5587
-            $this->_like_style_operators
5588
-        );
5589
-    }
5590
-
5591
-    /**
5592
-     * Gets the "in"-style operators
5593
-     * @return array keys are accepted strings, values are the SQL they are converted to
5594
-     */
5595
-    public function valid_in_style_operators()
5596
-    {
5597
-        return array_intersect(
5598
-            $this->valid_operators(),
5599
-            $this->_in_style_operators
5600
-        );
5601
-    }
5602
-
5603
-    /**
5604
-     * Gets the "null"-style operators (accept no arguments)
5605
-     * @return array keys are accepted strings, values are the SQL they are converted to
5606
-     */
5607
-    public function valid_null_style_operators()
5608
-    {
5609
-        return array_intersect(
5610
-            $this->valid_operators(),
5611
-            $this->_null_style_operators
5612
-        );
5613
-    }
5614
-
5615
-    /**
5616
-     * Gets an array where keys are the primary keys and values are their 'names'
5617
-     * (as determined by the model object's name() function, which is often overridden)
5618
-     *
5619
-     * @param array $query_params like get_all's
5620
-     * @return string[]
5621
-     * @throws \EE_Error
5622
-     */
5623
-    public function get_all_names($query_params = array())
5624
-    {
5625
-        $objs = $this->get_all($query_params);
5626
-        $names = array();
5627
-        foreach ($objs as $obj) {
5628
-            $names[$obj->ID()] = $obj->name();
5629
-        }
5630
-        return $names;
5631
-    }
5632
-
5633
-
5634
-
5635
-    /**
5636
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5637
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5638
-     * this is duplicated effort and reduces efficiency) you would be better to use
5639
-     * array_keys() on $model_objects.
5640
-     *
5641
-     * @param \EE_Base_Class[] $model_objects
5642
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5643
-     *                                               in the returned array
5644
-     * @return array
5645
-     * @throws \EE_Error
5646
-     */
5647
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5648
-    {
5649
-        if (! $this->has_primary_key_field()) {
5650
-            if (WP_DEBUG) {
5651
-                EE_Error::add_error(
5652
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5653
-                    __FILE__,
5654
-                    __FUNCTION__,
5655
-                    __LINE__
5656
-                );
5657
-            }
5658
-        }
5659
-        $IDs = array();
5660
-        foreach ($model_objects as $model_object) {
5661
-            $id = $model_object->ID();
5662
-            if (! $id) {
5663
-                if ($filter_out_empty_ids) {
5664
-                    continue;
5665
-                }
5666
-                if (WP_DEBUG) {
5667
-                    EE_Error::add_error(
5668
-                        __(
5669
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5670
-                            'event_espresso'
5671
-                        ),
5672
-                        __FILE__,
5673
-                        __FUNCTION__,
5674
-                        __LINE__
5675
-                    );
5676
-                }
5677
-            }
5678
-            $IDs[] = $id;
5679
-        }
5680
-        return $IDs;
5681
-    }
5682
-
5683
-
5684
-
5685
-    /**
5686
-     * Returns the string used in capabilities relating to this model. If there
5687
-     * are no capabilities that relate to this model returns false
5688
-     *
5689
-     * @return string|false
5690
-     */
5691
-    public function cap_slug()
5692
-    {
5693
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5694
-    }
5695
-
5696
-
5697
-
5698
-    /**
5699
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5700
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5701
-     * only returns the cap restrictions array in that context (ie, the array
5702
-     * at that key)
5703
-     *
5704
-     * @param string $context
5705
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5706
-     * @throws \EE_Error
5707
-     */
5708
-    public function cap_restrictions($context = EEM_Base::caps_read)
5709
-    {
5710
-        EEM_Base::verify_is_valid_cap_context($context);
5711
-        //check if we ought to run the restriction generator first
5712
-        if (
5713
-            isset($this->_cap_restriction_generators[$context])
5714
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5715
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5716
-        ) {
5717
-            $this->_cap_restrictions[$context] = array_merge(
5718
-                $this->_cap_restrictions[$context],
5719
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5720
-            );
5721
-        }
5722
-        //and make sure we've finalized the construction of each restriction
5723
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5724
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5725
-                $where_conditions_obj->_finalize_construct($this);
5726
-            }
5727
-        }
5728
-        return $this->_cap_restrictions[$context];
5729
-    }
5730
-
5731
-
5732
-
5733
-    /**
5734
-     * Indicating whether or not this model thinks its a wp core model
5735
-     *
5736
-     * @return boolean
5737
-     */
5738
-    public function is_wp_core_model()
5739
-    {
5740
-        return $this->_wp_core_model;
5741
-    }
5742
-
5743
-
5744
-
5745
-    /**
5746
-     * Gets all the caps that are missing which impose a restriction on
5747
-     * queries made in this context
5748
-     *
5749
-     * @param string $context one of EEM_Base::caps_ constants
5750
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5751
-     * @throws \EE_Error
5752
-     */
5753
-    public function caps_missing($context = EEM_Base::caps_read)
5754
-    {
5755
-        $missing_caps = array();
5756
-        $cap_restrictions = $this->cap_restrictions($context);
5757
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5758
-            if (! EE_Capabilities::instance()
5759
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5760
-            ) {
5761
-                $missing_caps[$cap] = $restriction_if_no_cap;
5762
-            }
5763
-        }
5764
-        return $missing_caps;
5765
-    }
5766
-
5767
-
5768
-
5769
-    /**
5770
-     * Gets the mapping from capability contexts to action strings used in capability names
5771
-     *
5772
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5773
-     * one of 'read', 'edit', or 'delete'
5774
-     */
5775
-    public function cap_contexts_to_cap_action_map()
5776
-    {
5777
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5778
-            $this);
5779
-    }
5780
-
5781
-
5782
-
5783
-    /**
5784
-     * Gets the action string for the specified capability context
5785
-     *
5786
-     * @param string $context
5787
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5788
-     * @throws \EE_Error
5789
-     */
5790
-    public function cap_action_for_context($context)
5791
-    {
5792
-        $mapping = $this->cap_contexts_to_cap_action_map();
5793
-        if (isset($mapping[$context])) {
5794
-            return $mapping[$context];
5795
-        }
5796
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5797
-            return $action;
5798
-        }
5799
-        throw new EE_Error(
5800
-            sprintf(
5801
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5802
-                $context,
5803
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5804
-            )
5805
-        );
5806
-    }
5807
-
5808
-
5809
-
5810
-    /**
5811
-     * Returns all the capability contexts which are valid when querying models
5812
-     *
5813
-     * @return array
5814
-     */
5815
-    public static function valid_cap_contexts()
5816
-    {
5817
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5818
-            self::caps_read,
5819
-            self::caps_read_admin,
5820
-            self::caps_edit,
5821
-            self::caps_delete,
5822
-        ));
5823
-    }
5824
-
5825
-
5826
-
5827
-    /**
5828
-     * Returns all valid options for 'default_where_conditions'
5829
-     *
5830
-     * @return array
5831
-     */
5832
-    public static function valid_default_where_conditions()
5833
-    {
5834
-        return array(
5835
-            EEM_Base::default_where_conditions_all,
5836
-            EEM_Base::default_where_conditions_this_only,
5837
-            EEM_Base::default_where_conditions_others_only,
5838
-            EEM_Base::default_where_conditions_minimum_all,
5839
-            EEM_Base::default_where_conditions_minimum_others,
5840
-            EEM_Base::default_where_conditions_none
5841
-        );
5842
-    }
5843
-
5844
-    // public static function default_where_conditions_full
5845
-    /**
5846
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5847
-     *
5848
-     * @param string $context
5849
-     * @return bool
5850
-     * @throws \EE_Error
5851
-     */
5852
-    static public function verify_is_valid_cap_context($context)
5853
-    {
5854
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5855
-        if (in_array($context, $valid_cap_contexts)) {
5856
-            return true;
5857
-        } else {
5858
-            throw new EE_Error(
5859
-                sprintf(
5860
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5861
-                        'event_espresso'),
5862
-                    $context,
5863
-                    'EEM_Base',
5864
-                    implode(',', $valid_cap_contexts)
5865
-                )
5866
-            );
5867
-        }
5868
-    }
5869
-
5870
-
5871
-
5872
-    /**
5873
-     * Clears all the models field caches. This is only useful when a sub-class
5874
-     * might have added a field or something and these caches might be invalidated
5875
-     */
5876
-    protected function _invalidate_field_caches()
5877
-    {
5878
-        $this->_cache_foreign_key_to_fields = array();
5879
-        $this->_cached_fields = null;
5880
-        $this->_cached_fields_non_db_only = null;
5881
-    }
5882
-
5883
-
5884
-
5885
-    /**
5886
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5887
-     * (eg "and", "or", "not").
5888
-     *
5889
-     * @return array
5890
-     */
5891
-    public function logic_query_param_keys()
5892
-    {
5893
-        return $this->_logic_query_param_keys;
5894
-    }
5895
-
5896
-
5897
-
5898
-    /**
5899
-     * Determines whether or not the where query param array key is for a logic query param.
5900
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5901
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5902
-     *
5903
-     * @param $query_param_key
5904
-     * @return bool
5905
-     */
5906
-    public function is_logic_query_param_key($query_param_key)
5907
-    {
5908
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5909
-            if ($query_param_key === $logic_query_param_key
5910
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5911
-            ) {
5912
-                return true;
5913
-            }
5914
-        }
5915
-        return false;
5916
-    }
3645
+		}
3646
+		return $null_friendly_where_conditions;
3647
+	}
3648
+
3649
+
3650
+
3651
+	/**
3652
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3653
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3654
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3655
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3656
+	 *
3657
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3658
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3659
+	 */
3660
+	private function _get_default_where_conditions($model_relation_path = null)
3661
+	{
3662
+		if ($this->_ignore_where_strategy) {
3663
+			return array();
3664
+		}
3665
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3666
+	}
3667
+
3668
+
3669
+
3670
+	/**
3671
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3672
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3673
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3674
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3675
+	 * Similar to _get_default_where_conditions
3676
+	 *
3677
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3678
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3679
+	 */
3680
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3681
+	{
3682
+		if ($this->_ignore_where_strategy) {
3683
+			return array();
3684
+		}
3685
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3686
+	}
3687
+
3688
+
3689
+
3690
+	/**
3691
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3692
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3693
+	 *
3694
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3695
+	 * @return string
3696
+	 * @throws \EE_Error
3697
+	 */
3698
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3699
+	{
3700
+		$selects = $this->_get_columns_to_select_for_this_model();
3701
+		foreach (
3702
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3703
+			$name_of_other_model_included
3704
+		) {
3705
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3706
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3707
+			foreach ($other_model_selects as $key => $value) {
3708
+				$selects[] = $value;
3709
+			}
3710
+		}
3711
+		return implode(", ", $selects);
3712
+	}
3713
+
3714
+
3715
+
3716
+	/**
3717
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3718
+	 * So that's going to be the columns for all the fields on the model
3719
+	 *
3720
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3721
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3722
+	 */
3723
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3724
+	{
3725
+		$fields = $this->field_settings();
3726
+		$selects = array();
3727
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3728
+			$this->get_this_model_name());
3729
+		foreach ($fields as $field_obj) {
3730
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3731
+						 . $field_obj->get_table_alias()
3732
+						 . "."
3733
+						 . $field_obj->get_table_column()
3734
+						 . " AS '"
3735
+						 . $table_alias_with_model_relation_chain_prefix
3736
+						 . $field_obj->get_table_alias()
3737
+						 . "."
3738
+						 . $field_obj->get_table_column()
3739
+						 . "'";
3740
+		}
3741
+		//make sure we are also getting the PKs of each table
3742
+		$tables = $this->get_tables();
3743
+		if (count($tables) > 1) {
3744
+			foreach ($tables as $table_obj) {
3745
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3746
+									   . $table_obj->get_fully_qualified_pk_column();
3747
+				if (! in_array($qualified_pk_column, $selects)) {
3748
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3749
+				}
3750
+			}
3751
+		}
3752
+		return $selects;
3753
+	}
3754
+
3755
+
3756
+
3757
+	/**
3758
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3759
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3760
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3761
+	 * SQL for joining, and the data types
3762
+	 *
3763
+	 * @param null|string                 $original_query_param
3764
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3765
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3766
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3767
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3768
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3769
+	 *                                                          or 'Registration's
3770
+	 * @param string                      $original_query_param what it originally was (eg
3771
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3772
+	 *                                                          matches $query_param
3773
+	 * @throws EE_Error
3774
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3775
+	 */
3776
+	private function _extract_related_model_info_from_query_param(
3777
+		$query_param,
3778
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3779
+		$query_param_type,
3780
+		$original_query_param = null
3781
+	) {
3782
+		if ($original_query_param === null) {
3783
+			$original_query_param = $query_param;
3784
+		}
3785
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3786
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3787
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3788
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3789
+		//check to see if we have a field on this model
3790
+		$this_model_fields = $this->field_settings(true);
3791
+		if (array_key_exists($query_param, $this_model_fields)) {
3792
+			if ($allow_fields) {
3793
+				return;
3794
+			} else {
3795
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3796
+					"event_espresso"),
3797
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3798
+			}
3799
+		} //check if this is a special logic query param
3800
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3801
+			if ($allow_logic_query_params) {
3802
+				return;
3803
+			} else {
3804
+				throw new EE_Error(
3805
+					sprintf(
3806
+						__('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',
3807
+							'event_espresso'),
3808
+						implode('", "', $this->_logic_query_param_keys),
3809
+						$query_param,
3810
+						get_class($this),
3811
+						'<br />',
3812
+						"\t"
3813
+						. ' $passed_in_query_info = <pre>'
3814
+						. print_r($passed_in_query_info, true)
3815
+						. '</pre>'
3816
+						. "\n\t"
3817
+						. ' $query_param_type = '
3818
+						. $query_param_type
3819
+						. "\n\t"
3820
+						. ' $original_query_param = '
3821
+						. $original_query_param
3822
+					)
3823
+				);
3824
+			}
3825
+		} //check if it's a custom selection
3826
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3827
+			return;
3828
+		}
3829
+		//check if has a model name at the beginning
3830
+		//and
3831
+		//check if it's a field on a related model
3832
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3833
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3834
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3835
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3836
+				if ($query_param === '') {
3837
+					//nothing left to $query_param
3838
+					//we should actually end in a field name, not a model like this!
3839
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3840
+						"event_espresso"),
3841
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3842
+				} else {
3843
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3844
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3845
+						$passed_in_query_info, $query_param_type, $original_query_param);
3846
+					return;
3847
+				}
3848
+			} elseif ($query_param === $valid_related_model_name) {
3849
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3850
+				return;
3851
+			}
3852
+		}
3853
+		//ok so $query_param didn't start with a model name
3854
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3855
+		//it's wack, that's what it is
3856
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3857
+			"event_espresso"),
3858
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3859
+	}
3860
+
3861
+
3862
+
3863
+	/**
3864
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3865
+	 * and store it on $passed_in_query_info
3866
+	 *
3867
+	 * @param string                      $model_name
3868
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3869
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3870
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3871
+	 *                                                          and are adding a join to 'Payment' with the original
3872
+	 *                                                          query param key
3873
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3874
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3875
+	 *                                                          Payment wants to add default query params so that it
3876
+	 *                                                          will know what models to prepend onto its default query
3877
+	 *                                                          params or in case it wants to rename tables (in case
3878
+	 *                                                          there are multiple joins to the same table)
3879
+	 * @return void
3880
+	 * @throws \EE_Error
3881
+	 */
3882
+	private function _add_join_to_model(
3883
+		$model_name,
3884
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3885
+		$original_query_param
3886
+	) {
3887
+		$relation_obj = $this->related_settings_for($model_name);
3888
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3889
+		//check if the relation is HABTM, because then we're essentially doing two joins
3890
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3891
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3892
+			$join_model_obj = $relation_obj->get_join_model();
3893
+			//replace the model specified with the join model for this relation chain, whi
3894
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3895
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3896
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3897
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3898
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3899
+			$passed_in_query_info->merge($new_query_info);
3900
+		}
3901
+		//now just join to the other table pointed to by the relation object, and add its data types
3902
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3903
+			array($model_relation_chain => $model_name),
3904
+			$relation_obj->get_join_statement($model_relation_chain));
3905
+		$passed_in_query_info->merge($new_query_info);
3906
+	}
3907
+
3908
+
3909
+
3910
+	/**
3911
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3912
+	 *
3913
+	 * @param array $where_params like EEM_Base::get_all
3914
+	 * @return string of SQL
3915
+	 * @throws \EE_Error
3916
+	 */
3917
+	private function _construct_where_clause($where_params)
3918
+	{
3919
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3920
+		if ($SQL) {
3921
+			return " WHERE " . $SQL;
3922
+		} else {
3923
+			return '';
3924
+		}
3925
+	}
3926
+
3927
+
3928
+
3929
+	/**
3930
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3931
+	 * and should be passed HAVING parameters, not WHERE parameters
3932
+	 *
3933
+	 * @param array $having_params
3934
+	 * @return string
3935
+	 * @throws \EE_Error
3936
+	 */
3937
+	private function _construct_having_clause($having_params)
3938
+	{
3939
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3940
+		if ($SQL) {
3941
+			return " HAVING " . $SQL;
3942
+		} else {
3943
+			return '';
3944
+		}
3945
+	}
3946
+
3947
+
3948
+	/**
3949
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3950
+	 * Event_Meta.meta_value = 'foo'))"
3951
+	 *
3952
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3953
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3954
+	 * @throws EE_Error
3955
+	 * @return string of SQL
3956
+	 */
3957
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3958
+	{
3959
+		$where_clauses = array();
3960
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3961
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3962
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3963
+				switch ($query_param) {
3964
+					case 'not':
3965
+					case 'NOT':
3966
+						$where_clauses[] = "! ("
3967
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3968
+								$glue)
3969
+										   . ")";
3970
+						break;
3971
+					case 'and':
3972
+					case 'AND':
3973
+						$where_clauses[] = " ("
3974
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3975
+								' AND ')
3976
+										   . ")";
3977
+						break;
3978
+					case 'or':
3979
+					case 'OR':
3980
+						$where_clauses[] = " ("
3981
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3982
+								' OR ')
3983
+										   . ")";
3984
+						break;
3985
+				}
3986
+			} else {
3987
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3988
+				//if it's not a normal field, maybe it's a custom selection?
3989
+				if (! $field_obj) {
3990
+					if (isset($this->_custom_selections[$query_param][1])) {
3991
+						$field_obj = $this->_custom_selections[$query_param][1];
3992
+					} else {
3993
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3994
+							"event_espresso"), $query_param));
3995
+					}
3996
+				}
3997
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3998
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3999
+			}
4000
+		}
4001
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4002
+	}
4003
+
4004
+
4005
+
4006
+	/**
4007
+	 * Takes the input parameter and extract the table name (alias) and column name
4008
+	 *
4009
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4010
+	 * @throws EE_Error
4011
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4012
+	 */
4013
+	private function _deduce_column_name_from_query_param($query_param)
4014
+	{
4015
+		$field = $this->_deduce_field_from_query_param($query_param);
4016
+		if ($field) {
4017
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4018
+				$query_param);
4019
+			return $table_alias_prefix . $field->get_qualified_column();
4020
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4021
+			//maybe it's custom selection item?
4022
+			//if so, just use it as the "column name"
4023
+			return $query_param;
4024
+		} else {
4025
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4026
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4027
+		}
4028
+	}
4029
+
4030
+
4031
+
4032
+	/**
4033
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4034
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4035
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4036
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4037
+	 *
4038
+	 * @param string $condition_query_param_key
4039
+	 * @return string
4040
+	 */
4041
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4042
+	{
4043
+		$pos_of_star = strpos($condition_query_param_key, '*');
4044
+		if ($pos_of_star === false) {
4045
+			return $condition_query_param_key;
4046
+		} else {
4047
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4048
+			return $condition_query_param_sans_star;
4049
+		}
4050
+	}
4051
+
4052
+
4053
+
4054
+	/**
4055
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4056
+	 *
4057
+	 * @param                            mixed      array | string    $op_and_value
4058
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4059
+	 * @throws EE_Error
4060
+	 * @return string
4061
+	 */
4062
+	private function _construct_op_and_value($op_and_value, $field_obj)
4063
+	{
4064
+		if (is_array($op_and_value)) {
4065
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4066
+			if (! $operator) {
4067
+				$php_array_like_string = array();
4068
+				foreach ($op_and_value as $key => $value) {
4069
+					$php_array_like_string[] = "$key=>$value";
4070
+				}
4071
+				throw new EE_Error(
4072
+					sprintf(
4073
+						__(
4074
+							"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))",
4075
+							"event_espresso"
4076
+						),
4077
+						implode(",", $php_array_like_string)
4078
+					)
4079
+				);
4080
+			}
4081
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4082
+		} else {
4083
+			$operator = '=';
4084
+			$value = $op_and_value;
4085
+		}
4086
+		//check to see if the value is actually another field
4087
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4088
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4089
+		} elseif (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4090
+			//in this case, the value should be an array, or at least a comma-separated list
4091
+			//it will need to handle a little differently
4092
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4093
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4094
+			return $operator . SP . $cleaned_value;
4095
+		} elseif (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4096
+			//the value should be an array with count of two.
4097
+			if (count($value) !== 2) {
4098
+				throw new EE_Error(
4099
+					sprintf(
4100
+						__(
4101
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4102
+							'event_espresso'
4103
+						),
4104
+						"BETWEEN"
4105
+					)
4106
+				);
4107
+			}
4108
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4109
+			return $operator . SP . $cleaned_value;
4110
+		} elseif (in_array($operator, $this->valid_null_style_operators())) {
4111
+			if ($value !== null) {
4112
+				throw new EE_Error(
4113
+					sprintf(
4114
+						__(
4115
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4116
+							"event_espresso"
4117
+						),
4118
+						$value,
4119
+						$operator
4120
+					)
4121
+				);
4122
+			}
4123
+			return $operator;
4124
+		} elseif (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4125
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4126
+			//remove other junk. So just treat it as a string.
4127
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4128
+		} elseif (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4129
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4130
+		} elseif (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4131
+			throw new EE_Error(
4132
+				sprintf(
4133
+					__(
4134
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4135
+						'event_espresso'
4136
+					),
4137
+					$operator,
4138
+					$operator
4139
+				)
4140
+			);
4141
+		} elseif (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4142
+			throw new EE_Error(
4143
+				sprintf(
4144
+					__(
4145
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4146
+						'event_espresso'
4147
+					),
4148
+					$operator,
4149
+					$operator
4150
+				)
4151
+			);
4152
+		} else {
4153
+			throw new EE_Error(
4154
+				sprintf(
4155
+					__(
4156
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4157
+						"event_espresso"
4158
+					),
4159
+					http_build_query($op_and_value)
4160
+				)
4161
+			);
4162
+		}
4163
+	}
4164
+
4165
+
4166
+
4167
+	/**
4168
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4169
+	 *
4170
+	 * @param array                      $values
4171
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4172
+	 *                                              '%s'
4173
+	 * @return string
4174
+	 * @throws \EE_Error
4175
+	 */
4176
+	public function _construct_between_value($values, $field_obj)
4177
+	{
4178
+		$cleaned_values = array();
4179
+		foreach ($values as $value) {
4180
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4181
+		}
4182
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4183
+	}
4184
+
4185
+
4186
+
4187
+	/**
4188
+	 * Takes an array or a comma-separated list of $values and cleans them
4189
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4190
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4191
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4192
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4193
+	 *
4194
+	 * @param mixed                      $values    array or comma-separated string
4195
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4196
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4197
+	 * @throws \EE_Error
4198
+	 */
4199
+	public function _construct_in_value($values, $field_obj)
4200
+	{
4201
+		//check if the value is a CSV list
4202
+		if (is_string($values)) {
4203
+			//in which case, turn it into an array
4204
+			$values = explode(",", $values);
4205
+		}
4206
+		$cleaned_values = array();
4207
+		foreach ($values as $value) {
4208
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4209
+		}
4210
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4211
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4212
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4213
+		if (empty($cleaned_values)) {
4214
+			$all_fields = $this->field_settings();
4215
+			$a_field = array_shift($all_fields);
4216
+			$main_table = $this->_get_main_table();
4217
+			$cleaned_values[] = "SELECT "
4218
+								. $a_field->get_table_column()
4219
+								. " FROM "
4220
+								. $main_table->get_table_name()
4221
+								. " WHERE FALSE";
4222
+		}
4223
+		return "(" . implode(",", $cleaned_values) . ")";
4224
+	}
4225
+
4226
+
4227
+
4228
+	/**
4229
+	 * @param mixed                      $value
4230
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4231
+	 * @throws EE_Error
4232
+	 * @return false|null|string
4233
+	 */
4234
+	private function _wpdb_prepare_using_field($value, $field_obj)
4235
+	{
4236
+		/** @type WPDB $wpdb */
4237
+		global $wpdb;
4238
+		if ($field_obj instanceof EE_Model_Field_Base) {
4239
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4240
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4241
+		} else {//$field_obj should really just be a data type
4242
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4243
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4244
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4245
+			}
4246
+			return $wpdb->prepare($field_obj, $value);
4247
+		}
4248
+	}
4249
+
4250
+
4251
+
4252
+	/**
4253
+	 * Takes the input parameter and finds the model field that it indicates.
4254
+	 *
4255
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4256
+	 * @throws EE_Error
4257
+	 * @return EE_Model_Field_Base
4258
+	 */
4259
+	protected function _deduce_field_from_query_param($query_param_name)
4260
+	{
4261
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4262
+		//which will help us find the database table and column
4263
+		$query_param_parts = explode(".", $query_param_name);
4264
+		if (empty($query_param_parts)) {
4265
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4266
+				'event_espresso'), $query_param_name));
4267
+		}
4268
+		$number_of_parts = count($query_param_parts);
4269
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4270
+		if ($number_of_parts === 1) {
4271
+			$field_name = $last_query_param_part;
4272
+			$model_obj = $this;
4273
+		} else {// $number_of_parts >= 2
4274
+			//the last part is the column name, and there are only 2parts. therefore...
4275
+			$field_name = $last_query_param_part;
4276
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4277
+		}
4278
+		try {
4279
+			return $model_obj->field_settings_for($field_name);
4280
+		} catch (EE_Error $e) {
4281
+			return null;
4282
+		}
4283
+	}
4284
+
4285
+
4286
+
4287
+	/**
4288
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4289
+	 * alias and column which corresponds to it
4290
+	 *
4291
+	 * @param string $field_name
4292
+	 * @throws EE_Error
4293
+	 * @return string
4294
+	 */
4295
+	public function _get_qualified_column_for_field($field_name)
4296
+	{
4297
+		$all_fields = $this->field_settings();
4298
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4299
+		if ($field) {
4300
+			return $field->get_qualified_column();
4301
+		} else {
4302
+			throw new EE_Error(sprintf(__("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.",
4303
+				'event_espresso'), $field_name, get_class($this)));
4304
+		}
4305
+	}
4306
+
4307
+
4308
+
4309
+	/**
4310
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4311
+	 * Example usage:
4312
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4313
+	 *      array(),
4314
+	 *      ARRAY_A,
4315
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4316
+	 *  );
4317
+	 * is equivalent to
4318
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4319
+	 * and
4320
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4321
+	 *      array(
4322
+	 *          array(
4323
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4324
+	 *          ),
4325
+	 *          ARRAY_A,
4326
+	 *          implode(
4327
+	 *              ', ',
4328
+	 *              array_merge(
4329
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4330
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4331
+	 *              )
4332
+	 *          )
4333
+	 *      )
4334
+	 *  );
4335
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4336
+	 *
4337
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4338
+	 *                                            and the one whose fields you are selecting for example: when querying
4339
+	 *                                            tickets model and selecting fields from the tickets model you would
4340
+	 *                                            leave this parameter empty, because no models are needed to join
4341
+	 *                                            between the queried model and the selected one. Likewise when
4342
+	 *                                            querying the datetime model and selecting fields from the tickets
4343
+	 *                                            model, it would also be left empty, because there is a direct
4344
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4345
+	 *                                            them together. However, when querying from the event model and
4346
+	 *                                            selecting fields from the ticket model, you should provide the string
4347
+	 *                                            'Datetime', indicating that the event model must first join to the
4348
+	 *                                            datetime model in order to find its relation to ticket model.
4349
+	 *                                            Also, when querying from the venue model and selecting fields from
4350
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4351
+	 *                                            indicating you need to join the venue model to the event model,
4352
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4353
+	 *                                            This string is used to deduce the prefix that gets added onto the
4354
+	 *                                            models' tables qualified columns
4355
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4356
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4357
+	 *                                            qualified column names
4358
+	 * @return array|string
4359
+	 */
4360
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4361
+	{
4362
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4363
+		$qualified_columns = array();
4364
+		foreach ($this->field_settings() as $field_name => $field) {
4365
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4366
+		}
4367
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4368
+	}
4369
+
4370
+
4371
+
4372
+	/**
4373
+	 * constructs the select use on special limit joins
4374
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4375
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4376
+	 * (as that is typically where the limits would be set).
4377
+	 *
4378
+	 * @param  string       $table_alias The table the select is being built for
4379
+	 * @param  mixed|string $limit       The limit for this select
4380
+	 * @return string                The final select join element for the query.
4381
+	 */
4382
+	public function _construct_limit_join_select($table_alias, $limit)
4383
+	{
4384
+		$SQL = '';
4385
+		foreach ($this->_tables as $table_obj) {
4386
+			if ($table_obj instanceof EE_Primary_Table) {
4387
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4388
+					? $table_obj->get_select_join_limit($limit)
4389
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4390
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4391
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4392
+					? $table_obj->get_select_join_limit_join($limit)
4393
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4394
+			}
4395
+		}
4396
+		return $SQL;
4397
+	}
4398
+
4399
+
4400
+
4401
+	/**
4402
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4403
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4404
+	 *
4405
+	 * @return string SQL
4406
+	 * @throws \EE_Error
4407
+	 */
4408
+	public function _construct_internal_join()
4409
+	{
4410
+		$SQL = $this->_get_main_table()->get_table_sql();
4411
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4412
+		return $SQL;
4413
+	}
4414
+
4415
+
4416
+
4417
+	/**
4418
+	 * Constructs the SQL for joining all the tables on this model.
4419
+	 * Normally $alias should be the primary table's alias, but in cases where
4420
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4421
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4422
+	 * alias, this will construct SQL like:
4423
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4424
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4425
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4426
+	 *
4427
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4428
+	 * @return string
4429
+	 */
4430
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4431
+	{
4432
+		$SQL = '';
4433
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4434
+		foreach ($this->_tables as $table_obj) {
4435
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4436
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4437
+					//so we're joining to this table, meaning the table is already in
4438
+					//the FROM statement, BUT the primary table isn't. So we want
4439
+					//to add the inverse join sql
4440
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4441
+				} else {
4442
+					//just add a regular JOIN to this table from the primary table
4443
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4444
+				}
4445
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4446
+		}
4447
+		return $SQL;
4448
+	}
4449
+
4450
+
4451
+
4452
+	/**
4453
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4454
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4455
+	 * their data type (eg, '%s', '%d', etc)
4456
+	 *
4457
+	 * @return array
4458
+	 */
4459
+	public function _get_data_types()
4460
+	{
4461
+		$data_types = array();
4462
+		foreach ($this->field_settings() as $field_obj) {
4463
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4464
+			/** @var $field_obj EE_Model_Field_Base */
4465
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4466
+		}
4467
+		return $data_types;
4468
+	}
4469
+
4470
+
4471
+
4472
+	/**
4473
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4474
+	 *
4475
+	 * @param string $model_name
4476
+	 * @throws EE_Error
4477
+	 * @return EEM_Base
4478
+	 */
4479
+	public function get_related_model_obj($model_name)
4480
+	{
4481
+		$model_classname = "EEM_" . $model_name;
4482
+		if (! class_exists($model_classname)) {
4483
+			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4484
+				'event_espresso'), $model_name, $model_classname));
4485
+		}
4486
+		return call_user_func($model_classname . "::instance");
4487
+	}
4488
+
4489
+
4490
+
4491
+	/**
4492
+	 * Returns the array of EE_ModelRelations for this model.
4493
+	 *
4494
+	 * @return EE_Model_Relation_Base[]
4495
+	 */
4496
+	public function relation_settings()
4497
+	{
4498
+		return $this->_model_relations;
4499
+	}
4500
+
4501
+
4502
+
4503
+	/**
4504
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4505
+	 * because without THOSE models, this model probably doesn't have much purpose.
4506
+	 * (Eg, without an event, datetimes have little purpose.)
4507
+	 *
4508
+	 * @return EE_Belongs_To_Relation[]
4509
+	 */
4510
+	public function belongs_to_relations()
4511
+	{
4512
+		$belongs_to_relations = array();
4513
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4514
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4515
+				$belongs_to_relations[$model_name] = $relation_obj;
4516
+			}
4517
+		}
4518
+		return $belongs_to_relations;
4519
+	}
4520
+
4521
+
4522
+
4523
+	/**
4524
+	 * Returns the specified EE_Model_Relation, or throws an exception
4525
+	 *
4526
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4527
+	 * @throws EE_Error
4528
+	 * @return EE_Model_Relation_Base
4529
+	 */
4530
+	public function related_settings_for($relation_name)
4531
+	{
4532
+		$relatedModels = $this->relation_settings();
4533
+		if (! array_key_exists($relation_name, $relatedModels)) {
4534
+			throw new EE_Error(
4535
+				sprintf(
4536
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4537
+						'event_espresso'),
4538
+					$relation_name,
4539
+					$this->_get_class_name(),
4540
+					implode(', ', array_keys($relatedModels))
4541
+				)
4542
+			);
4543
+		}
4544
+		return $relatedModels[$relation_name];
4545
+	}
4546
+
4547
+
4548
+
4549
+	/**
4550
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4551
+	 * fields
4552
+	 *
4553
+	 * @param string $fieldName
4554
+	 * @param boolean $include_db_only_fields
4555
+	 * @throws EE_Error
4556
+	 * @return EE_Model_Field_Base
4557
+	 */
4558
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4559
+	{
4560
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4561
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4562
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4563
+				get_class($this)));
4564
+		}
4565
+		return $fieldSettings[$fieldName];
4566
+	}
4567
+
4568
+
4569
+
4570
+	/**
4571
+	 * Checks if this field exists on this model
4572
+	 *
4573
+	 * @param string $fieldName a key in the model's _field_settings array
4574
+	 * @return boolean
4575
+	 */
4576
+	public function has_field($fieldName)
4577
+	{
4578
+		$fieldSettings = $this->field_settings(true);
4579
+		if (isset($fieldSettings[$fieldName])) {
4580
+			return true;
4581
+		} else {
4582
+			return false;
4583
+		}
4584
+	}
4585
+
4586
+
4587
+
4588
+	/**
4589
+	 * Returns whether or not this model has a relation to the specified model
4590
+	 *
4591
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4592
+	 * @return boolean
4593
+	 */
4594
+	public function has_relation($relation_name)
4595
+	{
4596
+		$relations = $this->relation_settings();
4597
+		if (isset($relations[$relation_name])) {
4598
+			return true;
4599
+		} else {
4600
+			return false;
4601
+		}
4602
+	}
4603
+
4604
+
4605
+
4606
+	/**
4607
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4608
+	 * Eg, on EE_Answer that would be ANS_ID field object
4609
+	 *
4610
+	 * @param $field_obj
4611
+	 * @return boolean
4612
+	 */
4613
+	public function is_primary_key_field($field_obj)
4614
+	{
4615
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4616
+	}
4617
+
4618
+
4619
+
4620
+	/**
4621
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4622
+	 * Eg, on EE_Answer that would be ANS_ID field object
4623
+	 *
4624
+	 * @return EE_Model_Field_Base
4625
+	 * @throws EE_Error
4626
+	 */
4627
+	public function get_primary_key_field()
4628
+	{
4629
+		if ($this->_primary_key_field === null) {
4630
+			foreach ($this->field_settings(true) as $field_obj) {
4631
+				if ($this->is_primary_key_field($field_obj)) {
4632
+					$this->_primary_key_field = $field_obj;
4633
+					break;
4634
+				}
4635
+			}
4636
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4637
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4638
+					get_class($this)));
4639
+			}
4640
+		}
4641
+		return $this->_primary_key_field;
4642
+	}
4643
+
4644
+
4645
+
4646
+	/**
4647
+	 * Returns whether or not not there is a primary key on this model.
4648
+	 * Internally does some caching.
4649
+	 *
4650
+	 * @return boolean
4651
+	 */
4652
+	public function has_primary_key_field()
4653
+	{
4654
+		if ($this->_has_primary_key_field === null) {
4655
+			try {
4656
+				$this->get_primary_key_field();
4657
+				$this->_has_primary_key_field = true;
4658
+			} catch (EE_Error $e) {
4659
+				$this->_has_primary_key_field = false;
4660
+			}
4661
+		}
4662
+		return $this->_has_primary_key_field;
4663
+	}
4664
+
4665
+
4666
+
4667
+	/**
4668
+	 * Finds the first field of type $field_class_name.
4669
+	 *
4670
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4671
+	 *                                 EE_Foreign_Key_Field, etc
4672
+	 * @return EE_Model_Field_Base or null if none is found
4673
+	 */
4674
+	public function get_a_field_of_type($field_class_name)
4675
+	{
4676
+		foreach ($this->field_settings() as $field) {
4677
+			if ($field instanceof $field_class_name) {
4678
+				return $field;
4679
+			}
4680
+		}
4681
+		return null;
4682
+	}
4683
+
4684
+
4685
+
4686
+	/**
4687
+	 * Gets a foreign key field pointing to model.
4688
+	 *
4689
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4690
+	 * @return EE_Foreign_Key_Field_Base
4691
+	 * @throws EE_Error
4692
+	 */
4693
+	public function get_foreign_key_to($model_name)
4694
+	{
4695
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4696
+			foreach ($this->field_settings() as $field) {
4697
+				if (
4698
+					$field instanceof EE_Foreign_Key_Field_Base
4699
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4700
+				) {
4701
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4702
+					break;
4703
+				}
4704
+			}
4705
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4706
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4707
+					'event_espresso'), $model_name, get_class($this)));
4708
+			}
4709
+		}
4710
+		return $this->_cache_foreign_key_to_fields[$model_name];
4711
+	}
4712
+
4713
+
4714
+
4715
+	/**
4716
+	 * Gets the actual table for the table alias
4717
+	 *
4718
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4719
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4720
+	 *                            Either one works
4721
+	 * @return EE_Table_Base
4722
+	 */
4723
+	public function get_table_for_alias($table_alias)
4724
+	{
4725
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4726
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4727
+	}
4728
+
4729
+
4730
+
4731
+	/**
4732
+	 * Returns a flat array of all field son this model, instead of organizing them
4733
+	 * by table_alias as they are in the constructor.
4734
+	 *
4735
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4736
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4737
+	 */
4738
+	public function field_settings($include_db_only_fields = false)
4739
+	{
4740
+		if ($include_db_only_fields) {
4741
+			if ($this->_cached_fields === null) {
4742
+				$this->_cached_fields = array();
4743
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4744
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4745
+						$this->_cached_fields[$field_name] = $field_obj;
4746
+					}
4747
+				}
4748
+			}
4749
+			return $this->_cached_fields;
4750
+		} else {
4751
+			if ($this->_cached_fields_non_db_only === null) {
4752
+				$this->_cached_fields_non_db_only = array();
4753
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4754
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4755
+						/** @var $field_obj EE_Model_Field_Base */
4756
+						if (! $field_obj->is_db_only_field()) {
4757
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4758
+						}
4759
+					}
4760
+				}
4761
+			}
4762
+			return $this->_cached_fields_non_db_only;
4763
+		}
4764
+	}
4765
+
4766
+
4767
+
4768
+	/**
4769
+	 *        cycle though array of attendees and create objects out of each item
4770
+	 *
4771
+	 * @access        private
4772
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4773
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4774
+	 *                           numerically indexed)
4775
+	 * @throws \EE_Error
4776
+	 */
4777
+	protected function _create_objects($rows = array())
4778
+	{
4779
+		$array_of_objects = array();
4780
+		if (empty($rows)) {
4781
+			return array();
4782
+		}
4783
+		$count_if_model_has_no_primary_key = 0;
4784
+		$has_primary_key = $this->has_primary_key_field();
4785
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4786
+		foreach ((array)$rows as $row) {
4787
+			if (empty($row)) {
4788
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4789
+				return array();
4790
+			}
4791
+			//check if we've already set this object in the results array,
4792
+			//in which case there's no need to process it further (again)
4793
+			if ($has_primary_key) {
4794
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4795
+					$row,
4796
+					$primary_key_field->get_qualified_column(),
4797
+					$primary_key_field->get_table_column()
4798
+				);
4799
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4800
+					continue;
4801
+				}
4802
+			}
4803
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4804
+			if (! $classInstance) {
4805
+				throw new EE_Error(
4806
+					sprintf(
4807
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4808
+						$this->get_this_model_name(),
4809
+						http_build_query($row)
4810
+					)
4811
+				);
4812
+			}
4813
+			//set the timezone on the instantiated objects
4814
+			$classInstance->set_timezone($this->_timezone);
4815
+			//make sure if there is any timezone setting present that we set the timezone for the object
4816
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4817
+			$array_of_objects[$key] = $classInstance;
4818
+			//also, for all the relations of type BelongsTo, see if we can cache
4819
+			//those related models
4820
+			//(we could do this for other relations too, but if there are conditions
4821
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4822
+			//so it requires a little more thought than just caching them immediately...)
4823
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4824
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4825
+					//check if this model's INFO is present. If so, cache it on the model
4826
+					$other_model = $relation_obj->get_other_model();
4827
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4828
+					//if we managed to make a model object from the results, cache it on the main model object
4829
+					if ($other_model_obj_maybe) {
4830
+						//set timezone on these other model objects if they are present
4831
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4832
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4833
+					}
4834
+				}
4835
+			}
4836
+		}
4837
+		return $array_of_objects;
4838
+	}
4839
+
4840
+
4841
+
4842
+	/**
4843
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4844
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4845
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4846
+	 * object (as set in the model_field!).
4847
+	 *
4848
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4849
+	 */
4850
+	public function create_default_object()
4851
+	{
4852
+		$this_model_fields_and_values = array();
4853
+		//setup the row using default values;
4854
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4855
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4856
+		}
4857
+		$className = $this->_get_class_name();
4858
+		$classInstance = EE_Registry::instance()
4859
+									->load_class($className, array($this_model_fields_and_values), false, false);
4860
+		return $classInstance;
4861
+	}
4862
+
4863
+
4864
+
4865
+	/**
4866
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4867
+	 *                             or an stdClass where each property is the name of a column,
4868
+	 * @return EE_Base_Class
4869
+	 * @throws \EE_Error
4870
+	 */
4871
+	public function instantiate_class_from_array_or_object($cols_n_values)
4872
+	{
4873
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4874
+			$cols_n_values = get_object_vars($cols_n_values);
4875
+		}
4876
+		$primary_key = null;
4877
+		//make sure the array only has keys that are fields/columns on this model
4878
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4879
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4880
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4881
+		}
4882
+		$className = $this->_get_class_name();
4883
+		//check we actually found results that we can use to build our model object
4884
+		//if not, return null
4885
+		if ($this->has_primary_key_field()) {
4886
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4887
+				return null;
4888
+			}
4889
+		} else if ($this->unique_indexes()) {
4890
+			$first_column = reset($this_model_fields_n_values);
4891
+			if (empty($first_column)) {
4892
+				return null;
4893
+			}
4894
+		}
4895
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4896
+		if ($primary_key) {
4897
+			$classInstance = $this->get_from_entity_map($primary_key);
4898
+			if (! $classInstance) {
4899
+				$classInstance = EE_Registry::instance()
4900
+											->load_class($className,
4901
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4902
+				// add this new object to the entity map
4903
+				$classInstance = $this->add_to_entity_map($classInstance);
4904
+			}
4905
+		} else {
4906
+			$classInstance = EE_Registry::instance()
4907
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4908
+											true, false);
4909
+		}
4910
+		//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4911
+		$this->set_timezone($classInstance->get_timezone());
4912
+		return $classInstance;
4913
+	}
4914
+
4915
+
4916
+
4917
+	/**
4918
+	 * Gets the model object from the  entity map if it exists
4919
+	 *
4920
+	 * @param int|string $id the ID of the model object
4921
+	 * @return EE_Base_Class
4922
+	 */
4923
+	public function get_from_entity_map($id)
4924
+	{
4925
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4926
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4927
+	}
4928
+
4929
+
4930
+
4931
+	/**
4932
+	 * add_to_entity_map
4933
+	 * Adds the object to the model's entity mappings
4934
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4935
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4936
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4937
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4938
+	 *        then this method should be called immediately after the update query
4939
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4940
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4941
+	 *
4942
+	 * @param    EE_Base_Class $object
4943
+	 * @throws EE_Error
4944
+	 * @return \EE_Base_Class
4945
+	 */
4946
+	public function add_to_entity_map(EE_Base_Class $object)
4947
+	{
4948
+		$className = $this->_get_class_name();
4949
+		if (! $object instanceof $className) {
4950
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4951
+				is_object($object) ? get_class($object) : $object, $className));
4952
+		}
4953
+		/** @var $object EE_Base_Class */
4954
+		if (! $object->ID()) {
4955
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4956
+				"event_espresso"), get_class($this)));
4957
+		}
4958
+		// double check it's not already there
4959
+		$classInstance = $this->get_from_entity_map($object->ID());
4960
+		if ($classInstance) {
4961
+			return $classInstance;
4962
+		} else {
4963
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4964
+			return $object;
4965
+		}
4966
+	}
4967
+
4968
+
4969
+
4970
+	/**
4971
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4972
+	 * if no identifier is provided, then the entire entity map is emptied
4973
+	 *
4974
+	 * @param int|string $id the ID of the model object
4975
+	 * @return boolean
4976
+	 */
4977
+	public function clear_entity_map($id = null)
4978
+	{
4979
+		if (empty($id)) {
4980
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4981
+			return true;
4982
+		}
4983
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4984
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4985
+			return true;
4986
+		}
4987
+		return false;
4988
+	}
4989
+
4990
+
4991
+
4992
+	/**
4993
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4994
+	 * Given an array where keys are column (or column alias) names and values,
4995
+	 * returns an array of their corresponding field names and database values
4996
+	 *
4997
+	 * @param array $cols_n_values
4998
+	 * @return array
4999
+	 */
5000
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5001
+	{
5002
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5003
+	}
5004
+
5005
+
5006
+
5007
+	/**
5008
+	 * _deduce_fields_n_values_from_cols_n_values
5009
+	 * Given an array where keys are column (or column alias) names and values,
5010
+	 * returns an array of their corresponding field names and database values
5011
+	 *
5012
+	 * @param string $cols_n_values
5013
+	 * @return array
5014
+	 */
5015
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5016
+	{
5017
+		$this_model_fields_n_values = array();
5018
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5019
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5020
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5021
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5022
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5023
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5024
+					if (! $field_obj->is_db_only_field()) {
5025
+						//prepare field as if its coming from db
5026
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5027
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5028
+					}
5029
+				}
5030
+			} else {
5031
+				//the table's rows existed. Use their values
5032
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5033
+					if (! $field_obj->is_db_only_field()) {
5034
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5035
+							$cols_n_values, $field_obj->get_qualified_column(),
5036
+							$field_obj->get_table_column()
5037
+						);
5038
+					}
5039
+				}
5040
+			}
5041
+		}
5042
+		return $this_model_fields_n_values;
5043
+	}
5044
+
5045
+
5046
+
5047
+	/**
5048
+	 * @param $cols_n_values
5049
+	 * @param $qualified_column
5050
+	 * @param $regular_column
5051
+	 * @return null
5052
+	 */
5053
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5054
+	{
5055
+		$value = null;
5056
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5057
+		//does the field on the model relate to this column retrieved from the db?
5058
+		//or is it a db-only field? (not relating to the model)
5059
+		if (isset($cols_n_values[$qualified_column])) {
5060
+			$value = $cols_n_values[$qualified_column];
5061
+		} elseif (isset($cols_n_values[$regular_column])) {
5062
+			$value = $cols_n_values[$regular_column];
5063
+		}
5064
+		return $value;
5065
+	}
5066
+
5067
+
5068
+
5069
+	/**
5070
+	 * refresh_entity_map_from_db
5071
+	 * Makes sure the model object in the entity map at $id assumes the values
5072
+	 * of the database (opposite of EE_base_Class::save())
5073
+	 *
5074
+	 * @param int|string $id
5075
+	 * @return EE_Base_Class
5076
+	 * @throws \EE_Error
5077
+	 */
5078
+	public function refresh_entity_map_from_db($id)
5079
+	{
5080
+		$obj_in_map = $this->get_from_entity_map($id);
5081
+		if ($obj_in_map) {
5082
+			$wpdb_results = $this->_get_all_wpdb_results(
5083
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5084
+			);
5085
+			if ($wpdb_results && is_array($wpdb_results)) {
5086
+				$one_row = reset($wpdb_results);
5087
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5088
+					$obj_in_map->set_from_db($field_name, $db_value);
5089
+				}
5090
+				//clear the cache of related model objects
5091
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5092
+					$obj_in_map->clear_cache($relation_name, null, true);
5093
+				}
5094
+			}
5095
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5096
+			return $obj_in_map;
5097
+		} else {
5098
+			return $this->get_one_by_ID($id);
5099
+		}
5100
+	}
5101
+
5102
+
5103
+
5104
+	/**
5105
+	 * refresh_entity_map_with
5106
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5107
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5108
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5109
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5110
+	 *
5111
+	 * @param int|string    $id
5112
+	 * @param EE_Base_Class $replacing_model_obj
5113
+	 * @return \EE_Base_Class
5114
+	 * @throws \EE_Error
5115
+	 */
5116
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5117
+	{
5118
+		$obj_in_map = $this->get_from_entity_map($id);
5119
+		if ($obj_in_map) {
5120
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5121
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5122
+					$obj_in_map->set($field_name, $value);
5123
+				}
5124
+				//make the model object in the entity map's cache match the $replacing_model_obj
5125
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5126
+					$obj_in_map->clear_cache($relation_name, null, true);
5127
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5128
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5129
+					}
5130
+				}
5131
+			}
5132
+			return $obj_in_map;
5133
+		} else {
5134
+			$this->add_to_entity_map($replacing_model_obj);
5135
+			return $replacing_model_obj;
5136
+		}
5137
+	}
5138
+
5139
+
5140
+
5141
+	/**
5142
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5143
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5144
+	 * require_once($this->_getClassName().".class.php");
5145
+	 *
5146
+	 * @return string
5147
+	 */
5148
+	private function _get_class_name()
5149
+	{
5150
+		return "EE_" . $this->get_this_model_name();
5151
+	}
5152
+
5153
+
5154
+
5155
+	/**
5156
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5157
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5158
+	 * it would be 'Events'.
5159
+	 *
5160
+	 * @param int $quantity
5161
+	 * @return string
5162
+	 */
5163
+	public function item_name($quantity = 1)
5164
+	{
5165
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5166
+	}
5167
+
5168
+
5169
+
5170
+	/**
5171
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5172
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5173
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5174
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5175
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5176
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5177
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5178
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5179
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5180
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5181
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5182
+	 *        return $previousReturnValue.$returnString;
5183
+	 * }
5184
+	 * require('EEM_Answer.model.php');
5185
+	 * $answer=EEM_Answer::instance();
5186
+	 * echo $answer->my_callback('monkeys',100);
5187
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5188
+	 *
5189
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5190
+	 * @param array  $args       array of original arguments passed to the function
5191
+	 * @throws EE_Error
5192
+	 * @return mixed whatever the plugin which calls add_filter decides
5193
+	 */
5194
+	public function __call($methodName, $args)
5195
+	{
5196
+		$className = get_class($this);
5197
+		$tagName = "FHEE__{$className}__{$methodName}";
5198
+		if (! has_filter($tagName)) {
5199
+			throw new EE_Error(
5200
+				sprintf(
5201
+					__('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 );',
5202
+						'event_espresso'),
5203
+					$methodName,
5204
+					$className,
5205
+					$tagName,
5206
+					'<br />'
5207
+				)
5208
+			);
5209
+		}
5210
+		return apply_filters($tagName, null, $this, $args);
5211
+	}
5212
+
5213
+
5214
+
5215
+	/**
5216
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5217
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5218
+	 *
5219
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5220
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5221
+	 *                                                       the object's class name
5222
+	 *                                                       or object's ID
5223
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5224
+	 *                                                       exists in the database. If it does not, we add it
5225
+	 * @throws EE_Error
5226
+	 * @return EE_Base_Class
5227
+	 */
5228
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5229
+	{
5230
+		$className = $this->_get_class_name();
5231
+		if ($base_class_obj_or_id instanceof $className) {
5232
+			$model_object = $base_class_obj_or_id;
5233
+		} else {
5234
+			$primary_key_field = $this->get_primary_key_field();
5235
+			if (
5236
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5237
+				&& (
5238
+					is_int($base_class_obj_or_id)
5239
+					|| is_string($base_class_obj_or_id)
5240
+				)
5241
+			) {
5242
+				// assume it's an ID.
5243
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5244
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5245
+			} else if (
5246
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5247
+				&& is_string($base_class_obj_or_id)
5248
+			) {
5249
+				// assume its a string representation of the object
5250
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5251
+			} else {
5252
+				throw new EE_Error(
5253
+					sprintf(
5254
+						__(
5255
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5256
+							'event_espresso'
5257
+						),
5258
+						$base_class_obj_or_id,
5259
+						$this->_get_class_name(),
5260
+						print_r($base_class_obj_or_id, true)
5261
+					)
5262
+				);
5263
+			}
5264
+		}
5265
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5266
+			$model_object->save();
5267
+		}
5268
+		return $model_object;
5269
+	}
5270
+
5271
+
5272
+
5273
+	/**
5274
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5275
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5276
+	 * returns it ID.
5277
+	 *
5278
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5279
+	 * @return int|string depending on the type of this model object's ID
5280
+	 * @throws EE_Error
5281
+	 */
5282
+	public function ensure_is_ID($base_class_obj_or_id)
5283
+	{
5284
+		$className = $this->_get_class_name();
5285
+		if ($base_class_obj_or_id instanceof $className) {
5286
+			/** @var $base_class_obj_or_id EE_Base_Class */
5287
+			$id = $base_class_obj_or_id->ID();
5288
+		} elseif (is_int($base_class_obj_or_id)) {
5289
+			//assume it's an ID
5290
+			$id = $base_class_obj_or_id;
5291
+		} elseif (is_string($base_class_obj_or_id)) {
5292
+			//assume its a string representation of the object
5293
+			$id = $base_class_obj_or_id;
5294
+		} else {
5295
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5296
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5297
+				print_r($base_class_obj_or_id, true)));
5298
+		}
5299
+		return $id;
5300
+	}
5301
+
5302
+
5303
+
5304
+	/**
5305
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5306
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5307
+	 * been sanitized and converted into the appropriate domain.
5308
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5309
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5310
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5311
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5312
+	 * $EVT = EEM_Event::instance(); $old_setting =
5313
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5314
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5315
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5316
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5317
+	 *
5318
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5319
+	 * @return void
5320
+	 */
5321
+	public function assume_values_already_prepared_by_model_object(
5322
+		$values_already_prepared = self::not_prepared_by_model_object
5323
+	) {
5324
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5325
+	}
5326
+
5327
+
5328
+
5329
+	/**
5330
+	 * Read comments for assume_values_already_prepared_by_model_object()
5331
+	 *
5332
+	 * @return int
5333
+	 */
5334
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5335
+	{
5336
+		return $this->_values_already_prepared_by_model_object;
5337
+	}
5338
+
5339
+
5340
+
5341
+	/**
5342
+	 * Gets all the indexes on this model
5343
+	 *
5344
+	 * @return EE_Index[]
5345
+	 */
5346
+	public function indexes()
5347
+	{
5348
+		return $this->_indexes;
5349
+	}
5350
+
5351
+
5352
+
5353
+	/**
5354
+	 * Gets all the Unique Indexes on this model
5355
+	 *
5356
+	 * @return EE_Unique_Index[]
5357
+	 */
5358
+	public function unique_indexes()
5359
+	{
5360
+		$unique_indexes = array();
5361
+		foreach ($this->_indexes as $name => $index) {
5362
+			if ($index instanceof EE_Unique_Index) {
5363
+				$unique_indexes [$name] = $index;
5364
+			}
5365
+		}
5366
+		return $unique_indexes;
5367
+	}
5368
+
5369
+
5370
+
5371
+	/**
5372
+	 * Gets all the fields which, when combined, make the primary key.
5373
+	 * This is usually just an array with 1 element (the primary key), but in cases
5374
+	 * where there is no primary key, it's a combination of fields as defined
5375
+	 * on a primary index
5376
+	 *
5377
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5378
+	 * @throws \EE_Error
5379
+	 */
5380
+	public function get_combined_primary_key_fields()
5381
+	{
5382
+		foreach ($this->indexes() as $index) {
5383
+			if ($index instanceof EE_Primary_Key_Index) {
5384
+				return $index->fields();
5385
+			}
5386
+		}
5387
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5388
+	}
5389
+
5390
+
5391
+
5392
+	/**
5393
+	 * Used to build a primary key string (when the model has no primary key),
5394
+	 * which can be used a unique string to identify this model object.
5395
+	 *
5396
+	 * @param array $cols_n_values keys are field names, values are their values
5397
+	 * @return string
5398
+	 * @throws \EE_Error
5399
+	 */
5400
+	public function get_index_primary_key_string($cols_n_values)
5401
+	{
5402
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5403
+			$this->get_combined_primary_key_fields());
5404
+		return http_build_query($cols_n_values_for_primary_key_index);
5405
+	}
5406
+
5407
+
5408
+
5409
+	/**
5410
+	 * Gets the field values from the primary key string
5411
+	 *
5412
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5413
+	 * @param string $index_primary_key_string
5414
+	 * @return null|array
5415
+	 * @throws \EE_Error
5416
+	 */
5417
+	public function parse_index_primary_key_string($index_primary_key_string)
5418
+	{
5419
+		$key_fields = $this->get_combined_primary_key_fields();
5420
+		//check all of them are in the $id
5421
+		$key_vals_in_combined_pk = array();
5422
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5423
+		foreach ($key_fields as $key_field_name => $field_obj) {
5424
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5425
+				return null;
5426
+			}
5427
+		}
5428
+		return $key_vals_in_combined_pk;
5429
+	}
5430
+
5431
+
5432
+
5433
+	/**
5434
+	 * verifies that an array of key-value pairs for model fields has a key
5435
+	 * for each field comprising the primary key index
5436
+	 *
5437
+	 * @param array $key_vals
5438
+	 * @return boolean
5439
+	 * @throws \EE_Error
5440
+	 */
5441
+	public function has_all_combined_primary_key_fields($key_vals)
5442
+	{
5443
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5444
+		foreach ($keys_it_should_have as $key) {
5445
+			if (! isset($key_vals[$key])) {
5446
+				return false;
5447
+			}
5448
+		}
5449
+		return true;
5450
+	}
5451
+
5452
+
5453
+
5454
+	/**
5455
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5456
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5457
+	 *
5458
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5459
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5460
+	 * @throws EE_Error
5461
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5462
+	 *                                                              indexed)
5463
+	 */
5464
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5465
+	{
5466
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5467
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5468
+		} elseif (is_array($model_object_or_attributes_array)) {
5469
+			$attributes_array = $model_object_or_attributes_array;
5470
+		} else {
5471
+			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5472
+				"event_espresso"), $model_object_or_attributes_array));
5473
+		}
5474
+		//even copies obviously won't have the same ID, so remove the primary key
5475
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5476
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5477
+			unset($attributes_array[$this->primary_key_name()]);
5478
+		}
5479
+		if (isset($query_params[0])) {
5480
+			$query_params[0] = array_merge($attributes_array, $query_params);
5481
+		} else {
5482
+			$query_params[0] = $attributes_array;
5483
+		}
5484
+		return $this->get_all($query_params);
5485
+	}
5486
+
5487
+
5488
+
5489
+	/**
5490
+	 * Gets the first copy we find. See get_all_copies for more details
5491
+	 *
5492
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5493
+	 * @param array $query_params
5494
+	 * @return EE_Base_Class
5495
+	 * @throws \EE_Error
5496
+	 */
5497
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5498
+	{
5499
+		if (! is_array($query_params)) {
5500
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5501
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5502
+					gettype($query_params)), '4.6.0');
5503
+			$query_params = array();
5504
+		}
5505
+		$query_params['limit'] = 1;
5506
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5507
+		if (is_array($copies)) {
5508
+			return array_shift($copies);
5509
+		} else {
5510
+			return null;
5511
+		}
5512
+	}
5513
+
5514
+
5515
+
5516
+	/**
5517
+	 * Updates the item with the specified id. Ignores default query parameters because
5518
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5519
+	 *
5520
+	 * @param array      $fields_n_values keys are field names, values are their new values
5521
+	 * @param int|string $id              the value of the primary key to update
5522
+	 * @return int number of rows updated
5523
+	 * @throws \EE_Error
5524
+	 */
5525
+	public function update_by_ID($fields_n_values, $id)
5526
+	{
5527
+		$query_params = array(
5528
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5529
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5530
+		);
5531
+		return $this->update($fields_n_values, $query_params);
5532
+	}
5533
+
5534
+
5535
+
5536
+	/**
5537
+	 * Changes an operator which was supplied to the models into one usable in SQL
5538
+	 *
5539
+	 * @param string $operator_supplied
5540
+	 * @return string an operator which can be used in SQL
5541
+	 * @throws EE_Error
5542
+	 */
5543
+	private function _prepare_operator_for_sql($operator_supplied)
5544
+	{
5545
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5546
+			: null;
5547
+		if ($sql_operator) {
5548
+			return $sql_operator;
5549
+		} else {
5550
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5551
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5552
+		}
5553
+	}
5554
+
5555
+
5556
+
5557
+	/**
5558
+	 * Gets the valid operators
5559
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5560
+	 */
5561
+	public function valid_operators(){
5562
+		return $this->_valid_operators;
5563
+	}
5564
+
5565
+
5566
+
5567
+	/**
5568
+	 * Gets the between-style operators (take 2 arguments).
5569
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5570
+	 */
5571
+	public function valid_between_style_operators()
5572
+	{
5573
+		return array_intersect(
5574
+			$this->valid_operators(),
5575
+			$this->_between_style_operators
5576
+		);
5577
+	}
5578
+
5579
+	/**
5580
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5581
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5582
+	 */
5583
+	public function valid_like_style_operators()
5584
+	{
5585
+		return array_intersect(
5586
+			$this->valid_operators(),
5587
+			$this->_like_style_operators
5588
+		);
5589
+	}
5590
+
5591
+	/**
5592
+	 * Gets the "in"-style operators
5593
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5594
+	 */
5595
+	public function valid_in_style_operators()
5596
+	{
5597
+		return array_intersect(
5598
+			$this->valid_operators(),
5599
+			$this->_in_style_operators
5600
+		);
5601
+	}
5602
+
5603
+	/**
5604
+	 * Gets the "null"-style operators (accept no arguments)
5605
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5606
+	 */
5607
+	public function valid_null_style_operators()
5608
+	{
5609
+		return array_intersect(
5610
+			$this->valid_operators(),
5611
+			$this->_null_style_operators
5612
+		);
5613
+	}
5614
+
5615
+	/**
5616
+	 * Gets an array where keys are the primary keys and values are their 'names'
5617
+	 * (as determined by the model object's name() function, which is often overridden)
5618
+	 *
5619
+	 * @param array $query_params like get_all's
5620
+	 * @return string[]
5621
+	 * @throws \EE_Error
5622
+	 */
5623
+	public function get_all_names($query_params = array())
5624
+	{
5625
+		$objs = $this->get_all($query_params);
5626
+		$names = array();
5627
+		foreach ($objs as $obj) {
5628
+			$names[$obj->ID()] = $obj->name();
5629
+		}
5630
+		return $names;
5631
+	}
5632
+
5633
+
5634
+
5635
+	/**
5636
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5637
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5638
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5639
+	 * array_keys() on $model_objects.
5640
+	 *
5641
+	 * @param \EE_Base_Class[] $model_objects
5642
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5643
+	 *                                               in the returned array
5644
+	 * @return array
5645
+	 * @throws \EE_Error
5646
+	 */
5647
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5648
+	{
5649
+		if (! $this->has_primary_key_field()) {
5650
+			if (WP_DEBUG) {
5651
+				EE_Error::add_error(
5652
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5653
+					__FILE__,
5654
+					__FUNCTION__,
5655
+					__LINE__
5656
+				);
5657
+			}
5658
+		}
5659
+		$IDs = array();
5660
+		foreach ($model_objects as $model_object) {
5661
+			$id = $model_object->ID();
5662
+			if (! $id) {
5663
+				if ($filter_out_empty_ids) {
5664
+					continue;
5665
+				}
5666
+				if (WP_DEBUG) {
5667
+					EE_Error::add_error(
5668
+						__(
5669
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5670
+							'event_espresso'
5671
+						),
5672
+						__FILE__,
5673
+						__FUNCTION__,
5674
+						__LINE__
5675
+					);
5676
+				}
5677
+			}
5678
+			$IDs[] = $id;
5679
+		}
5680
+		return $IDs;
5681
+	}
5682
+
5683
+
5684
+
5685
+	/**
5686
+	 * Returns the string used in capabilities relating to this model. If there
5687
+	 * are no capabilities that relate to this model returns false
5688
+	 *
5689
+	 * @return string|false
5690
+	 */
5691
+	public function cap_slug()
5692
+	{
5693
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5694
+	}
5695
+
5696
+
5697
+
5698
+	/**
5699
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5700
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5701
+	 * only returns the cap restrictions array in that context (ie, the array
5702
+	 * at that key)
5703
+	 *
5704
+	 * @param string $context
5705
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5706
+	 * @throws \EE_Error
5707
+	 */
5708
+	public function cap_restrictions($context = EEM_Base::caps_read)
5709
+	{
5710
+		EEM_Base::verify_is_valid_cap_context($context);
5711
+		//check if we ought to run the restriction generator first
5712
+		if (
5713
+			isset($this->_cap_restriction_generators[$context])
5714
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5715
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5716
+		) {
5717
+			$this->_cap_restrictions[$context] = array_merge(
5718
+				$this->_cap_restrictions[$context],
5719
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5720
+			);
5721
+		}
5722
+		//and make sure we've finalized the construction of each restriction
5723
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5724
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5725
+				$where_conditions_obj->_finalize_construct($this);
5726
+			}
5727
+		}
5728
+		return $this->_cap_restrictions[$context];
5729
+	}
5730
+
5731
+
5732
+
5733
+	/**
5734
+	 * Indicating whether or not this model thinks its a wp core model
5735
+	 *
5736
+	 * @return boolean
5737
+	 */
5738
+	public function is_wp_core_model()
5739
+	{
5740
+		return $this->_wp_core_model;
5741
+	}
5742
+
5743
+
5744
+
5745
+	/**
5746
+	 * Gets all the caps that are missing which impose a restriction on
5747
+	 * queries made in this context
5748
+	 *
5749
+	 * @param string $context one of EEM_Base::caps_ constants
5750
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5751
+	 * @throws \EE_Error
5752
+	 */
5753
+	public function caps_missing($context = EEM_Base::caps_read)
5754
+	{
5755
+		$missing_caps = array();
5756
+		$cap_restrictions = $this->cap_restrictions($context);
5757
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5758
+			if (! EE_Capabilities::instance()
5759
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5760
+			) {
5761
+				$missing_caps[$cap] = $restriction_if_no_cap;
5762
+			}
5763
+		}
5764
+		return $missing_caps;
5765
+	}
5766
+
5767
+
5768
+
5769
+	/**
5770
+	 * Gets the mapping from capability contexts to action strings used in capability names
5771
+	 *
5772
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5773
+	 * one of 'read', 'edit', or 'delete'
5774
+	 */
5775
+	public function cap_contexts_to_cap_action_map()
5776
+	{
5777
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5778
+			$this);
5779
+	}
5780
+
5781
+
5782
+
5783
+	/**
5784
+	 * Gets the action string for the specified capability context
5785
+	 *
5786
+	 * @param string $context
5787
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5788
+	 * @throws \EE_Error
5789
+	 */
5790
+	public function cap_action_for_context($context)
5791
+	{
5792
+		$mapping = $this->cap_contexts_to_cap_action_map();
5793
+		if (isset($mapping[$context])) {
5794
+			return $mapping[$context];
5795
+		}
5796
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5797
+			return $action;
5798
+		}
5799
+		throw new EE_Error(
5800
+			sprintf(
5801
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5802
+				$context,
5803
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5804
+			)
5805
+		);
5806
+	}
5807
+
5808
+
5809
+
5810
+	/**
5811
+	 * Returns all the capability contexts which are valid when querying models
5812
+	 *
5813
+	 * @return array
5814
+	 */
5815
+	public static function valid_cap_contexts()
5816
+	{
5817
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5818
+			self::caps_read,
5819
+			self::caps_read_admin,
5820
+			self::caps_edit,
5821
+			self::caps_delete,
5822
+		));
5823
+	}
5824
+
5825
+
5826
+
5827
+	/**
5828
+	 * Returns all valid options for 'default_where_conditions'
5829
+	 *
5830
+	 * @return array
5831
+	 */
5832
+	public static function valid_default_where_conditions()
5833
+	{
5834
+		return array(
5835
+			EEM_Base::default_where_conditions_all,
5836
+			EEM_Base::default_where_conditions_this_only,
5837
+			EEM_Base::default_where_conditions_others_only,
5838
+			EEM_Base::default_where_conditions_minimum_all,
5839
+			EEM_Base::default_where_conditions_minimum_others,
5840
+			EEM_Base::default_where_conditions_none
5841
+		);
5842
+	}
5843
+
5844
+	// public static function default_where_conditions_full
5845
+	/**
5846
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5847
+	 *
5848
+	 * @param string $context
5849
+	 * @return bool
5850
+	 * @throws \EE_Error
5851
+	 */
5852
+	static public function verify_is_valid_cap_context($context)
5853
+	{
5854
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5855
+		if (in_array($context, $valid_cap_contexts)) {
5856
+			return true;
5857
+		} else {
5858
+			throw new EE_Error(
5859
+				sprintf(
5860
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5861
+						'event_espresso'),
5862
+					$context,
5863
+					'EEM_Base',
5864
+					implode(',', $valid_cap_contexts)
5865
+				)
5866
+			);
5867
+		}
5868
+	}
5869
+
5870
+
5871
+
5872
+	/**
5873
+	 * Clears all the models field caches. This is only useful when a sub-class
5874
+	 * might have added a field or something and these caches might be invalidated
5875
+	 */
5876
+	protected function _invalidate_field_caches()
5877
+	{
5878
+		$this->_cache_foreign_key_to_fields = array();
5879
+		$this->_cached_fields = null;
5880
+		$this->_cached_fields_non_db_only = null;
5881
+	}
5882
+
5883
+
5884
+
5885
+	/**
5886
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5887
+	 * (eg "and", "or", "not").
5888
+	 *
5889
+	 * @return array
5890
+	 */
5891
+	public function logic_query_param_keys()
5892
+	{
5893
+		return $this->_logic_query_param_keys;
5894
+	}
5895
+
5896
+
5897
+
5898
+	/**
5899
+	 * Determines whether or not the where query param array key is for a logic query param.
5900
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5901
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5902
+	 *
5903
+	 * @param $query_param_key
5904
+	 * @return bool
5905
+	 */
5906
+	public function is_logic_query_param_key($query_param_key)
5907
+	{
5908
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5909
+			if ($query_param_key === $logic_query_param_key
5910
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5911
+			) {
5912
+				return true;
5913
+			}
5914
+		}
5915
+		return false;
5916
+	}
5917 5917
 
5918 5918
 
5919 5919
 
Please login to merge, or discard this patch.
Spacing   +158 added lines, -158 removed lines patch added patch discarded remove patch
@@ -510,8 +510,8 @@  discard block
 block discarded – undo
510 510
     protected function __construct($timezone = null)
511 511
     {
512 512
         // check that the model has not been loaded too soon
513
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
514
-            throw new EE_Error (
513
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
514
+            throw new EE_Error(
515 515
                 sprintf(
516 516
                     __('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.',
517 517
                         'event_espresso'),
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
          *
532 532
          * @var EE_Table_Base[] $_tables
533 533
          */
534
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
534
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
535 535
         foreach ($this->_tables as $table_alias => $table_obj) {
536 536
             /** @var $table_obj EE_Table_Base */
537 537
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -546,10 +546,10 @@  discard block
 block discarded – undo
546 546
          *
547 547
          * @param EE_Model_Field_Base[] $_fields
548 548
          */
549
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
549
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
550 550
         $this->_invalidate_field_caches();
551 551
         foreach ($this->_fields as $table_alias => $fields_for_table) {
552
-            if (! array_key_exists($table_alias, $this->_tables)) {
552
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
553 553
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
554 554
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
555 555
             }
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
          *
578 578
          * @param EE_Model_Relation_Base[] $_model_relations
579 579
          */
580
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
580
+        $this->_model_relations = (array) apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
581 581
             $this->_model_relations);
582 582
         foreach ($this->_model_relations as $model_name => $relation_obj) {
583 583
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -589,12 +589,12 @@  discard block
 block discarded – undo
589 589
         }
590 590
         $this->set_timezone($timezone);
591 591
         //finalize default where condition strategy, or set default
592
-        if (! $this->_default_where_conditions_strategy) {
592
+        if ( ! $this->_default_where_conditions_strategy) {
593 593
             //nothing was set during child constructor, so set default
594 594
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
595 595
         }
596 596
         $this->_default_where_conditions_strategy->_finalize_construct($this);
597
-        if (! $this->_minimum_where_conditions_strategy) {
597
+        if ( ! $this->_minimum_where_conditions_strategy) {
598 598
             //nothing was set during child constructor, so set default
599 599
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
600 600
         }
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
         //initialize the standard cap restriction generators if none were specified by the child constructor
608 608
         if ($this->_cap_restriction_generators !== false) {
609 609
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
610
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
610
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
611 611
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
612 612
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
613 613
                         new EE_Restriction_Generator_Protected(),
@@ -620,10 +620,10 @@  discard block
 block discarded – undo
620 620
         //if there are cap restriction generators, use them to make the default cap restrictions
621 621
         if ($this->_cap_restriction_generators !== false) {
622 622
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
623
-                if (! $generator_object) {
623
+                if ( ! $generator_object) {
624 624
                     continue;
625 625
                 }
626
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
626
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
627 627
                     throw new EE_Error(
628 628
                         sprintf(
629 629
                             __('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.',
@@ -634,12 +634,12 @@  discard block
 block discarded – undo
634 634
                     );
635 635
                 }
636 636
                 $action = $this->cap_action_for_context($context);
637
-                if (! $generator_object->construction_finalized()) {
637
+                if ( ! $generator_object->construction_finalized()) {
638 638
                     $generator_object->_construct_finalize($this, $action);
639 639
                 }
640 640
             }
641 641
         }
642
-        do_action('AHEE__' . get_class($this) . '__construct__end');
642
+        do_action('AHEE__'.get_class($this).'__construct__end');
643 643
     }
644 644
 
645 645
 
@@ -652,7 +652,7 @@  discard block
 block discarded – undo
652 652
      */
653 653
     public static function set_model_query_blog_id($blog_id = 0)
654 654
     {
655
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
655
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
656 656
     }
657 657
 
658 658
 
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
     public static function instance($timezone = null)
683 683
     {
684 684
         // check if instance of Espresso_model already exists
685
-        if (! static::$_instance instanceof static) {
685
+        if ( ! static::$_instance instanceof static) {
686 686
             // instantiate Espresso_model
687 687
             static::$_instance = new static($timezone, self::getLoader());
688 688
         }
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
             foreach ($r->getDefaultProperties() as $property => $value) {
714 714
                 //don't set instance to null like it was originally,
715 715
                 //but it's static anyways, and we're ignoring static properties (for now at least)
716
-                if (! isset($static_properties[$property])) {
716
+                if ( ! isset($static_properties[$property])) {
717 717
                     static::$_instance->{$property} = $value;
718 718
                 }
719 719
             }
@@ -729,7 +729,7 @@  discard block
 block discarded – undo
729 729
 
730 730
     private static function getLoader()
731 731
     {
732
-        if(! self::$loader instanceof Loader) {
732
+        if ( ! self::$loader instanceof Loader) {
733 733
             self::$loader = new Loader();
734 734
         }
735 735
         return self::$loader;
@@ -744,7 +744,7 @@  discard block
 block discarded – undo
744 744
      */
745 745
     public function status_array($translated = false)
746 746
     {
747
-        if (! array_key_exists('Status', $this->_model_relations)) {
747
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
748 748
             return array();
749 749
         }
750 750
         $model_name = $this->get_this_model_name();
@@ -947,17 +947,17 @@  discard block
 block discarded – undo
947 947
     public function wp_user_field_name()
948 948
     {
949 949
         try {
950
-            if (! empty($this->_model_chain_to_wp_user)) {
950
+            if ( ! empty($this->_model_chain_to_wp_user)) {
951 951
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
952 952
                 $last_model_name = end($models_to_follow_to_wp_users);
953 953
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
954
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
954
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
955 955
             } else {
956 956
                 $model_with_fk_to_wp_users = $this;
957 957
                 $model_chain_to_wp_user = '';
958 958
             }
959 959
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
960
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
960
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
961 961
         } catch (EE_Error $e) {
962 962
             return false;
963 963
         }
@@ -1029,12 +1029,12 @@  discard block
 block discarded – undo
1029 1029
         // remember the custom selections, if any, and type cast as array
1030 1030
         // (unless $columns_to_select is an object, then just set as an empty array)
1031 1031
         // Note: (array) 'some string' === array( 'some string' )
1032
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1032
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1033 1033
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1034 1034
         $select_expressions = $columns_to_select !== null
1035 1035
             ? $this->_construct_select_from_input($columns_to_select)
1036 1036
             : $this->_construct_default_select_sql($model_query_info);
1037
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1037
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1038 1038
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1039 1039
     }
1040 1040
 
@@ -1079,7 +1079,7 @@  discard block
 block discarded – undo
1079 1079
         if (is_array($columns_to_select)) {
1080 1080
             $select_sql_array = array();
1081 1081
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1082
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1083 1083
                     throw new EE_Error(
1084 1084
                         sprintf(
1085 1085
                             __(
@@ -1091,7 +1091,7 @@  discard block
 block discarded – undo
1091 1091
                         )
1092 1092
                     );
1093 1093
                 }
1094
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1094
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1095 1095
                     throw new EE_Error(
1096 1096
                         sprintf(
1097 1097
                             __(
@@ -1163,7 +1163,7 @@  discard block
 block discarded – undo
1163 1163
      */
1164 1164
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1165 1165
     {
1166
-        if (! isset($query_params[0])) {
1166
+        if ( ! isset($query_params[0])) {
1167 1167
             $query_params[0] = array();
1168 1168
         }
1169 1169
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1188,7 +1188,7 @@  discard block
 block discarded – undo
1188 1188
      */
1189 1189
     public function get_one($query_params = array())
1190 1190
     {
1191
-        if (! is_array($query_params)) {
1191
+        if ( ! is_array($query_params)) {
1192 1192
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1193 1193
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1194 1194
                     gettype($query_params)), '4.6.0');
@@ -1356,7 +1356,7 @@  discard block
 block discarded – undo
1356 1356
                 return array();
1357 1357
             }
1358 1358
         }
1359
-        if (! is_array($query_params)) {
1359
+        if ( ! is_array($query_params)) {
1360 1360
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1361 1361
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1362 1362
                     gettype($query_params)), '4.6.0');
@@ -1366,7 +1366,7 @@  discard block
 block discarded – undo
1366 1366
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1367 1367
         $query_params['limit'] = $limit;
1368 1368
         //set direction
1369
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1369
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1370 1370
         $query_params['order_by'] = $operand === '>'
1371 1371
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1372 1372
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1445,7 +1445,7 @@  discard block
 block discarded – undo
1445 1445
     {
1446 1446
         $field_settings = $this->field_settings_for($field_name);
1447 1447
         //if not a valid EE_Datetime_Field then throw error
1448
-        if (! $field_settings instanceof EE_Datetime_Field) {
1448
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1449 1449
             throw new EE_Error(sprintf(__('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.',
1450 1450
                 'event_espresso'), $field_name));
1451 1451
         }
@@ -1522,7 +1522,7 @@  discard block
 block discarded – undo
1522 1522
         //load EEH_DTT_Helper
1523 1523
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1524 1524
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1525
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1525
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1526 1526
     }
1527 1527
 
1528 1528
 
@@ -1590,7 +1590,7 @@  discard block
 block discarded – undo
1590 1590
      */
1591 1591
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1592 1592
     {
1593
-        if (! is_array($query_params)) {
1593
+        if ( ! is_array($query_params)) {
1594 1594
             EE_Error::doing_it_wrong('EEM_Base::update',
1595 1595
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1596 1596
                     gettype($query_params)), '4.6.0');
@@ -1612,7 +1612,7 @@  discard block
 block discarded – undo
1612 1612
          * @param EEM_Base $model           the model being queried
1613 1613
          * @param array    $query_params    see EEM_Base::get_all()
1614 1614
          */
1615
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1615
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1616 1616
             $query_params);
1617 1617
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1618 1618
         //to do that, for each table, verify that it's PK isn't null.
@@ -1626,7 +1626,7 @@  discard block
 block discarded – undo
1626 1626
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1627 1627
         foreach ($wpdb_select_results as $wpdb_result) {
1628 1628
             // type cast stdClass as array
1629
-            $wpdb_result = (array)$wpdb_result;
1629
+            $wpdb_result = (array) $wpdb_result;
1630 1630
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1631 1631
             if ($this->has_primary_key_field()) {
1632 1632
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1643,13 +1643,13 @@  discard block
 block discarded – undo
1643 1643
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1644 1644
                     //if there is no private key for this table on the results, it means there's no entry
1645 1645
                     //in this table, right? so insert a row in the current table, using any fields available
1646
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1646
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1647 1647
                            && $wpdb_result[$this_table_pk_column])
1648 1648
                     ) {
1649 1649
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1650 1650
                             $main_table_pk_value);
1651 1651
                         //if we died here, report the error
1652
-                        if (! $success) {
1652
+                        if ( ! $success) {
1653 1653
                             return false;
1654 1654
                         }
1655 1655
                     }
@@ -1680,7 +1680,7 @@  discard block
 block discarded – undo
1680 1680
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1681 1681
                 }
1682 1682
             }
1683
-            if (! $model_objs_affected_ids) {
1683
+            if ( ! $model_objs_affected_ids) {
1684 1684
                 //wait wait wait- if nothing was affected let's stop here
1685 1685
                 return 0;
1686 1686
             }
@@ -1707,7 +1707,7 @@  discard block
 block discarded – undo
1707 1707
                . $model_query_info->get_full_join_sql()
1708 1708
                . " SET "
1709 1709
                . $this->_construct_update_sql($fields_n_values)
1710
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1710
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1711 1711
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1712 1712
         /**
1713 1713
          * Action called after a model update call has been made.
@@ -1718,7 +1718,7 @@  discard block
 block discarded – undo
1718 1718
          * @param int      $rows_affected
1719 1719
          */
1720 1720
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1721
-        return $rows_affected;//how many supposedly got updated
1721
+        return $rows_affected; //how many supposedly got updated
1722 1722
     }
1723 1723
 
1724 1724
 
@@ -1746,7 +1746,7 @@  discard block
 block discarded – undo
1746 1746
         }
1747 1747
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1748 1748
         $select_expressions = $field->get_qualified_column();
1749
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1749
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1750 1750
         return $this->_do_wpdb_query('get_col', array($SQL));
1751 1751
     }
1752 1752
 
@@ -1764,7 +1764,7 @@  discard block
 block discarded – undo
1764 1764
     {
1765 1765
         $query_params['limit'] = 1;
1766 1766
         $col = $this->get_col($query_params, $field_to_select);
1767
-        if (! empty($col)) {
1767
+        if ( ! empty($col)) {
1768 1768
             return reset($col);
1769 1769
         } else {
1770 1770
             return null;
@@ -1796,7 +1796,7 @@  discard block
 block discarded – undo
1796 1796
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1797 1797
             $value_sql = $prepared_value === null ? 'NULL'
1798 1798
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1799
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1799
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1800 1800
         }
1801 1801
         return implode(",", $cols_n_values);
1802 1802
     }
@@ -1932,7 +1932,7 @@  discard block
 block discarded – undo
1932 1932
          * @param int      $rows_deleted
1933 1933
          */
1934 1934
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1935
-        return $rows_deleted;//how many supposedly got deleted
1935
+        return $rows_deleted; //how many supposedly got deleted
1936 1936
     }
1937 1937
 
1938 1938
 
@@ -2017,7 +2017,7 @@  discard block
 block discarded – undo
2017 2017
              * @var EE_Primary_Key_Field_Base[] $other_tables_fk_fields EE_Foreign_Key_Field_Base[] keys are table aliases
2018 2018
              */
2019 2019
             $other_tables_fk_fields = array();
2020
-            foreach($other_tables as $other_table_alias => $other_table_obj){
2020
+            foreach ($other_tables as $other_table_alias => $other_table_obj) {
2021 2021
                 $other_tables_pk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_pk_column());
2022 2022
                 $other_tables_fk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_fk_column());
2023 2023
             }
@@ -2042,7 +2042,7 @@  discard block
 block discarded – undo
2042 2042
                     );
2043 2043
                 }
2044 2044
                 //other tables
2045
-                if (! empty($other_tables)) {
2045
+                if ( ! empty($other_tables)) {
2046 2046
                     foreach ($other_tables as $other_table_alias => $other_table_obj) {
2047 2047
                         $other_table_pk_field = $other_tables_pk_fields[$other_table_alias];
2048 2048
                         $other_table_fk_field = $other_tables_fk_fields[$other_table_alias];
@@ -2076,7 +2076,7 @@  discard block
 block discarded – undo
2076 2076
             foreach ($deletes as $column => $values) {
2077 2077
                 //make sure we have unique $values;
2078 2078
                 $values = array_unique($values);
2079
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2079
+                $query[] = $column.' IN('.implode(",", $values).')';
2080 2080
             }
2081 2081
             return ! empty($query) ? implode(' AND ', $query) : '';
2082 2082
         }
@@ -2093,7 +2093,7 @@  discard block
 block discarded – undo
2093 2093
                                                            . $delete_object[$field_in_combined_primary_key->get_qualified_column()];
2094 2094
                     }
2095 2095
                 }
2096
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $combined_primary_key_row_values) . ")";
2096
+                $ways_to_identify_a_row[] = "(".implode(" AND ", $combined_primary_key_row_values).")";
2097 2097
             }
2098 2098
             return implode(" OR ", $ways_to_identify_a_row);
2099 2099
         } else {
@@ -2112,8 +2112,8 @@  discard block
 block discarded – undo
2112 2112
      */
2113 2113
     public function get_field_by_column($qualified_column_name)
2114 2114
     {
2115
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2116
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2115
+       foreach ($this->field_settings(true) as $field_name => $field_obj) {
2116
+           if ($field_obj->get_qualified_column() === $qualified_column_name) {
2117 2117
                return $field_obj;
2118 2118
            }
2119 2119
        }
@@ -2164,9 +2164,9 @@  discard block
 block discarded – undo
2164 2164
                 $column_to_count = '*';
2165 2165
             }
2166 2166
         }
2167
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2168
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2169
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2167
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2168
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2169
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2170 2170
     }
2171 2171
 
2172 2172
 
@@ -2188,13 +2188,13 @@  discard block
 block discarded – undo
2188 2188
             $field_obj = $this->get_primary_key_field();
2189 2189
         }
2190 2190
         $column_to_count = $field_obj->get_qualified_column();
2191
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2191
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2192 2192
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2193 2193
         $data_type = $field_obj->get_wpdb_data_type();
2194 2194
         if ($data_type === '%d' || $data_type === '%s') {
2195
-            return (float)$return_value;
2195
+            return (float) $return_value;
2196 2196
         } else {//must be %f
2197
-            return (float)$return_value;
2197
+            return (float) $return_value;
2198 2198
         }
2199 2199
     }
2200 2200
 
@@ -2215,13 +2215,13 @@  discard block
 block discarded – undo
2215 2215
         //if we're in maintenance mode level 2, DON'T run any queries
2216 2216
         //because level 2 indicates the database needs updating and
2217 2217
         //is probably out of sync with the code
2218
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2218
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2219 2219
             throw new EE_Error(sprintf(__("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.",
2220 2220
                 "event_espresso")));
2221 2221
         }
2222 2222
         /** @type WPDB $wpdb */
2223 2223
         global $wpdb;
2224
-        if (! method_exists($wpdb, $wpdb_method)) {
2224
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2225 2225
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2226 2226
                 'event_espresso'), $wpdb_method));
2227 2227
         }
@@ -2233,7 +2233,7 @@  discard block
 block discarded – undo
2233 2233
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2234 2234
         if (WP_DEBUG) {
2235 2235
             $wpdb->show_errors($old_show_errors_value);
2236
-            if (! empty($wpdb->last_error)) {
2236
+            if ( ! empty($wpdb->last_error)) {
2237 2237
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2238 2238
             } elseif ($result === false) {
2239 2239
                 throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
@@ -2293,7 +2293,7 @@  discard block
 block discarded – undo
2293 2293
                     return $result;
2294 2294
                     break;
2295 2295
             }
2296
-            if (! empty($error_message)) {
2296
+            if ( ! empty($error_message)) {
2297 2297
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2298 2298
                 trigger_error($error_message);
2299 2299
             }
@@ -2369,11 +2369,11 @@  discard block
 block discarded – undo
2369 2369
      */
2370 2370
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2371 2371
     {
2372
-        return " FROM " . $model_query_info->get_full_join_sql() .
2373
-               $model_query_info->get_where_sql() .
2374
-               $model_query_info->get_group_by_sql() .
2375
-               $model_query_info->get_having_sql() .
2376
-               $model_query_info->get_order_by_sql() .
2372
+        return " FROM ".$model_query_info->get_full_join_sql().
2373
+               $model_query_info->get_where_sql().
2374
+               $model_query_info->get_group_by_sql().
2375
+               $model_query_info->get_having_sql().
2376
+               $model_query_info->get_order_by_sql().
2377 2377
                $model_query_info->get_limit_sql();
2378 2378
     }
2379 2379
 
@@ -2569,12 +2569,12 @@  discard block
 block discarded – undo
2569 2569
         $related_model = $this->get_related_model_obj($model_name);
2570 2570
         //we're just going to use the query params on the related model's normal get_all query,
2571 2571
         //except add a condition to say to match the current mod
2572
-        if (! isset($query_params['default_where_conditions'])) {
2572
+        if ( ! isset($query_params['default_where_conditions'])) {
2573 2573
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2574 2574
         }
2575 2575
         $this_model_name = $this->get_this_model_name();
2576 2576
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2577
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2577
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2578 2578
         return $related_model->count($query_params, $field_to_count, $distinct);
2579 2579
     }
2580 2580
 
@@ -2594,7 +2594,7 @@  discard block
 block discarded – undo
2594 2594
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2595 2595
     {
2596 2596
         $related_model = $this->get_related_model_obj($model_name);
2597
-        if (! is_array($query_params)) {
2597
+        if ( ! is_array($query_params)) {
2598 2598
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2599 2599
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2600 2600
                     gettype($query_params)), '4.6.0');
@@ -2602,12 +2602,12 @@  discard block
 block discarded – undo
2602 2602
         }
2603 2603
         //we're just going to use the query params on the related model's normal get_all query,
2604 2604
         //except add a condition to say to match the current mod
2605
-        if (! isset($query_params['default_where_conditions'])) {
2605
+        if ( ! isset($query_params['default_where_conditions'])) {
2606 2606
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2607 2607
         }
2608 2608
         $this_model_name = $this->get_this_model_name();
2609 2609
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2610
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2610
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2611 2611
         return $related_model->sum($query_params, $field_to_sum);
2612 2612
     }
2613 2613
 
@@ -2661,7 +2661,7 @@  discard block
 block discarded – undo
2661 2661
                 $field_with_model_name = $field;
2662 2662
             }
2663 2663
         }
2664
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2664
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2665 2665
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2666 2666
                 $this->get_this_model_name()));
2667 2667
         }
@@ -2694,7 +2694,7 @@  discard block
 block discarded – undo
2694 2694
          * @param array    $fields_n_values keys are the fields and values are their new values
2695 2695
          * @param EEM_Base $model           the model used
2696 2696
          */
2697
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2697
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2698 2698
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2699 2699
             $main_table = $this->_get_main_table();
2700 2700
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2802,7 +2802,7 @@  discard block
 block discarded – undo
2802 2802
         }
2803 2803
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2804 2804
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2805
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2805
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2806 2806
         }
2807 2807
         //if there is nothing to base this search on, then we shouldn't find anything
2808 2808
         if (empty($query_params)) {
@@ -2889,7 +2889,7 @@  discard block
 block discarded – undo
2889 2889
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2890 2890
             //so add the fk to the main table as a column
2891 2891
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2892
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2892
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2893 2893
         }
2894 2894
         //insert the new entry
2895 2895
         $result = $this->_do_wpdb_query('insert',
@@ -2928,7 +2928,7 @@  discard block
 block discarded – undo
2928 2928
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2929 2929
     {
2930 2930
         //if this field doesn't allow nullable, don't allow it
2931
-        if (! $field_obj->is_nullable()
2931
+        if ( ! $field_obj->is_nullable()
2932 2932
             && (
2933 2933
                 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2934 2934
         ) {
@@ -3091,7 +3091,7 @@  discard block
 block discarded – undo
3091 3091
                     $query_info_carrier,
3092 3092
                     'group_by'
3093 3093
                 );
3094
-            } elseif (! empty ($query_params['group_by'])) {
3094
+            } elseif ( ! empty ($query_params['group_by'])) {
3095 3095
                 $this->_extract_related_model_info_from_query_param(
3096 3096
                     $query_params['group_by'],
3097 3097
                     $query_info_carrier,
@@ -3113,7 +3113,7 @@  discard block
 block discarded – undo
3113 3113
                     $query_info_carrier,
3114 3114
                     'order_by'
3115 3115
                 );
3116
-            } elseif (! empty($query_params['order_by'])) {
3116
+            } elseif ( ! empty($query_params['order_by'])) {
3117 3117
                 $this->_extract_related_model_info_from_query_param(
3118 3118
                     $query_params['order_by'],
3119 3119
                     $query_info_carrier,
@@ -3148,8 +3148,8 @@  discard block
 block discarded – undo
3148 3148
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3149 3149
         $query_param_type
3150 3150
     ) {
3151
-        if (! empty($sub_query_params)) {
3152
-            $sub_query_params = (array)$sub_query_params;
3151
+        if ( ! empty($sub_query_params)) {
3152
+            $sub_query_params = (array) $sub_query_params;
3153 3153
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3154 3154
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3155 3155
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3160,7 +3160,7 @@  discard block
 block discarded – undo
3160 3160
                 //of array('Registration.TXN_ID'=>23)
3161 3161
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3162 3162
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3163
-                    if (! is_array($possibly_array_of_params)) {
3163
+                    if ( ! is_array($possibly_array_of_params)) {
3164 3164
                         throw new EE_Error(sprintf(__("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'))",
3165 3165
                             "event_espresso"),
3166 3166
                             $param, $possibly_array_of_params));
@@ -3176,7 +3176,7 @@  discard block
 block discarded – undo
3176 3176
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3177 3177
                     //indicating that $possible_array_of_params[1] is actually a field name,
3178 3178
                     //from which we should extract query parameters!
3179
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3179
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3180 3180
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3181 3181
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3182 3182
                     }
@@ -3206,8 +3206,8 @@  discard block
 block discarded – undo
3206 3206
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3207 3207
         $query_param_type
3208 3208
     ) {
3209
-        if (! empty($sub_query_params)) {
3210
-            if (! is_array($sub_query_params)) {
3209
+        if ( ! empty($sub_query_params)) {
3210
+            if ( ! is_array($sub_query_params)) {
3211 3211
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3212 3212
                     $sub_query_params));
3213 3213
             }
@@ -3236,7 +3236,7 @@  discard block
 block discarded – undo
3236 3236
      */
3237 3237
     public function _create_model_query_info_carrier($query_params)
3238 3238
     {
3239
-        if (! is_array($query_params)) {
3239
+        if ( ! is_array($query_params)) {
3240 3240
             EE_Error::doing_it_wrong(
3241 3241
                 'EEM_Base::_create_model_query_info_carrier',
3242 3242
                 sprintf(
@@ -3312,7 +3312,7 @@  discard block
 block discarded – undo
3312 3312
         //set limit
3313 3313
         if (array_key_exists('limit', $query_params)) {
3314 3314
             if (is_array($query_params['limit'])) {
3315
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3315
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3316 3316
                     $e = sprintf(
3317 3317
                         __(
3318 3318
                             "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)",
@@ -3320,12 +3320,12 @@  discard block
 block discarded – undo
3320 3320
                         ),
3321 3321
                         http_build_query($query_params['limit'])
3322 3322
                     );
3323
-                    throw new EE_Error($e . "|" . $e);
3323
+                    throw new EE_Error($e."|".$e);
3324 3324
                 }
3325 3325
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3326
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3327
-            } elseif (! empty ($query_params['limit'])) {
3328
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3326
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3327
+            } elseif ( ! empty ($query_params['limit'])) {
3328
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3329 3329
             }
3330 3330
         }
3331 3331
         //set order by
@@ -3357,10 +3357,10 @@  discard block
 block discarded – undo
3357 3357
                 $order_array = array();
3358 3358
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3359 3359
                     $order = $this->_extract_order($order);
3360
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3360
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3361 3361
                 }
3362
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3363
-            } elseif (! empty ($query_params['order_by'])) {
3362
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3363
+            } elseif ( ! empty ($query_params['order_by'])) {
3364 3364
                 $this->_extract_related_model_info_from_query_param(
3365 3365
                     $query_params['order_by'],
3366 3366
                     $query_object,
@@ -3371,18 +3371,18 @@  discard block
 block discarded – undo
3371 3371
                     ? $this->_extract_order($query_params['order'])
3372 3372
                     : 'DESC';
3373 3373
                 $query_object->set_order_by_sql(
3374
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3374
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3375 3375
                 );
3376 3376
             }
3377 3377
         }
3378 3378
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3379
-        if (! array_key_exists('order_by', $query_params)
3379
+        if ( ! array_key_exists('order_by', $query_params)
3380 3380
             && array_key_exists('order', $query_params)
3381 3381
             && ! empty($query_params['order'])
3382 3382
         ) {
3383 3383
             $pk_field = $this->get_primary_key_field();
3384 3384
             $order = $this->_extract_order($query_params['order']);
3385
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3385
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3386 3386
         }
3387 3387
         //set group by
3388 3388
         if (array_key_exists('group_by', $query_params)) {
@@ -3392,10 +3392,10 @@  discard block
 block discarded – undo
3392 3392
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3393 3393
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3394 3394
                 }
3395
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3396
-            } elseif (! empty ($query_params['group_by'])) {
3395
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3396
+            } elseif ( ! empty ($query_params['group_by'])) {
3397 3397
                 $query_object->set_group_by_sql(
3398
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3398
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3399 3399
                 );
3400 3400
             }
3401 3401
         }
@@ -3405,7 +3405,7 @@  discard block
 block discarded – undo
3405 3405
         }
3406 3406
         //now, just verify they didn't pass anything wack
3407 3407
         foreach ($query_params as $query_key => $query_value) {
3408
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3408
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3409 3409
                 throw new EE_Error(
3410 3410
                     sprintf(
3411 3411
                         __(
@@ -3499,22 +3499,22 @@  discard block
 block discarded – undo
3499 3499
         $where_query_params = array()
3500 3500
     ) {
3501 3501
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3502
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3502
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3503 3503
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3504 3504
                 "event_espresso"), $use_default_where_conditions,
3505 3505
                 implode(", ", $allowed_used_default_where_conditions_values)));
3506 3506
         }
3507 3507
         $universal_query_params = array();
3508
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3508
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3509 3509
             $universal_query_params = $this->_get_default_where_conditions();
3510
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3510
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3511 3511
             $universal_query_params = $this->_get_minimum_where_conditions();
3512 3512
         }
3513 3513
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3514 3514
             $related_model = $this->get_related_model_obj($model_name);
3515
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3515
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3516 3516
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3517
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3517
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3518 3518
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3519 3519
             } else {
3520 3520
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3547,7 +3547,7 @@  discard block
 block discarded – undo
3547 3547
      * @param bool $for_this_model false means this is for OTHER related models
3548 3548
      * @return bool
3549 3549
      */
3550
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3550
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3551 3551
     {
3552 3552
         return (
3553 3553
                    $for_this_model
@@ -3626,7 +3626,7 @@  discard block
 block discarded – undo
3626 3626
     ) {
3627 3627
         $null_friendly_where_conditions = array();
3628 3628
         $none_overridden = true;
3629
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3629
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3630 3630
         foreach ($default_where_conditions as $key => $val) {
3631 3631
             if (isset($provided_where_conditions[$key])) {
3632 3632
                 $none_overridden = false;
@@ -3744,7 +3744,7 @@  discard block
 block discarded – undo
3744 3744
             foreach ($tables as $table_obj) {
3745 3745
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3746 3746
                                        . $table_obj->get_fully_qualified_pk_column();
3747
-                if (! in_array($qualified_pk_column, $selects)) {
3747
+                if ( ! in_array($qualified_pk_column, $selects)) {
3748 3748
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3749 3749
                 }
3750 3750
             }
@@ -3830,9 +3830,9 @@  discard block
 block discarded – undo
3830 3830
         //and
3831 3831
         //check if it's a field on a related model
3832 3832
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3833
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3833
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3834 3834
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3835
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3835
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3836 3836
                 if ($query_param === '') {
3837 3837
                     //nothing left to $query_param
3838 3838
                     //we should actually end in a field name, not a model like this!
@@ -3918,7 +3918,7 @@  discard block
 block discarded – undo
3918 3918
     {
3919 3919
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3920 3920
         if ($SQL) {
3921
-            return " WHERE " . $SQL;
3921
+            return " WHERE ".$SQL;
3922 3922
         } else {
3923 3923
             return '';
3924 3924
         }
@@ -3938,7 +3938,7 @@  discard block
 block discarded – undo
3938 3938
     {
3939 3939
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3940 3940
         if ($SQL) {
3941
-            return " HAVING " . $SQL;
3941
+            return " HAVING ".$SQL;
3942 3942
         } else {
3943 3943
             return '';
3944 3944
         }
@@ -3958,7 +3958,7 @@  discard block
 block discarded – undo
3958 3958
     {
3959 3959
         $where_clauses = array();
3960 3960
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3961
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3961
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
3962 3962
             if (in_array($query_param, $this->_logic_query_param_keys)) {
3963 3963
                 switch ($query_param) {
3964 3964
                     case 'not':
@@ -3986,7 +3986,7 @@  discard block
 block discarded – undo
3986 3986
             } else {
3987 3987
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
3988 3988
                 //if it's not a normal field, maybe it's a custom selection?
3989
-                if (! $field_obj) {
3989
+                if ( ! $field_obj) {
3990 3990
                     if (isset($this->_custom_selections[$query_param][1])) {
3991 3991
                         $field_obj = $this->_custom_selections[$query_param][1];
3992 3992
                     } else {
@@ -3995,7 +3995,7 @@  discard block
 block discarded – undo
3995 3995
                     }
3996 3996
                 }
3997 3997
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3998
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3998
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
3999 3999
             }
4000 4000
         }
4001 4001
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4016,7 +4016,7 @@  discard block
 block discarded – undo
4016 4016
         if ($field) {
4017 4017
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4018 4018
                 $query_param);
4019
-            return $table_alias_prefix . $field->get_qualified_column();
4019
+            return $table_alias_prefix.$field->get_qualified_column();
4020 4020
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4021 4021
             //maybe it's custom selection item?
4022 4022
             //if so, just use it as the "column name"
@@ -4063,7 +4063,7 @@  discard block
 block discarded – undo
4063 4063
     {
4064 4064
         if (is_array($op_and_value)) {
4065 4065
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4066
-            if (! $operator) {
4066
+            if ( ! $operator) {
4067 4067
                 $php_array_like_string = array();
4068 4068
                 foreach ($op_and_value as $key => $value) {
4069 4069
                     $php_array_like_string[] = "$key=>$value";
@@ -4085,13 +4085,13 @@  discard block
 block discarded – undo
4085 4085
         }
4086 4086
         //check to see if the value is actually another field
4087 4087
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4088
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4088
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4089 4089
         } elseif (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4090 4090
             //in this case, the value should be an array, or at least a comma-separated list
4091 4091
             //it will need to handle a little differently
4092 4092
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4093 4093
             //note: $cleaned_value has already been run through $wpdb->prepare()
4094
-            return $operator . SP . $cleaned_value;
4094
+            return $operator.SP.$cleaned_value;
4095 4095
         } elseif (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4096 4096
             //the value should be an array with count of two.
4097 4097
             if (count($value) !== 2) {
@@ -4106,7 +4106,7 @@  discard block
 block discarded – undo
4106 4106
                 );
4107 4107
             }
4108 4108
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4109
-            return $operator . SP . $cleaned_value;
4109
+            return $operator.SP.$cleaned_value;
4110 4110
         } elseif (in_array($operator, $this->valid_null_style_operators())) {
4111 4111
             if ($value !== null) {
4112 4112
                 throw new EE_Error(
@@ -4124,9 +4124,9 @@  discard block
 block discarded – undo
4124 4124
         } elseif (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4125 4125
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4126 4126
             //remove other junk. So just treat it as a string.
4127
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4128
-        } elseif (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4129
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4127
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4128
+        } elseif ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4129
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4130 4130
         } elseif (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4131 4131
             throw new EE_Error(
4132 4132
                 sprintf(
@@ -4138,7 +4138,7 @@  discard block
 block discarded – undo
4138 4138
                     $operator
4139 4139
                 )
4140 4140
             );
4141
-        } elseif (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4141
+        } elseif ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4142 4142
             throw new EE_Error(
4143 4143
                 sprintf(
4144 4144
                     __(
@@ -4179,7 +4179,7 @@  discard block
 block discarded – undo
4179 4179
         foreach ($values as $value) {
4180 4180
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4181 4181
         }
4182
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4182
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4183 4183
     }
4184 4184
 
4185 4185
 
@@ -4220,7 +4220,7 @@  discard block
 block discarded – undo
4220 4220
                                 . $main_table->get_table_name()
4221 4221
                                 . " WHERE FALSE";
4222 4222
         }
4223
-        return "(" . implode(",", $cleaned_values) . ")";
4223
+        return "(".implode(",", $cleaned_values).")";
4224 4224
     }
4225 4225
 
4226 4226
 
@@ -4239,7 +4239,7 @@  discard block
 block discarded – undo
4239 4239
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4240 4240
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4241 4241
         } else {//$field_obj should really just be a data type
4242
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4242
+            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4243 4243
                 throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4244 4244
                     $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4245 4245
             }
@@ -4359,10 +4359,10 @@  discard block
 block discarded – undo
4359 4359
      */
4360 4360
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4361 4361
     {
4362
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4362
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4363 4363
         $qualified_columns = array();
4364 4364
         foreach ($this->field_settings() as $field_name => $field) {
4365
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4365
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4366 4366
         }
4367 4367
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4368 4368
     }
@@ -4386,11 +4386,11 @@  discard block
 block discarded – undo
4386 4386
             if ($table_obj instanceof EE_Primary_Table) {
4387 4387
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4388 4388
                     ? $table_obj->get_select_join_limit($limit)
4389
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4389
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4390 4390
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4391 4391
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4392 4392
                     ? $table_obj->get_select_join_limit_join($limit)
4393
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4393
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4394 4394
             }
4395 4395
         }
4396 4396
         return $SQL;
@@ -4478,12 +4478,12 @@  discard block
 block discarded – undo
4478 4478
      */
4479 4479
     public function get_related_model_obj($model_name)
4480 4480
     {
4481
-        $model_classname = "EEM_" . $model_name;
4482
-        if (! class_exists($model_classname)) {
4481
+        $model_classname = "EEM_".$model_name;
4482
+        if ( ! class_exists($model_classname)) {
4483 4483
             throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4484 4484
                 'event_espresso'), $model_name, $model_classname));
4485 4485
         }
4486
-        return call_user_func($model_classname . "::instance");
4486
+        return call_user_func($model_classname."::instance");
4487 4487
     }
4488 4488
 
4489 4489
 
@@ -4530,7 +4530,7 @@  discard block
 block discarded – undo
4530 4530
     public function related_settings_for($relation_name)
4531 4531
     {
4532 4532
         $relatedModels = $this->relation_settings();
4533
-        if (! array_key_exists($relation_name, $relatedModels)) {
4533
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4534 4534
             throw new EE_Error(
4535 4535
                 sprintf(
4536 4536
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4558,7 +4558,7 @@  discard block
 block discarded – undo
4558 4558
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4559 4559
     {
4560 4560
         $fieldSettings = $this->field_settings($include_db_only_fields);
4561
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4561
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4562 4562
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4563 4563
                 get_class($this)));
4564 4564
         }
@@ -4633,7 +4633,7 @@  discard block
 block discarded – undo
4633 4633
                     break;
4634 4634
                 }
4635 4635
             }
4636
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4636
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4637 4637
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4638 4638
                     get_class($this)));
4639 4639
             }
@@ -4692,7 +4692,7 @@  discard block
 block discarded – undo
4692 4692
      */
4693 4693
     public function get_foreign_key_to($model_name)
4694 4694
     {
4695
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4695
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4696 4696
             foreach ($this->field_settings() as $field) {
4697 4697
                 if (
4698 4698
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4702,7 +4702,7 @@  discard block
 block discarded – undo
4702 4702
                     break;
4703 4703
                 }
4704 4704
             }
4705
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4705
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4706 4706
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4707 4707
                     'event_espresso'), $model_name, get_class($this)));
4708 4708
             }
@@ -4753,7 +4753,7 @@  discard block
 block discarded – undo
4753 4753
                 foreach ($this->_fields as $fields_corresponding_to_table) {
4754 4754
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4755 4755
                         /** @var $field_obj EE_Model_Field_Base */
4756
-                        if (! $field_obj->is_db_only_field()) {
4756
+                        if ( ! $field_obj->is_db_only_field()) {
4757 4757
                             $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4758 4758
                         }
4759 4759
                     }
@@ -4783,7 +4783,7 @@  discard block
 block discarded – undo
4783 4783
         $count_if_model_has_no_primary_key = 0;
4784 4784
         $has_primary_key = $this->has_primary_key_field();
4785 4785
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4786
-        foreach ((array)$rows as $row) {
4786
+        foreach ((array) $rows as $row) {
4787 4787
             if (empty($row)) {
4788 4788
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4789 4789
                 return array();
@@ -4801,7 +4801,7 @@  discard block
 block discarded – undo
4801 4801
                 }
4802 4802
             }
4803 4803
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4804
-            if (! $classInstance) {
4804
+            if ( ! $classInstance) {
4805 4805
                 throw new EE_Error(
4806 4806
                     sprintf(
4807 4807
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4870,7 +4870,7 @@  discard block
 block discarded – undo
4870 4870
      */
4871 4871
     public function instantiate_class_from_array_or_object($cols_n_values)
4872 4872
     {
4873
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4873
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4874 4874
             $cols_n_values = get_object_vars($cols_n_values);
4875 4875
         }
4876 4876
         $primary_key = null;
@@ -4895,7 +4895,7 @@  discard block
 block discarded – undo
4895 4895
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4896 4896
         if ($primary_key) {
4897 4897
             $classInstance = $this->get_from_entity_map($primary_key);
4898
-            if (! $classInstance) {
4898
+            if ( ! $classInstance) {
4899 4899
                 $classInstance = EE_Registry::instance()
4900 4900
                                             ->load_class($className,
4901 4901
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -4946,12 +4946,12 @@  discard block
 block discarded – undo
4946 4946
     public function add_to_entity_map(EE_Base_Class $object)
4947 4947
     {
4948 4948
         $className = $this->_get_class_name();
4949
-        if (! $object instanceof $className) {
4949
+        if ( ! $object instanceof $className) {
4950 4950
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4951 4951
                 is_object($object) ? get_class($object) : $object, $className));
4952 4952
         }
4953 4953
         /** @var $object EE_Base_Class */
4954
-        if (! $object->ID()) {
4954
+        if ( ! $object->ID()) {
4955 4955
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4956 4956
                 "event_espresso"), get_class($this)));
4957 4957
         }
@@ -5021,7 +5021,7 @@  discard block
 block discarded – undo
5021 5021
             //there is a primary key on this table and its not set. Use defaults for all its columns
5022 5022
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5023 5023
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5024
-                    if (! $field_obj->is_db_only_field()) {
5024
+                    if ( ! $field_obj->is_db_only_field()) {
5025 5025
                         //prepare field as if its coming from db
5026 5026
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5027 5027
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5030,7 +5030,7 @@  discard block
 block discarded – undo
5030 5030
             } else {
5031 5031
                 //the table's rows existed. Use their values
5032 5032
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5033
-                    if (! $field_obj->is_db_only_field()) {
5033
+                    if ( ! $field_obj->is_db_only_field()) {
5034 5034
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5035 5035
                             $cols_n_values, $field_obj->get_qualified_column(),
5036 5036
                             $field_obj->get_table_column()
@@ -5147,7 +5147,7 @@  discard block
 block discarded – undo
5147 5147
      */
5148 5148
     private function _get_class_name()
5149 5149
     {
5150
-        return "EE_" . $this->get_this_model_name();
5150
+        return "EE_".$this->get_this_model_name();
5151 5151
     }
5152 5152
 
5153 5153
 
@@ -5162,7 +5162,7 @@  discard block
 block discarded – undo
5162 5162
      */
5163 5163
     public function item_name($quantity = 1)
5164 5164
     {
5165
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5165
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5166 5166
     }
5167 5167
 
5168 5168
 
@@ -5195,7 +5195,7 @@  discard block
 block discarded – undo
5195 5195
     {
5196 5196
         $className = get_class($this);
5197 5197
         $tagName = "FHEE__{$className}__{$methodName}";
5198
-        if (! has_filter($tagName)) {
5198
+        if ( ! has_filter($tagName)) {
5199 5199
             throw new EE_Error(
5200 5200
                 sprintf(
5201 5201
                     __('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 );',
@@ -5421,7 +5421,7 @@  discard block
 block discarded – undo
5421 5421
         $key_vals_in_combined_pk = array();
5422 5422
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5423 5423
         foreach ($key_fields as $key_field_name => $field_obj) {
5424
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5424
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5425 5425
                 return null;
5426 5426
             }
5427 5427
         }
@@ -5442,7 +5442,7 @@  discard block
 block discarded – undo
5442 5442
     {
5443 5443
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5444 5444
         foreach ($keys_it_should_have as $key) {
5445
-            if (! isset($key_vals[$key])) {
5445
+            if ( ! isset($key_vals[$key])) {
5446 5446
                 return false;
5447 5447
             }
5448 5448
         }
@@ -5496,7 +5496,7 @@  discard block
 block discarded – undo
5496 5496
      */
5497 5497
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5498 5498
     {
5499
-        if (! is_array($query_params)) {
5499
+        if ( ! is_array($query_params)) {
5500 5500
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5501 5501
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5502 5502
                     gettype($query_params)), '4.6.0');
@@ -5558,7 +5558,7 @@  discard block
 block discarded – undo
5558 5558
      * Gets the valid operators
5559 5559
      * @return array keys are accepted strings, values are the SQL they are converted to
5560 5560
      */
5561
-    public function valid_operators(){
5561
+    public function valid_operators() {
5562 5562
         return $this->_valid_operators;
5563 5563
     }
5564 5564
 
@@ -5646,7 +5646,7 @@  discard block
 block discarded – undo
5646 5646
      */
5647 5647
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5648 5648
     {
5649
-        if (! $this->has_primary_key_field()) {
5649
+        if ( ! $this->has_primary_key_field()) {
5650 5650
             if (WP_DEBUG) {
5651 5651
                 EE_Error::add_error(
5652 5652
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5659,7 +5659,7 @@  discard block
 block discarded – undo
5659 5659
         $IDs = array();
5660 5660
         foreach ($model_objects as $model_object) {
5661 5661
             $id = $model_object->ID();
5662
-            if (! $id) {
5662
+            if ( ! $id) {
5663 5663
                 if ($filter_out_empty_ids) {
5664 5664
                     continue;
5665 5665
                 }
@@ -5755,8 +5755,8 @@  discard block
 block discarded – undo
5755 5755
         $missing_caps = array();
5756 5756
         $cap_restrictions = $this->cap_restrictions($context);
5757 5757
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5758
-            if (! EE_Capabilities::instance()
5759
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5758
+            if ( ! EE_Capabilities::instance()
5759
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5760 5760
             ) {
5761 5761
                 $missing_caps[$cap] = $restriction_if_no_cap;
5762 5762
             }
@@ -5907,7 +5907,7 @@  discard block
 block discarded – undo
5907 5907
     {
5908 5908
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5909 5909
             if ($query_param_key === $logic_query_param_key
5910
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5910
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
5911 5911
             ) {
5912 5912
                 return true;
5913 5913
             }
Please login to merge, or discard this patch.