Completed
Branch FET-9856-direct-instantiation (142681)
by
unknown
108:29 queued 96:36
created
core/EE_System.core.php 1 patch
Indentation   +1501 added lines, -1501 removed lines patch added patch discarded remove patch
@@ -7,7 +7,7 @@  discard block
 block discarded – undo
7 7
 
8 8
 
9 9
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
10
-    exit('No direct script access allowed');
10
+	exit('No direct script access allowed');
11 11
 }
12 12
 
13 13
 
@@ -24,1506 +24,1506 @@  discard block
 block discarded – undo
24 24
 {
25 25
 
26 26
 
27
-    /**
28
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
29
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
30
-     */
31
-    const req_type_normal = 0;
32
-
33
-    /**
34
-     * Indicates this is a brand new installation of EE so we should install
35
-     * tables and default data etc
36
-     */
37
-    const req_type_new_activation = 1;
38
-
39
-    /**
40
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
41
-     * and we just exited maintenance mode). We MUST check the database is setup properly
42
-     * and that default data is setup too
43
-     */
44
-    const req_type_reactivation = 2;
45
-
46
-    /**
47
-     * indicates that EE has been upgraded since its previous request.
48
-     * We may have data migration scripts to call and will want to trigger maintenance mode
49
-     */
50
-    const req_type_upgrade = 3;
51
-
52
-    /**
53
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
54
-     */
55
-    const req_type_downgrade = 4;
56
-
57
-    /**
58
-     * @deprecated since version 4.6.0.dev.006
59
-     * Now whenever a new_activation is detected the request type is still just
60
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
61
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
62
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
63
-     * (Specifically, when the migration manager indicates migrations are finished
64
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
65
-     */
66
-    const req_type_activation_but_not_installed = 5;
67
-
68
-    /**
69
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
70
-     */
71
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
72
-
73
-
74
-    /**
75
-     * @var EE_System $_instance
76
-     */
77
-    private static $_instance;
78
-
79
-    /**
80
-     * @var EE_Registry $registry
81
-     */
82
-    protected $registry;
83
-
84
-    /**
85
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
86
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
87
-     *
88
-     * @var int $_req_type
89
-     */
90
-    private $_req_type;
91
-
92
-    /**
93
-     * Whether or not there was a non-micro version change in EE core version during this request
94
-     *
95
-     * @var boolean $_major_version_change
96
-     */
97
-    private $_major_version_change = false;
98
-
99
-
100
-
101
-    /**
102
-     * @singleton method used to instantiate class object
103
-     * @access    public
104
-     * @param  EE_Registry $Registry
105
-     * @return EE_System
106
-     */
107
-    public static function instance(EE_Registry $Registry = null)
108
-    {
109
-        // check if class object is instantiated
110
-        if ( ! self::$_instance instanceof EE_System) {
111
-            self::$_instance = new self($Registry);
112
-        }
113
-        return self::$_instance;
114
-    }
115
-
116
-
117
-
118
-    /**
119
-     * resets the instance and returns it
120
-     *
121
-     * @return EE_System
122
-     */
123
-    public static function reset()
124
-    {
125
-        self::$_instance->_req_type = null;
126
-        //make sure none of the old hooks are left hanging around
127
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
128
-        //we need to reset the migration manager in order for it to detect DMSs properly
129
-        EE_Data_Migration_Manager::reset();
130
-        self::instance()->detect_activations_or_upgrades();
131
-        self::instance()->perform_activations_upgrades_and_migrations();
132
-        return self::instance();
133
-    }
134
-
135
-
136
-
137
-    /**
138
-     *    sets hooks for running rest of system
139
-     *    provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
140
-     *    starting EE Addons from any other point may lead to problems
141
-     *
142
-     * @access private
143
-     * @param  EE_Registry $Registry
144
-     */
145
-    private function __construct(EE_Registry $Registry)
146
-    {
147
-        $this->registry = $Registry;
148
-        do_action('AHEE__EE_System__construct__begin', $this);
149
-        add_action(
150
-            'AHEE__EE_Bootstrap__load_espresso_addons',
151
-            array($this, 'loadCapabilities'),
152
-            5
153
-        );
154
-        add_action(
155
-            'AHEE__EE_Bootstrap__load_espresso_addons',
156
-            array($this, 'loadCommandBus'),
157
-            7
158
-        );
159
-        add_action(
160
-            'AHEE__EE_Bootstrap__load_espresso_addons',
161
-            array($this, 'loadPluginApi'),
162
-            9
163
-        );
164
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
165
-        add_action(
166
-            'AHEE__EE_Bootstrap__load_espresso_addons',
167
-            array($this, 'load_espresso_addons')
168
-        );
169
-        // when an ee addon is activated, we want to call the core hook(s) again
170
-        // because the newly-activated addon didn't get a chance to run at all
171
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
172
-        // detect whether install or upgrade
173
-        add_action(
174
-            'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
175
-            array($this, 'detect_activations_or_upgrades'),
176
-            3
177
-        );
178
-        // load EE_Config, EE_Textdomain, etc
179
-        add_action(
180
-            'AHEE__EE_Bootstrap__load_core_configuration',
181
-            array($this, 'load_core_configuration'),
182
-            5
183
-        );
184
-        // load EE_Config, EE_Textdomain, etc
185
-        add_action(
186
-            'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
187
-            array($this, 'register_shortcodes_modules_and_widgets'),
188
-            7
189
-        );
190
-        // you wanna get going? I wanna get going... let's get going!
191
-        add_action(
192
-            'AHEE__EE_Bootstrap__brew_espresso',
193
-            array($this, 'brew_espresso'),
194
-            9
195
-        );
196
-        //other housekeeping
197
-        //exclude EE critical pages from wp_list_pages
198
-        add_filter(
199
-            'wp_list_pages_excludes',
200
-            array($this, 'remove_pages_from_wp_list_pages'),
201
-            10
202
-        );
203
-        // ALL EE Addons should use the following hook point to attach their initial setup too
204
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
205
-        do_action('AHEE__EE_System__construct__complete', $this);
206
-    }
207
-
208
-
209
-
210
-    /**
211
-     * load and setup EE_Capabilities
212
-     *
213
-     * @return void
214
-     * @throws EE_Error
215
-     */
216
-    public function loadCapabilities()
217
-    {
218
-        $this->registry->load_core('EE_Capabilities');
219
-        add_action(
220
-            'AHEE__EE_Capabilities__init_caps__before_initialization',
221
-            function() {
222
-                EE_Registry::instance()->load_lib('Payment_Method_Manager');
223
-            }
224
-        );
225
-    }
226
-
227
-
228
-
229
-    /**
230
-     * create and cache the CommandBus, and also add middleware
231
-     * The CapChecker middleware requires the use of EE_Capabilities
232
-     * which is why we need to load the CommandBus after Caps are set up
233
-     *
234
-     * @return void
235
-     * @throws EE_Error
236
-     */
237
-    public function loadCommandBus()
238
-    {
239
-        $this->registry->create(
240
-            'CommandBusInterface',
241
-            array(
242
-                null,
243
-                apply_filters(
244
-                    'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
245
-                    array(
246
-                        $this->registry->create('CapChecker'),
247
-                        $this->registry->create('AddActionHook'),
248
-                    )
249
-                ),
250
-            ),
251
-            true
252
-        );
253
-    }
254
-
255
-
256
-
257
-    /**
258
-     * @return void
259
-     * @throws EE_Error
260
-     */
261
-    public function loadPluginApi()
262
-    {
263
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
264
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
265
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
266
-    }
267
-
268
-
269
-
270
-    /**
271
-     * load_espresso_addons
272
-     * allow addons to load first so that they can set hooks for running DMS's, etc
273
-     * this is hooked into both:
274
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
275
-     *        which runs during the WP 'plugins_loaded' action at priority 5
276
-     *    and the WP 'activate_plugin' hook point
277
-     *
278
-     * @access public
279
-     * @return void
280
-     * @throws EE_Error
281
-     */
282
-    public function load_espresso_addons()
283
-    {
284
-        do_action('AHEE__EE_System__load_espresso_addons');
285
-        //if the WP API basic auth plugin isn't already loaded, load it now.
286
-        //We want it for mobile apps. Just include the entire plugin
287
-        //also, don't load the basic auth when a plugin is getting activated, because
288
-        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
289
-        //and causes a fatal error
290
-        if (
291
-            ! (isset($_GET['activate']) && $_GET['activate'] === 'true')
292
-            && ! function_exists('json_basic_auth_handler')
293
-            && ! function_exists('json_basic_auth_error')
294
-            && ! (
295
-                isset($_GET['action'])
296
-                && in_array($_GET['action'], array('activate', 'activate-selected'), true)
297
-            )
298
-        ) {
299
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
300
-        }
301
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
302
-    }
303
-
304
-
305
-
306
-    /**
307
-     * detect_activations_or_upgrades
308
-     * Checks for activation or upgrade of core first;
309
-     * then also checks if any registered addons have been activated or upgraded
310
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
311
-     * which runs during the WP 'plugins_loaded' action at priority 3
312
-     *
313
-     * @access public
314
-     * @return void
315
-     */
316
-    public function detect_activations_or_upgrades()
317
-    {
318
-        //first off: let's make sure to handle core
319
-        $this->detect_if_activation_or_upgrade();
320
-        foreach ($this->registry->addons as $addon) {
321
-            //detect teh request type for that addon
322
-            $addon->detect_activation_or_upgrade();
323
-        }
324
-    }
325
-
326
-
327
-
328
-    /**
329
-     * detect_if_activation_or_upgrade
330
-     * Takes care of detecting whether this is a brand new install or code upgrade,
331
-     * and either setting up the DB or setting up maintenance mode etc.
332
-     *
333
-     * @access public
334
-     * @return void
335
-     */
336
-    public function detect_if_activation_or_upgrade()
337
-    {
338
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
339
-        // load M-Mode class
340
-        $this->registry->load_core('Maintenance_Mode');
341
-        // check if db has been updated, or if its a brand-new installation
342
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
343
-        $request_type = $this->detect_req_type($espresso_db_update);
344
-        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
345
-        switch ($request_type) {
346
-            case EE_System::req_type_new_activation:
347
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
348
-                $this->_handle_core_version_change($espresso_db_update);
349
-                break;
350
-            case EE_System::req_type_reactivation:
351
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
352
-                $this->_handle_core_version_change($espresso_db_update);
353
-                break;
354
-            case EE_System::req_type_upgrade:
355
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
356
-                //migrations may be required now that we've upgraded
357
-                EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
358
-                $this->_handle_core_version_change($espresso_db_update);
359
-                //				echo "done upgrade";die;
360
-                break;
361
-            case EE_System::req_type_downgrade:
362
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
363
-                //its possible migrations are no longer required
364
-                EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
365
-                $this->_handle_core_version_change($espresso_db_update);
366
-                break;
367
-            case EE_System::req_type_normal:
368
-            default:
369
-                //				$this->_maybe_redirect_to_ee_about();
370
-                break;
371
-        }
372
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
373
-    }
374
-
375
-
376
-
377
-    /**
378
-     * Updates the list of installed versions and sets hooks for
379
-     * initializing the database later during the request
380
-     *
381
-     * @param array $espresso_db_update
382
-     */
383
-    protected function _handle_core_version_change($espresso_db_update)
384
-    {
385
-        $this->update_list_of_installed_versions($espresso_db_update);
386
-        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
387
-        add_action('AHEE__EE_System__perform_activations_upgrades_and_migrations',
388
-            array($this, 'initialize_db_if_no_migrations_required'));
389
-    }
390
-
391
-
392
-
393
-    /**
394
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
395
-     * information about what versions of EE have been installed and activated,
396
-     * NOT necessarily the state of the database
397
-     *
398
-     * @param mixed $espresso_db_update the value of the WordPress option.
399
-     *                                            If not supplied, fetches it from the options table
400
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
401
-     */
402
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
403
-    {
404
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
405
-        if ( ! $espresso_db_update) {
406
-            $espresso_db_update = get_option('espresso_db_update');
407
-        }
408
-        // check that option is an array
409
-        if ( ! is_array($espresso_db_update)) {
410
-            // if option is FALSE, then it never existed
411
-            if ($espresso_db_update === false) {
412
-                // make $espresso_db_update an array and save option with autoload OFF
413
-                $espresso_db_update = array();
414
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
415
-            } else {
416
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
417
-                $espresso_db_update = array($espresso_db_update => array());
418
-                update_option('espresso_db_update', $espresso_db_update);
419
-            }
420
-        } else {
421
-            $corrected_db_update = array();
422
-            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
423
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
424
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
425
-                    //the key is an int, and the value IS NOT an array
426
-                    //so it must be numerically-indexed, where values are versions installed...
427
-                    //fix it!
428
-                    $version_string = $should_be_array;
429
-                    $corrected_db_update[$version_string] = array('unknown-date');
430
-                } else {
431
-                    //ok it checks out
432
-                    $corrected_db_update[$should_be_version_string] = $should_be_array;
433
-                }
434
-            }
435
-            $espresso_db_update = $corrected_db_update;
436
-            update_option('espresso_db_update', $espresso_db_update);
437
-        }
438
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
439
-        return $espresso_db_update;
440
-    }
441
-
442
-
443
-
444
-    /**
445
-     * Does the traditional work of setting up the plugin's database and adding default data.
446
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
447
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
448
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
449
-     * so that it will be done when migrations are finished
450
-     *
451
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
452
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
453
-     *                                       This is a resource-intensive job
454
-     *                                       so we prefer to only do it when necessary
455
-     * @return void
456
-     * @throws EE_Error
457
-     */
458
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
459
-    {
460
-        $request_type = $this->detect_req_type();
461
-        //only initialize system if we're not in maintenance mode.
462
-        if (EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
463
-            update_option('ee_flush_rewrite_rules', true);
464
-            if ($verify_schema) {
465
-                EEH_Activation::initialize_db_and_folders();
466
-            }
467
-            EEH_Activation::initialize_db_content();
468
-            EEH_Activation::system_initialization();
469
-            if ($initialize_addons_too) {
470
-                $this->initialize_addons();
471
-            }
472
-        } else {
473
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
474
-        }
475
-        if ($request_type === EE_System::req_type_new_activation
476
-            || $request_type === EE_System::req_type_reactivation
477
-            || (
478
-                $request_type === EE_System::req_type_upgrade
479
-                && $this->is_major_version_change()
480
-            )
481
-        ) {
482
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
483
-        }
484
-    }
485
-
486
-
487
-
488
-    /**
489
-     * Initializes the db for all registered addons
490
-     *
491
-     * @throws EE_Error
492
-     */
493
-    public function initialize_addons()
494
-    {
495
-        //foreach registered addon, make sure its db is up-to-date too
496
-        foreach ($this->registry->addons as $addon) {
497
-            $addon->initialize_db_if_no_migrations_required();
498
-        }
499
-    }
500
-
501
-
502
-
503
-    /**
504
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
505
-     *
506
-     * @param    array  $version_history
507
-     * @param    string $current_version_to_add version to be added to the version history
508
-     * @return    boolean success as to whether or not this option was changed
509
-     */
510
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
511
-    {
512
-        if ( ! $version_history) {
513
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
514
-        }
515
-        if ($current_version_to_add === null) {
516
-            $current_version_to_add = espresso_version();
517
-        }
518
-        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
519
-        // re-save
520
-        return update_option('espresso_db_update', $version_history);
521
-    }
522
-
523
-
524
-
525
-    /**
526
-     * Detects if the current version indicated in the has existed in the list of
527
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
528
-     *
529
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
530
-     *                                  If not supplied, fetches it from the options table.
531
-     *                                  Also, caches its result so later parts of the code can also know whether
532
-     *                                  there's been an update or not. This way we can add the current version to
533
-     *                                  espresso_db_update, but still know if this is a new install or not
534
-     * @return int one of the constants on EE_System::req_type_
535
-     */
536
-    public function detect_req_type($espresso_db_update = null)
537
-    {
538
-        if ($this->_req_type === null) {
539
-            $espresso_db_update = ! empty($espresso_db_update) ? $espresso_db_update
540
-                : $this->fix_espresso_db_upgrade_option();
541
-            $this->_req_type = EE_System::detect_req_type_given_activation_history($espresso_db_update,
542
-                'ee_espresso_activation', espresso_version());
543
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
544
-        }
545
-        return $this->_req_type;
546
-    }
547
-
548
-
549
-
550
-    /**
551
-     * Returns whether or not there was a non-micro version change (ie, change in either
552
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
553
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
554
-     *
555
-     * @param $activation_history
556
-     * @return bool
557
-     */
558
-    protected function _detect_major_version_change($activation_history)
559
-    {
560
-        $previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
561
-        $previous_version_parts = explode('.', $previous_version);
562
-        $current_version_parts = explode('.', espresso_version());
563
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
564
-               && ($previous_version_parts[0] !== $current_version_parts[0]
565
-                   || $previous_version_parts[1] !== $current_version_parts[1]
566
-               );
567
-    }
568
-
569
-
570
-
571
-    /**
572
-     * Returns true if either the major or minor version of EE changed during this request.
573
-     * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
574
-     *
575
-     * @return bool
576
-     */
577
-    public function is_major_version_change()
578
-    {
579
-        return $this->_major_version_change;
580
-    }
581
-
582
-
583
-
584
-    /**
585
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
586
-     * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
587
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
588
-     * just activated to (for core that will always be espresso_version())
589
-     *
590
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
591
-     *                                                 ee plugin. for core that's 'espresso_db_update'
592
-     * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
593
-     *                                                 indicate that this plugin was just activated
594
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
595
-     *                                                 espresso_version())
596
-     * @return int one of the constants on EE_System::req_type_*
597
-     */
598
-    public static function detect_req_type_given_activation_history(
599
-        $activation_history_for_addon,
600
-        $activation_indicator_option_name,
601
-        $version_to_upgrade_to
602
-    ) {
603
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
604
-        if ($activation_history_for_addon) {
605
-            //it exists, so this isn't a completely new install
606
-            //check if this version already in that list of previously installed versions
607
-            if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
608
-                //it a version we haven't seen before
609
-                if ($version_is_higher === 1) {
610
-                    $req_type = EE_System::req_type_upgrade;
611
-                } else {
612
-                    $req_type = EE_System::req_type_downgrade;
613
-                }
614
-                delete_option($activation_indicator_option_name);
615
-            } else {
616
-                // its not an update. maybe a reactivation?
617
-                if (get_option($activation_indicator_option_name, false)) {
618
-                    if ($version_is_higher === -1) {
619
-                        $req_type = EE_System::req_type_downgrade;
620
-                    } elseif ($version_is_higher === 0) {
621
-                        //we've seen this version before, but it's an activation. must be a reactivation
622
-                        $req_type = EE_System::req_type_reactivation;
623
-                    } else {//$version_is_higher === 1
624
-                        $req_type = EE_System::req_type_upgrade;
625
-                    }
626
-                    delete_option($activation_indicator_option_name);
627
-                } else {
628
-                    //we've seen this version before and the activation indicate doesn't show it was just activated
629
-                    if ($version_is_higher === -1) {
630
-                        $req_type = EE_System::req_type_downgrade;
631
-                    } elseif ($version_is_higher === 0) {
632
-                        //we've seen this version before and it's not an activation. its normal request
633
-                        $req_type = EE_System::req_type_normal;
634
-                    } else {//$version_is_higher === 1
635
-                        $req_type = EE_System::req_type_upgrade;
636
-                    }
637
-                }
638
-            }
639
-        } else {
640
-            //brand new install
641
-            $req_type = EE_System::req_type_new_activation;
642
-            delete_option($activation_indicator_option_name);
643
-        }
644
-        return $req_type;
645
-    }
646
-
647
-
648
-
649
-    /**
650
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
651
-     * the $activation_history_for_addon
652
-     *
653
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
654
-     *                                             sometimes containing 'unknown-date'
655
-     * @param string $version_to_upgrade_to        (current version)
656
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
657
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
658
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
659
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
660
-     */
661
-    protected static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
662
-    {
663
-        //find the most recently-activated version
664
-        $most_recently_active_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
665
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
666
-    }
667
-
668
-
669
-
670
-    /**
671
-     * Gets the most recently active version listed in the activation history,
672
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
673
-     *
674
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
675
-     *                                   sometimes containing 'unknown-date'
676
-     * @return string
677
-     */
678
-    protected static function _get_most_recently_active_version_from_activation_history($activation_history)
679
-    {
680
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
681
-        $most_recently_active_version = '0.0.0.dev.000';
682
-        if (is_array($activation_history)) {
683
-            foreach ($activation_history as $version => $times_activated) {
684
-                //check there is a record of when this version was activated. Otherwise,
685
-                //mark it as unknown
686
-                if ( ! $times_activated) {
687
-                    $times_activated = array('unknown-date');
688
-                }
689
-                if (is_string($times_activated)) {
690
-                    $times_activated = array($times_activated);
691
-                }
692
-                foreach ($times_activated as $an_activation) {
693
-                    if ($an_activation !== 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
694
-                        $most_recently_active_version = $version;
695
-                        $most_recently_active_version_activation = $an_activation === 'unknown-date'
696
-                            ? '1970-01-01 00:00:00' : $an_activation;
697
-                    }
698
-                }
699
-            }
700
-        }
701
-        return $most_recently_active_version;
702
-    }
703
-
704
-
705
-
706
-    /**
707
-     * This redirects to the about EE page after activation
708
-     *
709
-     * @return void
710
-     */
711
-    public function redirect_to_about_ee()
712
-    {
713
-        $notices = EE_Error::get_notices(false);
714
-        //if current user is an admin and it's not an ajax or rest request
715
-        if (
716
-            ! (defined('DOING_AJAX') && DOING_AJAX)
717
-            && ! (defined('REST_REQUEST') && REST_REQUEST)
718
-            && ! isset($notices['errors'])
719
-            && apply_filters(
720
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
721
-                $this->registry->CAP->current_user_can('manage_options', 'espresso_about_default')
722
-            )
723
-        ) {
724
-            $query_params = array('page' => 'espresso_about');
725
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
726
-                $query_params['new_activation'] = true;
727
-            }
728
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
729
-                $query_params['reactivation'] = true;
730
-            }
731
-            $url = add_query_arg($query_params, admin_url('admin.php'));
732
-            wp_safe_redirect($url);
733
-            exit();
734
-        }
735
-    }
736
-
737
-
738
-
739
-    /**
740
-     * load_core_configuration
741
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
742
-     * which runs during the WP 'plugins_loaded' action at priority 5
743
-     *
744
-     * @return void
745
-     * @throws \ReflectionException
746
-     */
747
-    public function load_core_configuration()
748
-    {
749
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
750
-        $this->registry->load_core('EE_Load_Textdomain');
751
-        //load textdomain
752
-        EE_Load_Textdomain::load_textdomain();
753
-        // load and setup EE_Config and EE_Network_Config
754
-        $this->registry->load_core('Config');
755
-        $this->registry->load_core('Network_Config');
756
-        // setup autoloaders
757
-        // enable logging?
758
-        if ($this->registry->CFG->admin->use_full_logging) {
759
-            $this->registry->load_core('Log');
760
-        }
761
-        // check for activation errors
762
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
763
-        if ($activation_errors) {
764
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
765
-            update_option('ee_plugin_activation_errors', false);
766
-        }
767
-        // get model names
768
-        $this->_parse_model_names();
769
-        //load caf stuff a chance to play during the activation process too.
770
-        $this->_maybe_brew_regular();
771
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
772
-    }
773
-
774
-
775
-
776
-    /**
777
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
778
-     *
779
-     * @return void
780
-     * @throws ReflectionException
781
-     */
782
-    private function _parse_model_names()
783
-    {
784
-        //get all the files in the EE_MODELS folder that end in .model.php
785
-        $models = glob(EE_MODELS . '*.model.php');
786
-        $model_names = array();
787
-        $non_abstract_db_models = array();
788
-        foreach ($models as $model) {
789
-            // get model classname
790
-            $classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
791
-            $short_name = str_replace('EEM_', '', $classname);
792
-            $reflectionClass = new ReflectionClass($classname);
793
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
794
-                $non_abstract_db_models[$short_name] = $classname;
795
-            }
796
-            $model_names[$short_name] = $classname;
797
-        }
798
-        $this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
799
-        $this->registry->non_abstract_db_models = apply_filters('FHEE__EE_System__parse_implemented_model_names',
800
-            $non_abstract_db_models);
801
-    }
802
-
803
-
804
-
805
-    /**
806
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
807
-     * that need to be setup before our EE_System launches.
808
-     *
809
-     * @return void
810
-     */
811
-    private function _maybe_brew_regular()
812
-    {
813
-        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
814
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
815
-        }
816
-    }
817
-
818
-
819
-
820
-    /**
821
-     * register_shortcodes_modules_and_widgets
822
-     * generate lists of shortcodes and modules, then verify paths and classes
823
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
824
-     * which runs during the WP 'plugins_loaded' action at priority 7
825
-     *
826
-     * @access public
827
-     * @return void
828
-     */
829
-    public function register_shortcodes_modules_and_widgets()
830
-    {
831
-        try {
832
-            // load, register, and add shortcodes the new way
833
-            LoaderFactory::getLoader()->getShared(
834
-                'EventEspresso\core\services\shortcodes\ShortcodesManager',
835
-                array(
836
-                    // and the old way, but we'll put it under control of the new system
837
-                    EE_Config::getLegacyShortcodesManager()
838
-                )
839
-            );
840
-        } catch (Exception $exception) {
841
-            new ExceptionStackTraceDisplay($exception);
842
-        }
843
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
844
-        // check for addons using old hook point
845
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
846
-            $this->_incompatible_addon_error();
847
-        }
848
-    }
849
-
850
-
851
-
852
-    /**
853
-     * _incompatible_addon_error
854
-     *
855
-     * @access public
856
-     * @return void
857
-     */
858
-    private function _incompatible_addon_error()
859
-    {
860
-        // get array of classes hooking into here
861
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook('AHEE__EE_System__register_shortcodes_modules_and_addons');
862
-        if ( ! empty($class_names)) {
863
-            $msg = __('The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
864
-                'event_espresso');
865
-            $msg .= '<ul>';
866
-            foreach ($class_names as $class_name) {
867
-                $msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
868
-                        $class_name) . '</b></li>';
869
-            }
870
-            $msg .= '</ul>';
871
-            $msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
872
-                'event_espresso');
873
-            // save list of incompatible addons to wp-options for later use
874
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
875
-            if (is_admin()) {
876
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
877
-            }
878
-        }
879
-    }
880
-
881
-
882
-
883
-    /**
884
-     * brew_espresso
885
-     * begins the process of setting hooks for initializing EE in the correct order
886
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
887
-     * which runs during the WP 'plugins_loaded' action at priority 9
888
-     *
889
-     * @return void
890
-     */
891
-    public function brew_espresso()
892
-    {
893
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
894
-        // load some final core systems
895
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
896
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
897
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
898
-        add_action('init', array($this, 'load_controllers'), 7);
899
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
900
-        add_action('init', array($this, 'initialize'), 10);
901
-        add_action('init', array($this, 'initialize_last'), 100);
902
-        add_action('admin_bar_menu', array($this, 'espresso_toolbar_items'), 100);
903
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
904
-            // pew pew pew
905
-            $this->registry->load_core('PUE');
906
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
907
-        }
908
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
909
-    }
910
-
911
-
912
-
913
-    /**
914
-     *    set_hooks_for_core
915
-     *
916
-     * @access public
917
-     * @return    void
918
-     * @throws EE_Error
919
-     */
920
-    public function set_hooks_for_core()
921
-    {
922
-        $this->_deactivate_incompatible_addons();
923
-        do_action('AHEE__EE_System__set_hooks_for_core');
924
-        //caps need to be initialized on every request so that capability maps are set.
925
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
926
-        $this->registry->CAP->init_caps();
927
-    }
928
-
929
-
930
-
931
-    /**
932
-     * Using the information gathered in EE_System::_incompatible_addon_error,
933
-     * deactivates any addons considered incompatible with the current version of EE
934
-     */
935
-    private function _deactivate_incompatible_addons()
936
-    {
937
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
938
-        if ( ! empty($incompatible_addons)) {
939
-            $active_plugins = get_option('active_plugins', array());
940
-            foreach ($active_plugins as $active_plugin) {
941
-                foreach ($incompatible_addons as $incompatible_addon) {
942
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
943
-                        unset($_GET['activate']);
944
-                        espresso_deactivate_plugin($active_plugin);
945
-                    }
946
-                }
947
-            }
948
-        }
949
-    }
950
-
951
-
952
-
953
-    /**
954
-     *    perform_activations_upgrades_and_migrations
955
-     *
956
-     * @access public
957
-     * @return    void
958
-     */
959
-    public function perform_activations_upgrades_and_migrations()
960
-    {
961
-        //first check if we had previously attempted to setup EE's directories but failed
962
-        if (EEH_Activation::upload_directories_incomplete()) {
963
-            EEH_Activation::create_upload_directories();
964
-        }
965
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
966
-    }
967
-
968
-
969
-
970
-    /**
971
-     *    load_CPTs_and_session
972
-     *
973
-     * @access public
974
-     * @return    void
975
-     */
976
-    public function load_CPTs_and_session()
977
-    {
978
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
979
-        // register Custom Post Types
980
-        $this->registry->load_core('Register_CPTs');
981
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
982
-    }
983
-
984
-
985
-
986
-    /**
987
-     * load_controllers
988
-     * this is the best place to load any additional controllers that needs access to EE core.
989
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
990
-     * time
991
-     *
992
-     * @access public
993
-     * @return void
994
-     */
995
-    public function load_controllers()
996
-    {
997
-        do_action('AHEE__EE_System__load_controllers__start');
998
-        // let's get it started
999
-        if ( ! is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
1000
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1001
-            $this->registry->load_core('Front_Controller');
1002
-        } else if ( ! EE_FRONT_AJAX) {
1003
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1004
-            EE_Registry::instance()->load_core('Admin');
1005
-        }
1006
-        do_action('AHEE__EE_System__load_controllers__complete');
1007
-    }
1008
-
1009
-
1010
-
1011
-    /**
1012
-     * core_loaded_and_ready
1013
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1014
-     *
1015
-     * @access public
1016
-     * @return void
1017
-     */
1018
-    public function core_loaded_and_ready()
1019
-    {
1020
-        $this->registry->load_core('Session');
1021
-        do_action('AHEE__EE_System__core_loaded_and_ready');
1022
-        // load_espresso_template_tags
1023
-        if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1024
-            require_once(EE_PUBLIC . 'template_tags.php');
1025
-        }
1026
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1027
-        $this->registry->create('EventEspresso\core\services\assets\Registry', array(), true);
1028
-    }
1029
-
1030
-
1031
-
1032
-    /**
1033
-     * initialize
1034
-     * this is the best place to begin initializing client code
1035
-     *
1036
-     * @access public
1037
-     * @return void
1038
-     */
1039
-    public function initialize()
1040
-    {
1041
-        do_action('AHEE__EE_System__initialize');
1042
-    }
1043
-
1044
-
1045
-
1046
-    /**
1047
-     * initialize_last
1048
-     * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1049
-     * initialize has done so
1050
-     *
1051
-     * @access public
1052
-     * @return void
1053
-     */
1054
-    public function initialize_last()
1055
-    {
1056
-        do_action('AHEE__EE_System__initialize_last');
1057
-    }
1058
-
1059
-
1060
-
1061
-    /**
1062
-     * set_hooks_for_shortcodes_modules_and_addons
1063
-     * this is the best place for other systems to set callbacks for hooking into other parts of EE
1064
-     * this happens at the very beginning of the wp_loaded hook point
1065
-     *
1066
-     * @access public
1067
-     * @return void
1068
-     */
1069
-    public function set_hooks_for_shortcodes_modules_and_addons()
1070
-    {
1071
-        //		do_action( 'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons' );
1072
-    }
1073
-
1074
-
1075
-
1076
-    /**
1077
-     * do_not_cache
1078
-     * sets no cache headers and defines no cache constants for WP plugins
1079
-     *
1080
-     * @access public
1081
-     * @return void
1082
-     */
1083
-    public static function do_not_cache()
1084
-    {
1085
-        // set no cache constants
1086
-        if ( ! defined('DONOTCACHEPAGE')) {
1087
-            define('DONOTCACHEPAGE', true);
1088
-        }
1089
-        if ( ! defined('DONOTCACHCEOBJECT')) {
1090
-            define('DONOTCACHCEOBJECT', true);
1091
-        }
1092
-        if ( ! defined('DONOTCACHEDB')) {
1093
-            define('DONOTCACHEDB', true);
1094
-        }
1095
-        // add no cache headers
1096
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1097
-        // plus a little extra for nginx and Google Chrome
1098
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1099
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1100
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1101
-    }
1102
-
1103
-
1104
-
1105
-    /**
1106
-     *    extra_nocache_headers
1107
-     *
1108
-     * @access    public
1109
-     * @param $headers
1110
-     * @return    array
1111
-     */
1112
-    public static function extra_nocache_headers($headers)
1113
-    {
1114
-        // for NGINX
1115
-        $headers['X-Accel-Expires'] = 0;
1116
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1117
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1118
-        return $headers;
1119
-    }
1120
-
1121
-
1122
-
1123
-    /**
1124
-     *    nocache_headers
1125
-     *
1126
-     * @access    public
1127
-     * @return    void
1128
-     */
1129
-    public static function nocache_headers()
1130
-    {
1131
-        nocache_headers();
1132
-    }
1133
-
1134
-
1135
-
1136
-    /**
1137
-     *    espresso_toolbar_items
1138
-     *
1139
-     * @access public
1140
-     * @param  WP_Admin_Bar $admin_bar
1141
-     * @return void
1142
-     */
1143
-    public function espresso_toolbar_items(WP_Admin_Bar $admin_bar)
1144
-    {
1145
-        // if in full M-Mode, or its an AJAX request, or user is NOT an admin
1146
-        if (
1147
-            defined('DOING_AJAX')
1148
-            || ! $this->registry->CAP->current_user_can('ee_read_ee', 'ee_admin_bar_menu_top_level')
1149
-            || EE_Maintenance_Mode::instance()->level() === EE_Maintenance_Mode::level_2_complete_maintenance
1150
-        ) {
1151
-            return;
1152
-        }
1153
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1154
-        $menu_class = 'espresso_menu_item_class';
1155
-        //we don't use the constants EVENTS_ADMIN_URL or REG_ADMIN_URL
1156
-        //because they're only defined in each of their respective constructors
1157
-        //and this might be a frontend request, in which case they aren't available
1158
-        $events_admin_url = admin_url('admin.php?page=espresso_events');
1159
-        $reg_admin_url = admin_url('admin.php?page=espresso_registrations');
1160
-        $extensions_admin_url = admin_url('admin.php?page=espresso_packages');
1161
-        //Top Level
1162
-        $admin_bar->add_menu(array(
1163
-            'id'    => 'espresso-toolbar',
1164
-            'title' => '<span class="ee-icon ee-icon-ee-cup-thick ee-icon-size-20"></span><span class="ab-label">'
1165
-                       . _x('Event Espresso', 'admin bar menu group label', 'event_espresso')
1166
-                       . '</span>',
1167
-            'href'  => $events_admin_url,
1168
-            'meta'  => array(
1169
-                'title' => __('Event Espresso', 'event_espresso'),
1170
-                'class' => $menu_class . 'first',
1171
-            ),
1172
-        ));
1173
-        //Events
1174
-        if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events')) {
1175
-            $admin_bar->add_menu(array(
1176
-                'id'     => 'espresso-toolbar-events',
1177
-                'parent' => 'espresso-toolbar',
1178
-                'title'  => __('Events', 'event_espresso'),
1179
-                'href'   => $events_admin_url,
1180
-                'meta'   => array(
1181
-                    'title'  => __('Events', 'event_espresso'),
1182
-                    'target' => '',
1183
-                    'class'  => $menu_class,
1184
-                ),
1185
-            ));
1186
-        }
1187
-        if ($this->registry->CAP->current_user_can('ee_edit_events', 'ee_admin_bar_menu_espresso-toolbar-events-new')) {
1188
-            //Events Add New
1189
-            $admin_bar->add_menu(array(
1190
-                'id'     => 'espresso-toolbar-events-new',
1191
-                'parent' => 'espresso-toolbar-events',
1192
-                'title'  => __('Add New', 'event_espresso'),
1193
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'create_new'), $events_admin_url),
1194
-                'meta'   => array(
1195
-                    'title'  => __('Add New', 'event_espresso'),
1196
-                    'target' => '',
1197
-                    'class'  => $menu_class,
1198
-                ),
1199
-            ));
1200
-        }
1201
-        if (is_single() && (get_post_type() === 'espresso_events')) {
1202
-            //Current post
1203
-            global $post;
1204
-            if ($this->registry->CAP->current_user_can('ee_edit_event',
1205
-                'ee_admin_bar_menu_espresso-toolbar-events-edit', $post->ID)
1206
-            ) {
1207
-                //Events Edit Current Event
1208
-                $admin_bar->add_menu(array(
1209
-                    'id'     => 'espresso-toolbar-events-edit',
1210
-                    'parent' => 'espresso-toolbar-events',
1211
-                    'title'  => __('Edit Event', 'event_espresso'),
1212
-                    'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'edit', 'post' => $post->ID),
1213
-                        $events_admin_url),
1214
-                    'meta'   => array(
1215
-                        'title'  => __('Edit Event', 'event_espresso'),
1216
-                        'target' => '',
1217
-                        'class'  => $menu_class,
1218
-                    ),
1219
-                ));
1220
-            }
1221
-        }
1222
-        //Events View
1223
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1224
-            'ee_admin_bar_menu_espresso-toolbar-events-view')
1225
-        ) {
1226
-            $admin_bar->add_menu(array(
1227
-                'id'     => 'espresso-toolbar-events-view',
1228
-                'parent' => 'espresso-toolbar-events',
1229
-                'title'  => __('View', 'event_espresso'),
1230
-                'href'   => $events_admin_url,
1231
-                'meta'   => array(
1232
-                    'title'  => __('View', 'event_espresso'),
1233
-                    'target' => '',
1234
-                    'class'  => $menu_class,
1235
-                ),
1236
-            ));
1237
-        }
1238
-        if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events-all')) {
1239
-            //Events View All
1240
-            $admin_bar->add_menu(array(
1241
-                'id'     => 'espresso-toolbar-events-all',
1242
-                'parent' => 'espresso-toolbar-events-view',
1243
-                'title'  => __('All', 'event_espresso'),
1244
-                'href'   => $events_admin_url,
1245
-                'meta'   => array(
1246
-                    'title'  => __('All', 'event_espresso'),
1247
-                    'target' => '',
1248
-                    'class'  => $menu_class,
1249
-                ),
1250
-            ));
1251
-        }
1252
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1253
-            'ee_admin_bar_menu_espresso-toolbar-events-today')
1254
-        ) {
1255
-            //Events View Today
1256
-            $admin_bar->add_menu(array(
1257
-                'id'     => 'espresso-toolbar-events-today',
1258
-                'parent' => 'espresso-toolbar-events-view',
1259
-                'title'  => __('Today', 'event_espresso'),
1260
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1261
-                    $events_admin_url),
1262
-                'meta'   => array(
1263
-                    'title'  => __('Today', 'event_espresso'),
1264
-                    'target' => '',
1265
-                    'class'  => $menu_class,
1266
-                ),
1267
-            ));
1268
-        }
1269
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1270
-            'ee_admin_bar_menu_espresso-toolbar-events-month')
1271
-        ) {
1272
-            //Events View This Month
1273
-            $admin_bar->add_menu(array(
1274
-                'id'     => 'espresso-toolbar-events-month',
1275
-                'parent' => 'espresso-toolbar-events-view',
1276
-                'title'  => __('This Month', 'event_espresso'),
1277
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1278
-                    $events_admin_url),
1279
-                'meta'   => array(
1280
-                    'title'  => __('This Month', 'event_espresso'),
1281
-                    'target' => '',
1282
-                    'class'  => $menu_class,
1283
-                ),
1284
-            ));
1285
-        }
1286
-        //Registration Overview
1287
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1288
-            'ee_admin_bar_menu_espresso-toolbar-registrations')
1289
-        ) {
1290
-            $admin_bar->add_menu(array(
1291
-                'id'     => 'espresso-toolbar-registrations',
1292
-                'parent' => 'espresso-toolbar',
1293
-                'title'  => __('Registrations', 'event_espresso'),
1294
-                'href'   => $reg_admin_url,
1295
-                'meta'   => array(
1296
-                    'title'  => __('Registrations', 'event_espresso'),
1297
-                    'target' => '',
1298
-                    'class'  => $menu_class,
1299
-                ),
1300
-            ));
1301
-        }
1302
-        //Registration Overview Today
1303
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1304
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today')
1305
-        ) {
1306
-            $admin_bar->add_menu(array(
1307
-                'id'     => 'espresso-toolbar-registrations-today',
1308
-                'parent' => 'espresso-toolbar-registrations',
1309
-                'title'  => __('Today', 'event_espresso'),
1310
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1311
-                    $reg_admin_url),
1312
-                'meta'   => array(
1313
-                    'title'  => __('Today', 'event_espresso'),
1314
-                    'target' => '',
1315
-                    'class'  => $menu_class,
1316
-                ),
1317
-            ));
1318
-        }
1319
-        //Registration Overview Today Completed
1320
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1321
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-approved')
1322
-        ) {
1323
-            $admin_bar->add_menu(array(
1324
-                'id'     => 'espresso-toolbar-registrations-today-approved',
1325
-                'parent' => 'espresso-toolbar-registrations-today',
1326
-                'title'  => __('Approved', 'event_espresso'),
1327
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1328
-                    'action'      => 'default',
1329
-                    'status'      => 'today',
1330
-                    '_reg_status' => EEM_Registration::status_id_approved,
1331
-                ), $reg_admin_url),
1332
-                'meta'   => array(
1333
-                    'title'  => __('Approved', 'event_espresso'),
1334
-                    'target' => '',
1335
-                    'class'  => $menu_class,
1336
-                ),
1337
-            ));
1338
-        }
1339
-        //Registration Overview Today Pending\
1340
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1341
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-pending')
1342
-        ) {
1343
-            $admin_bar->add_menu(array(
1344
-                'id'     => 'espresso-toolbar-registrations-today-pending',
1345
-                'parent' => 'espresso-toolbar-registrations-today',
1346
-                'title'  => __('Pending', 'event_espresso'),
1347
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1348
-                    'action'     => 'default',
1349
-                    'status'     => 'today',
1350
-                    'reg_status' => EEM_Registration::status_id_pending_payment,
1351
-                ), $reg_admin_url),
1352
-                'meta'   => array(
1353
-                    'title'  => __('Pending Payment', 'event_espresso'),
1354
-                    'target' => '',
1355
-                    'class'  => $menu_class,
1356
-                ),
1357
-            ));
1358
-        }
1359
-        //Registration Overview Today Incomplete
1360
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1361
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-not-approved')
1362
-        ) {
1363
-            $admin_bar->add_menu(array(
1364
-                'id'     => 'espresso-toolbar-registrations-today-not-approved',
1365
-                'parent' => 'espresso-toolbar-registrations-today',
1366
-                'title'  => __('Not Approved', 'event_espresso'),
1367
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1368
-                    'action'      => 'default',
1369
-                    'status'      => 'today',
1370
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1371
-                ), $reg_admin_url),
1372
-                'meta'   => array(
1373
-                    'title'  => __('Not Approved', 'event_espresso'),
1374
-                    'target' => '',
1375
-                    'class'  => $menu_class,
1376
-                ),
1377
-            ));
1378
-        }
1379
-        //Registration Overview Today Incomplete
1380
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1381
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-cancelled')
1382
-        ) {
1383
-            $admin_bar->add_menu(array(
1384
-                'id'     => 'espresso-toolbar-registrations-today-cancelled',
1385
-                'parent' => 'espresso-toolbar-registrations-today',
1386
-                'title'  => __('Cancelled', 'event_espresso'),
1387
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1388
-                    'action'      => 'default',
1389
-                    'status'      => 'today',
1390
-                    '_reg_status' => EEM_Registration::status_id_cancelled,
1391
-                ), $reg_admin_url),
1392
-                'meta'   => array(
1393
-                    'title'  => __('Cancelled', 'event_espresso'),
1394
-                    'target' => '',
1395
-                    'class'  => $menu_class,
1396
-                ),
1397
-            ));
1398
-        }
1399
-        //Registration Overview This Month
1400
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1401
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month')
1402
-        ) {
1403
-            $admin_bar->add_menu(array(
1404
-                'id'     => 'espresso-toolbar-registrations-month',
1405
-                'parent' => 'espresso-toolbar-registrations',
1406
-                'title'  => __('This Month', 'event_espresso'),
1407
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1408
-                    $reg_admin_url),
1409
-                'meta'   => array(
1410
-                    'title'  => __('This Month', 'event_espresso'),
1411
-                    'target' => '',
1412
-                    'class'  => $menu_class,
1413
-                ),
1414
-            ));
1415
-        }
1416
-        //Registration Overview This Month Approved
1417
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1418
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-approved')
1419
-        ) {
1420
-            $admin_bar->add_menu(array(
1421
-                'id'     => 'espresso-toolbar-registrations-month-approved',
1422
-                'parent' => 'espresso-toolbar-registrations-month',
1423
-                'title'  => __('Approved', 'event_espresso'),
1424
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1425
-                    'action'      => 'default',
1426
-                    'status'      => 'month',
1427
-                    '_reg_status' => EEM_Registration::status_id_approved,
1428
-                ), $reg_admin_url),
1429
-                'meta'   => array(
1430
-                    'title'  => __('Approved', 'event_espresso'),
1431
-                    'target' => '',
1432
-                    'class'  => $menu_class,
1433
-                ),
1434
-            ));
1435
-        }
1436
-        //Registration Overview This Month Pending
1437
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1438
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-pending')
1439
-        ) {
1440
-            $admin_bar->add_menu(array(
1441
-                'id'     => 'espresso-toolbar-registrations-month-pending',
1442
-                'parent' => 'espresso-toolbar-registrations-month',
1443
-                'title'  => __('Pending', 'event_espresso'),
1444
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1445
-                    'action'      => 'default',
1446
-                    'status'      => 'month',
1447
-                    '_reg_status' => EEM_Registration::status_id_pending_payment,
1448
-                ), $reg_admin_url),
1449
-                'meta'   => array(
1450
-                    'title'  => __('Pending', 'event_espresso'),
1451
-                    'target' => '',
1452
-                    'class'  => $menu_class,
1453
-                ),
1454
-            ));
1455
-        }
1456
-        //Registration Overview This Month Not Approved
1457
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1458
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-not-approved')
1459
-        ) {
1460
-            $admin_bar->add_menu(array(
1461
-                'id'     => 'espresso-toolbar-registrations-month-not-approved',
1462
-                'parent' => 'espresso-toolbar-registrations-month',
1463
-                'title'  => __('Not Approved', 'event_espresso'),
1464
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1465
-                    'action'      => 'default',
1466
-                    'status'      => 'month',
1467
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1468
-                ), $reg_admin_url),
1469
-                'meta'   => array(
1470
-                    'title'  => __('Not Approved', 'event_espresso'),
1471
-                    'target' => '',
1472
-                    'class'  => $menu_class,
1473
-                ),
1474
-            ));
1475
-        }
1476
-        //Registration Overview This Month Cancelled
1477
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1478
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-cancelled')
1479
-        ) {
1480
-            $admin_bar->add_menu(array(
1481
-                'id'     => 'espresso-toolbar-registrations-month-cancelled',
1482
-                'parent' => 'espresso-toolbar-registrations-month',
1483
-                'title'  => __('Cancelled', 'event_espresso'),
1484
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1485
-                    'action'      => 'default',
1486
-                    'status'      => 'month',
1487
-                    '_reg_status' => EEM_Registration::status_id_cancelled,
1488
-                ), $reg_admin_url),
1489
-                'meta'   => array(
1490
-                    'title'  => __('Cancelled', 'event_espresso'),
1491
-                    'target' => '',
1492
-                    'class'  => $menu_class,
1493
-                ),
1494
-            ));
1495
-        }
1496
-        //Extensions & Services
1497
-        if ($this->registry->CAP->current_user_can('ee_read_ee',
1498
-            'ee_admin_bar_menu_espresso-toolbar-extensions-and-services')
1499
-        ) {
1500
-            $admin_bar->add_menu(array(
1501
-                'id'     => 'espresso-toolbar-extensions-and-services',
1502
-                'parent' => 'espresso-toolbar',
1503
-                'title'  => __('Extensions & Services', 'event_espresso'),
1504
-                'href'   => $extensions_admin_url,
1505
-                'meta'   => array(
1506
-                    'title'  => __('Extensions & Services', 'event_espresso'),
1507
-                    'target' => '',
1508
-                    'class'  => $menu_class,
1509
-                ),
1510
-            ));
1511
-        }
1512
-    }
1513
-
1514
-
1515
-
1516
-    /**
1517
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1518
-     * never returned with the function.
1519
-     *
1520
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1521
-     * @return array
1522
-     */
1523
-    public function remove_pages_from_wp_list_pages($exclude_array)
1524
-    {
1525
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1526
-    }
27
+	/**
28
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
29
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
30
+	 */
31
+	const req_type_normal = 0;
32
+
33
+	/**
34
+	 * Indicates this is a brand new installation of EE so we should install
35
+	 * tables and default data etc
36
+	 */
37
+	const req_type_new_activation = 1;
38
+
39
+	/**
40
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
41
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
42
+	 * and that default data is setup too
43
+	 */
44
+	const req_type_reactivation = 2;
45
+
46
+	/**
47
+	 * indicates that EE has been upgraded since its previous request.
48
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
49
+	 */
50
+	const req_type_upgrade = 3;
51
+
52
+	/**
53
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
54
+	 */
55
+	const req_type_downgrade = 4;
56
+
57
+	/**
58
+	 * @deprecated since version 4.6.0.dev.006
59
+	 * Now whenever a new_activation is detected the request type is still just
60
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
61
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
62
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
63
+	 * (Specifically, when the migration manager indicates migrations are finished
64
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
65
+	 */
66
+	const req_type_activation_but_not_installed = 5;
67
+
68
+	/**
69
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
70
+	 */
71
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
72
+
73
+
74
+	/**
75
+	 * @var EE_System $_instance
76
+	 */
77
+	private static $_instance;
78
+
79
+	/**
80
+	 * @var EE_Registry $registry
81
+	 */
82
+	protected $registry;
83
+
84
+	/**
85
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
86
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
87
+	 *
88
+	 * @var int $_req_type
89
+	 */
90
+	private $_req_type;
91
+
92
+	/**
93
+	 * Whether or not there was a non-micro version change in EE core version during this request
94
+	 *
95
+	 * @var boolean $_major_version_change
96
+	 */
97
+	private $_major_version_change = false;
98
+
99
+
100
+
101
+	/**
102
+	 * @singleton method used to instantiate class object
103
+	 * @access    public
104
+	 * @param  EE_Registry $Registry
105
+	 * @return EE_System
106
+	 */
107
+	public static function instance(EE_Registry $Registry = null)
108
+	{
109
+		// check if class object is instantiated
110
+		if ( ! self::$_instance instanceof EE_System) {
111
+			self::$_instance = new self($Registry);
112
+		}
113
+		return self::$_instance;
114
+	}
115
+
116
+
117
+
118
+	/**
119
+	 * resets the instance and returns it
120
+	 *
121
+	 * @return EE_System
122
+	 */
123
+	public static function reset()
124
+	{
125
+		self::$_instance->_req_type = null;
126
+		//make sure none of the old hooks are left hanging around
127
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
128
+		//we need to reset the migration manager in order for it to detect DMSs properly
129
+		EE_Data_Migration_Manager::reset();
130
+		self::instance()->detect_activations_or_upgrades();
131
+		self::instance()->perform_activations_upgrades_and_migrations();
132
+		return self::instance();
133
+	}
134
+
135
+
136
+
137
+	/**
138
+	 *    sets hooks for running rest of system
139
+	 *    provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
140
+	 *    starting EE Addons from any other point may lead to problems
141
+	 *
142
+	 * @access private
143
+	 * @param  EE_Registry $Registry
144
+	 */
145
+	private function __construct(EE_Registry $Registry)
146
+	{
147
+		$this->registry = $Registry;
148
+		do_action('AHEE__EE_System__construct__begin', $this);
149
+		add_action(
150
+			'AHEE__EE_Bootstrap__load_espresso_addons',
151
+			array($this, 'loadCapabilities'),
152
+			5
153
+		);
154
+		add_action(
155
+			'AHEE__EE_Bootstrap__load_espresso_addons',
156
+			array($this, 'loadCommandBus'),
157
+			7
158
+		);
159
+		add_action(
160
+			'AHEE__EE_Bootstrap__load_espresso_addons',
161
+			array($this, 'loadPluginApi'),
162
+			9
163
+		);
164
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
165
+		add_action(
166
+			'AHEE__EE_Bootstrap__load_espresso_addons',
167
+			array($this, 'load_espresso_addons')
168
+		);
169
+		// when an ee addon is activated, we want to call the core hook(s) again
170
+		// because the newly-activated addon didn't get a chance to run at all
171
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
172
+		// detect whether install or upgrade
173
+		add_action(
174
+			'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
175
+			array($this, 'detect_activations_or_upgrades'),
176
+			3
177
+		);
178
+		// load EE_Config, EE_Textdomain, etc
179
+		add_action(
180
+			'AHEE__EE_Bootstrap__load_core_configuration',
181
+			array($this, 'load_core_configuration'),
182
+			5
183
+		);
184
+		// load EE_Config, EE_Textdomain, etc
185
+		add_action(
186
+			'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
187
+			array($this, 'register_shortcodes_modules_and_widgets'),
188
+			7
189
+		);
190
+		// you wanna get going? I wanna get going... let's get going!
191
+		add_action(
192
+			'AHEE__EE_Bootstrap__brew_espresso',
193
+			array($this, 'brew_espresso'),
194
+			9
195
+		);
196
+		//other housekeeping
197
+		//exclude EE critical pages from wp_list_pages
198
+		add_filter(
199
+			'wp_list_pages_excludes',
200
+			array($this, 'remove_pages_from_wp_list_pages'),
201
+			10
202
+		);
203
+		// ALL EE Addons should use the following hook point to attach their initial setup too
204
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
205
+		do_action('AHEE__EE_System__construct__complete', $this);
206
+	}
207
+
208
+
209
+
210
+	/**
211
+	 * load and setup EE_Capabilities
212
+	 *
213
+	 * @return void
214
+	 * @throws EE_Error
215
+	 */
216
+	public function loadCapabilities()
217
+	{
218
+		$this->registry->load_core('EE_Capabilities');
219
+		add_action(
220
+			'AHEE__EE_Capabilities__init_caps__before_initialization',
221
+			function() {
222
+				EE_Registry::instance()->load_lib('Payment_Method_Manager');
223
+			}
224
+		);
225
+	}
226
+
227
+
228
+
229
+	/**
230
+	 * create and cache the CommandBus, and also add middleware
231
+	 * The CapChecker middleware requires the use of EE_Capabilities
232
+	 * which is why we need to load the CommandBus after Caps are set up
233
+	 *
234
+	 * @return void
235
+	 * @throws EE_Error
236
+	 */
237
+	public function loadCommandBus()
238
+	{
239
+		$this->registry->create(
240
+			'CommandBusInterface',
241
+			array(
242
+				null,
243
+				apply_filters(
244
+					'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
245
+					array(
246
+						$this->registry->create('CapChecker'),
247
+						$this->registry->create('AddActionHook'),
248
+					)
249
+				),
250
+			),
251
+			true
252
+		);
253
+	}
254
+
255
+
256
+
257
+	/**
258
+	 * @return void
259
+	 * @throws EE_Error
260
+	 */
261
+	public function loadPluginApi()
262
+	{
263
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
264
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
265
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
266
+	}
267
+
268
+
269
+
270
+	/**
271
+	 * load_espresso_addons
272
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
273
+	 * this is hooked into both:
274
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
275
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
276
+	 *    and the WP 'activate_plugin' hook point
277
+	 *
278
+	 * @access public
279
+	 * @return void
280
+	 * @throws EE_Error
281
+	 */
282
+	public function load_espresso_addons()
283
+	{
284
+		do_action('AHEE__EE_System__load_espresso_addons');
285
+		//if the WP API basic auth plugin isn't already loaded, load it now.
286
+		//We want it for mobile apps. Just include the entire plugin
287
+		//also, don't load the basic auth when a plugin is getting activated, because
288
+		//it could be the basic auth plugin, and it doesn't check if its methods are already defined
289
+		//and causes a fatal error
290
+		if (
291
+			! (isset($_GET['activate']) && $_GET['activate'] === 'true')
292
+			&& ! function_exists('json_basic_auth_handler')
293
+			&& ! function_exists('json_basic_auth_error')
294
+			&& ! (
295
+				isset($_GET['action'])
296
+				&& in_array($_GET['action'], array('activate', 'activate-selected'), true)
297
+			)
298
+		) {
299
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
300
+		}
301
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
302
+	}
303
+
304
+
305
+
306
+	/**
307
+	 * detect_activations_or_upgrades
308
+	 * Checks for activation or upgrade of core first;
309
+	 * then also checks if any registered addons have been activated or upgraded
310
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
311
+	 * which runs during the WP 'plugins_loaded' action at priority 3
312
+	 *
313
+	 * @access public
314
+	 * @return void
315
+	 */
316
+	public function detect_activations_or_upgrades()
317
+	{
318
+		//first off: let's make sure to handle core
319
+		$this->detect_if_activation_or_upgrade();
320
+		foreach ($this->registry->addons as $addon) {
321
+			//detect teh request type for that addon
322
+			$addon->detect_activation_or_upgrade();
323
+		}
324
+	}
325
+
326
+
327
+
328
+	/**
329
+	 * detect_if_activation_or_upgrade
330
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
331
+	 * and either setting up the DB or setting up maintenance mode etc.
332
+	 *
333
+	 * @access public
334
+	 * @return void
335
+	 */
336
+	public function detect_if_activation_or_upgrade()
337
+	{
338
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
339
+		// load M-Mode class
340
+		$this->registry->load_core('Maintenance_Mode');
341
+		// check if db has been updated, or if its a brand-new installation
342
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
343
+		$request_type = $this->detect_req_type($espresso_db_update);
344
+		//EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
345
+		switch ($request_type) {
346
+			case EE_System::req_type_new_activation:
347
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
348
+				$this->_handle_core_version_change($espresso_db_update);
349
+				break;
350
+			case EE_System::req_type_reactivation:
351
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
352
+				$this->_handle_core_version_change($espresso_db_update);
353
+				break;
354
+			case EE_System::req_type_upgrade:
355
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
356
+				//migrations may be required now that we've upgraded
357
+				EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
358
+				$this->_handle_core_version_change($espresso_db_update);
359
+				//				echo "done upgrade";die;
360
+				break;
361
+			case EE_System::req_type_downgrade:
362
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
363
+				//its possible migrations are no longer required
364
+				EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
365
+				$this->_handle_core_version_change($espresso_db_update);
366
+				break;
367
+			case EE_System::req_type_normal:
368
+			default:
369
+				//				$this->_maybe_redirect_to_ee_about();
370
+				break;
371
+		}
372
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
373
+	}
374
+
375
+
376
+
377
+	/**
378
+	 * Updates the list of installed versions and sets hooks for
379
+	 * initializing the database later during the request
380
+	 *
381
+	 * @param array $espresso_db_update
382
+	 */
383
+	protected function _handle_core_version_change($espresso_db_update)
384
+	{
385
+		$this->update_list_of_installed_versions($espresso_db_update);
386
+		//get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
387
+		add_action('AHEE__EE_System__perform_activations_upgrades_and_migrations',
388
+			array($this, 'initialize_db_if_no_migrations_required'));
389
+	}
390
+
391
+
392
+
393
+	/**
394
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
395
+	 * information about what versions of EE have been installed and activated,
396
+	 * NOT necessarily the state of the database
397
+	 *
398
+	 * @param mixed $espresso_db_update the value of the WordPress option.
399
+	 *                                            If not supplied, fetches it from the options table
400
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
401
+	 */
402
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
403
+	{
404
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
405
+		if ( ! $espresso_db_update) {
406
+			$espresso_db_update = get_option('espresso_db_update');
407
+		}
408
+		// check that option is an array
409
+		if ( ! is_array($espresso_db_update)) {
410
+			// if option is FALSE, then it never existed
411
+			if ($espresso_db_update === false) {
412
+				// make $espresso_db_update an array and save option with autoload OFF
413
+				$espresso_db_update = array();
414
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
415
+			} else {
416
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
417
+				$espresso_db_update = array($espresso_db_update => array());
418
+				update_option('espresso_db_update', $espresso_db_update);
419
+			}
420
+		} else {
421
+			$corrected_db_update = array();
422
+			//if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
423
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
424
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
425
+					//the key is an int, and the value IS NOT an array
426
+					//so it must be numerically-indexed, where values are versions installed...
427
+					//fix it!
428
+					$version_string = $should_be_array;
429
+					$corrected_db_update[$version_string] = array('unknown-date');
430
+				} else {
431
+					//ok it checks out
432
+					$corrected_db_update[$should_be_version_string] = $should_be_array;
433
+				}
434
+			}
435
+			$espresso_db_update = $corrected_db_update;
436
+			update_option('espresso_db_update', $espresso_db_update);
437
+		}
438
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
439
+		return $espresso_db_update;
440
+	}
441
+
442
+
443
+
444
+	/**
445
+	 * Does the traditional work of setting up the plugin's database and adding default data.
446
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
447
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
448
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
449
+	 * so that it will be done when migrations are finished
450
+	 *
451
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
452
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
453
+	 *                                       This is a resource-intensive job
454
+	 *                                       so we prefer to only do it when necessary
455
+	 * @return void
456
+	 * @throws EE_Error
457
+	 */
458
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
459
+	{
460
+		$request_type = $this->detect_req_type();
461
+		//only initialize system if we're not in maintenance mode.
462
+		if (EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
463
+			update_option('ee_flush_rewrite_rules', true);
464
+			if ($verify_schema) {
465
+				EEH_Activation::initialize_db_and_folders();
466
+			}
467
+			EEH_Activation::initialize_db_content();
468
+			EEH_Activation::system_initialization();
469
+			if ($initialize_addons_too) {
470
+				$this->initialize_addons();
471
+			}
472
+		} else {
473
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
474
+		}
475
+		if ($request_type === EE_System::req_type_new_activation
476
+			|| $request_type === EE_System::req_type_reactivation
477
+			|| (
478
+				$request_type === EE_System::req_type_upgrade
479
+				&& $this->is_major_version_change()
480
+			)
481
+		) {
482
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
483
+		}
484
+	}
485
+
486
+
487
+
488
+	/**
489
+	 * Initializes the db for all registered addons
490
+	 *
491
+	 * @throws EE_Error
492
+	 */
493
+	public function initialize_addons()
494
+	{
495
+		//foreach registered addon, make sure its db is up-to-date too
496
+		foreach ($this->registry->addons as $addon) {
497
+			$addon->initialize_db_if_no_migrations_required();
498
+		}
499
+	}
500
+
501
+
502
+
503
+	/**
504
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
505
+	 *
506
+	 * @param    array  $version_history
507
+	 * @param    string $current_version_to_add version to be added to the version history
508
+	 * @return    boolean success as to whether or not this option was changed
509
+	 */
510
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
511
+	{
512
+		if ( ! $version_history) {
513
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
514
+		}
515
+		if ($current_version_to_add === null) {
516
+			$current_version_to_add = espresso_version();
517
+		}
518
+		$version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
519
+		// re-save
520
+		return update_option('espresso_db_update', $version_history);
521
+	}
522
+
523
+
524
+
525
+	/**
526
+	 * Detects if the current version indicated in the has existed in the list of
527
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
528
+	 *
529
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
530
+	 *                                  If not supplied, fetches it from the options table.
531
+	 *                                  Also, caches its result so later parts of the code can also know whether
532
+	 *                                  there's been an update or not. This way we can add the current version to
533
+	 *                                  espresso_db_update, but still know if this is a new install or not
534
+	 * @return int one of the constants on EE_System::req_type_
535
+	 */
536
+	public function detect_req_type($espresso_db_update = null)
537
+	{
538
+		if ($this->_req_type === null) {
539
+			$espresso_db_update = ! empty($espresso_db_update) ? $espresso_db_update
540
+				: $this->fix_espresso_db_upgrade_option();
541
+			$this->_req_type = EE_System::detect_req_type_given_activation_history($espresso_db_update,
542
+				'ee_espresso_activation', espresso_version());
543
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
544
+		}
545
+		return $this->_req_type;
546
+	}
547
+
548
+
549
+
550
+	/**
551
+	 * Returns whether or not there was a non-micro version change (ie, change in either
552
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
553
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
554
+	 *
555
+	 * @param $activation_history
556
+	 * @return bool
557
+	 */
558
+	protected function _detect_major_version_change($activation_history)
559
+	{
560
+		$previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
561
+		$previous_version_parts = explode('.', $previous_version);
562
+		$current_version_parts = explode('.', espresso_version());
563
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
564
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
565
+				   || $previous_version_parts[1] !== $current_version_parts[1]
566
+			   );
567
+	}
568
+
569
+
570
+
571
+	/**
572
+	 * Returns true if either the major or minor version of EE changed during this request.
573
+	 * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
574
+	 *
575
+	 * @return bool
576
+	 */
577
+	public function is_major_version_change()
578
+	{
579
+		return $this->_major_version_change;
580
+	}
581
+
582
+
583
+
584
+	/**
585
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
586
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
587
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
588
+	 * just activated to (for core that will always be espresso_version())
589
+	 *
590
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
591
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
592
+	 * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
593
+	 *                                                 indicate that this plugin was just activated
594
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
595
+	 *                                                 espresso_version())
596
+	 * @return int one of the constants on EE_System::req_type_*
597
+	 */
598
+	public static function detect_req_type_given_activation_history(
599
+		$activation_history_for_addon,
600
+		$activation_indicator_option_name,
601
+		$version_to_upgrade_to
602
+	) {
603
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
604
+		if ($activation_history_for_addon) {
605
+			//it exists, so this isn't a completely new install
606
+			//check if this version already in that list of previously installed versions
607
+			if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
608
+				//it a version we haven't seen before
609
+				if ($version_is_higher === 1) {
610
+					$req_type = EE_System::req_type_upgrade;
611
+				} else {
612
+					$req_type = EE_System::req_type_downgrade;
613
+				}
614
+				delete_option($activation_indicator_option_name);
615
+			} else {
616
+				// its not an update. maybe a reactivation?
617
+				if (get_option($activation_indicator_option_name, false)) {
618
+					if ($version_is_higher === -1) {
619
+						$req_type = EE_System::req_type_downgrade;
620
+					} elseif ($version_is_higher === 0) {
621
+						//we've seen this version before, but it's an activation. must be a reactivation
622
+						$req_type = EE_System::req_type_reactivation;
623
+					} else {//$version_is_higher === 1
624
+						$req_type = EE_System::req_type_upgrade;
625
+					}
626
+					delete_option($activation_indicator_option_name);
627
+				} else {
628
+					//we've seen this version before and the activation indicate doesn't show it was just activated
629
+					if ($version_is_higher === -1) {
630
+						$req_type = EE_System::req_type_downgrade;
631
+					} elseif ($version_is_higher === 0) {
632
+						//we've seen this version before and it's not an activation. its normal request
633
+						$req_type = EE_System::req_type_normal;
634
+					} else {//$version_is_higher === 1
635
+						$req_type = EE_System::req_type_upgrade;
636
+					}
637
+				}
638
+			}
639
+		} else {
640
+			//brand new install
641
+			$req_type = EE_System::req_type_new_activation;
642
+			delete_option($activation_indicator_option_name);
643
+		}
644
+		return $req_type;
645
+	}
646
+
647
+
648
+
649
+	/**
650
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
651
+	 * the $activation_history_for_addon
652
+	 *
653
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
654
+	 *                                             sometimes containing 'unknown-date'
655
+	 * @param string $version_to_upgrade_to        (current version)
656
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
657
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
658
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
659
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
660
+	 */
661
+	protected static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
662
+	{
663
+		//find the most recently-activated version
664
+		$most_recently_active_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
665
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
666
+	}
667
+
668
+
669
+
670
+	/**
671
+	 * Gets the most recently active version listed in the activation history,
672
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
673
+	 *
674
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
675
+	 *                                   sometimes containing 'unknown-date'
676
+	 * @return string
677
+	 */
678
+	protected static function _get_most_recently_active_version_from_activation_history($activation_history)
679
+	{
680
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
681
+		$most_recently_active_version = '0.0.0.dev.000';
682
+		if (is_array($activation_history)) {
683
+			foreach ($activation_history as $version => $times_activated) {
684
+				//check there is a record of when this version was activated. Otherwise,
685
+				//mark it as unknown
686
+				if ( ! $times_activated) {
687
+					$times_activated = array('unknown-date');
688
+				}
689
+				if (is_string($times_activated)) {
690
+					$times_activated = array($times_activated);
691
+				}
692
+				foreach ($times_activated as $an_activation) {
693
+					if ($an_activation !== 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
694
+						$most_recently_active_version = $version;
695
+						$most_recently_active_version_activation = $an_activation === 'unknown-date'
696
+							? '1970-01-01 00:00:00' : $an_activation;
697
+					}
698
+				}
699
+			}
700
+		}
701
+		return $most_recently_active_version;
702
+	}
703
+
704
+
705
+
706
+	/**
707
+	 * This redirects to the about EE page after activation
708
+	 *
709
+	 * @return void
710
+	 */
711
+	public function redirect_to_about_ee()
712
+	{
713
+		$notices = EE_Error::get_notices(false);
714
+		//if current user is an admin and it's not an ajax or rest request
715
+		if (
716
+			! (defined('DOING_AJAX') && DOING_AJAX)
717
+			&& ! (defined('REST_REQUEST') && REST_REQUEST)
718
+			&& ! isset($notices['errors'])
719
+			&& apply_filters(
720
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
721
+				$this->registry->CAP->current_user_can('manage_options', 'espresso_about_default')
722
+			)
723
+		) {
724
+			$query_params = array('page' => 'espresso_about');
725
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
726
+				$query_params['new_activation'] = true;
727
+			}
728
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
729
+				$query_params['reactivation'] = true;
730
+			}
731
+			$url = add_query_arg($query_params, admin_url('admin.php'));
732
+			wp_safe_redirect($url);
733
+			exit();
734
+		}
735
+	}
736
+
737
+
738
+
739
+	/**
740
+	 * load_core_configuration
741
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
742
+	 * which runs during the WP 'plugins_loaded' action at priority 5
743
+	 *
744
+	 * @return void
745
+	 * @throws \ReflectionException
746
+	 */
747
+	public function load_core_configuration()
748
+	{
749
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
750
+		$this->registry->load_core('EE_Load_Textdomain');
751
+		//load textdomain
752
+		EE_Load_Textdomain::load_textdomain();
753
+		// load and setup EE_Config and EE_Network_Config
754
+		$this->registry->load_core('Config');
755
+		$this->registry->load_core('Network_Config');
756
+		// setup autoloaders
757
+		// enable logging?
758
+		if ($this->registry->CFG->admin->use_full_logging) {
759
+			$this->registry->load_core('Log');
760
+		}
761
+		// check for activation errors
762
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
763
+		if ($activation_errors) {
764
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
765
+			update_option('ee_plugin_activation_errors', false);
766
+		}
767
+		// get model names
768
+		$this->_parse_model_names();
769
+		//load caf stuff a chance to play during the activation process too.
770
+		$this->_maybe_brew_regular();
771
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
772
+	}
773
+
774
+
775
+
776
+	/**
777
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
778
+	 *
779
+	 * @return void
780
+	 * @throws ReflectionException
781
+	 */
782
+	private function _parse_model_names()
783
+	{
784
+		//get all the files in the EE_MODELS folder that end in .model.php
785
+		$models = glob(EE_MODELS . '*.model.php');
786
+		$model_names = array();
787
+		$non_abstract_db_models = array();
788
+		foreach ($models as $model) {
789
+			// get model classname
790
+			$classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
791
+			$short_name = str_replace('EEM_', '', $classname);
792
+			$reflectionClass = new ReflectionClass($classname);
793
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
794
+				$non_abstract_db_models[$short_name] = $classname;
795
+			}
796
+			$model_names[$short_name] = $classname;
797
+		}
798
+		$this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
799
+		$this->registry->non_abstract_db_models = apply_filters('FHEE__EE_System__parse_implemented_model_names',
800
+			$non_abstract_db_models);
801
+	}
802
+
803
+
804
+
805
+	/**
806
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
807
+	 * that need to be setup before our EE_System launches.
808
+	 *
809
+	 * @return void
810
+	 */
811
+	private function _maybe_brew_regular()
812
+	{
813
+		if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
814
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
815
+		}
816
+	}
817
+
818
+
819
+
820
+	/**
821
+	 * register_shortcodes_modules_and_widgets
822
+	 * generate lists of shortcodes and modules, then verify paths and classes
823
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
824
+	 * which runs during the WP 'plugins_loaded' action at priority 7
825
+	 *
826
+	 * @access public
827
+	 * @return void
828
+	 */
829
+	public function register_shortcodes_modules_and_widgets()
830
+	{
831
+		try {
832
+			// load, register, and add shortcodes the new way
833
+			LoaderFactory::getLoader()->getShared(
834
+				'EventEspresso\core\services\shortcodes\ShortcodesManager',
835
+				array(
836
+					// and the old way, but we'll put it under control of the new system
837
+					EE_Config::getLegacyShortcodesManager()
838
+				)
839
+			);
840
+		} catch (Exception $exception) {
841
+			new ExceptionStackTraceDisplay($exception);
842
+		}
843
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
844
+		// check for addons using old hook point
845
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
846
+			$this->_incompatible_addon_error();
847
+		}
848
+	}
849
+
850
+
851
+
852
+	/**
853
+	 * _incompatible_addon_error
854
+	 *
855
+	 * @access public
856
+	 * @return void
857
+	 */
858
+	private function _incompatible_addon_error()
859
+	{
860
+		// get array of classes hooking into here
861
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook('AHEE__EE_System__register_shortcodes_modules_and_addons');
862
+		if ( ! empty($class_names)) {
863
+			$msg = __('The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
864
+				'event_espresso');
865
+			$msg .= '<ul>';
866
+			foreach ($class_names as $class_name) {
867
+				$msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
868
+						$class_name) . '</b></li>';
869
+			}
870
+			$msg .= '</ul>';
871
+			$msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
872
+				'event_espresso');
873
+			// save list of incompatible addons to wp-options for later use
874
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
875
+			if (is_admin()) {
876
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
877
+			}
878
+		}
879
+	}
880
+
881
+
882
+
883
+	/**
884
+	 * brew_espresso
885
+	 * begins the process of setting hooks for initializing EE in the correct order
886
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
887
+	 * which runs during the WP 'plugins_loaded' action at priority 9
888
+	 *
889
+	 * @return void
890
+	 */
891
+	public function brew_espresso()
892
+	{
893
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
894
+		// load some final core systems
895
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
896
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
897
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
898
+		add_action('init', array($this, 'load_controllers'), 7);
899
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
900
+		add_action('init', array($this, 'initialize'), 10);
901
+		add_action('init', array($this, 'initialize_last'), 100);
902
+		add_action('admin_bar_menu', array($this, 'espresso_toolbar_items'), 100);
903
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
904
+			// pew pew pew
905
+			$this->registry->load_core('PUE');
906
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
907
+		}
908
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
909
+	}
910
+
911
+
912
+
913
+	/**
914
+	 *    set_hooks_for_core
915
+	 *
916
+	 * @access public
917
+	 * @return    void
918
+	 * @throws EE_Error
919
+	 */
920
+	public function set_hooks_for_core()
921
+	{
922
+		$this->_deactivate_incompatible_addons();
923
+		do_action('AHEE__EE_System__set_hooks_for_core');
924
+		//caps need to be initialized on every request so that capability maps are set.
925
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
926
+		$this->registry->CAP->init_caps();
927
+	}
928
+
929
+
930
+
931
+	/**
932
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
933
+	 * deactivates any addons considered incompatible with the current version of EE
934
+	 */
935
+	private function _deactivate_incompatible_addons()
936
+	{
937
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
938
+		if ( ! empty($incompatible_addons)) {
939
+			$active_plugins = get_option('active_plugins', array());
940
+			foreach ($active_plugins as $active_plugin) {
941
+				foreach ($incompatible_addons as $incompatible_addon) {
942
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
943
+						unset($_GET['activate']);
944
+						espresso_deactivate_plugin($active_plugin);
945
+					}
946
+				}
947
+			}
948
+		}
949
+	}
950
+
951
+
952
+
953
+	/**
954
+	 *    perform_activations_upgrades_and_migrations
955
+	 *
956
+	 * @access public
957
+	 * @return    void
958
+	 */
959
+	public function perform_activations_upgrades_and_migrations()
960
+	{
961
+		//first check if we had previously attempted to setup EE's directories but failed
962
+		if (EEH_Activation::upload_directories_incomplete()) {
963
+			EEH_Activation::create_upload_directories();
964
+		}
965
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
966
+	}
967
+
968
+
969
+
970
+	/**
971
+	 *    load_CPTs_and_session
972
+	 *
973
+	 * @access public
974
+	 * @return    void
975
+	 */
976
+	public function load_CPTs_and_session()
977
+	{
978
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
979
+		// register Custom Post Types
980
+		$this->registry->load_core('Register_CPTs');
981
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
982
+	}
983
+
984
+
985
+
986
+	/**
987
+	 * load_controllers
988
+	 * this is the best place to load any additional controllers that needs access to EE core.
989
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
990
+	 * time
991
+	 *
992
+	 * @access public
993
+	 * @return void
994
+	 */
995
+	public function load_controllers()
996
+	{
997
+		do_action('AHEE__EE_System__load_controllers__start');
998
+		// let's get it started
999
+		if ( ! is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
1000
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1001
+			$this->registry->load_core('Front_Controller');
1002
+		} else if ( ! EE_FRONT_AJAX) {
1003
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1004
+			EE_Registry::instance()->load_core('Admin');
1005
+		}
1006
+		do_action('AHEE__EE_System__load_controllers__complete');
1007
+	}
1008
+
1009
+
1010
+
1011
+	/**
1012
+	 * core_loaded_and_ready
1013
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1014
+	 *
1015
+	 * @access public
1016
+	 * @return void
1017
+	 */
1018
+	public function core_loaded_and_ready()
1019
+	{
1020
+		$this->registry->load_core('Session');
1021
+		do_action('AHEE__EE_System__core_loaded_and_ready');
1022
+		// load_espresso_template_tags
1023
+		if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1024
+			require_once(EE_PUBLIC . 'template_tags.php');
1025
+		}
1026
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1027
+		$this->registry->create('EventEspresso\core\services\assets\Registry', array(), true);
1028
+	}
1029
+
1030
+
1031
+
1032
+	/**
1033
+	 * initialize
1034
+	 * this is the best place to begin initializing client code
1035
+	 *
1036
+	 * @access public
1037
+	 * @return void
1038
+	 */
1039
+	public function initialize()
1040
+	{
1041
+		do_action('AHEE__EE_System__initialize');
1042
+	}
1043
+
1044
+
1045
+
1046
+	/**
1047
+	 * initialize_last
1048
+	 * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1049
+	 * initialize has done so
1050
+	 *
1051
+	 * @access public
1052
+	 * @return void
1053
+	 */
1054
+	public function initialize_last()
1055
+	{
1056
+		do_action('AHEE__EE_System__initialize_last');
1057
+	}
1058
+
1059
+
1060
+
1061
+	/**
1062
+	 * set_hooks_for_shortcodes_modules_and_addons
1063
+	 * this is the best place for other systems to set callbacks for hooking into other parts of EE
1064
+	 * this happens at the very beginning of the wp_loaded hook point
1065
+	 *
1066
+	 * @access public
1067
+	 * @return void
1068
+	 */
1069
+	public function set_hooks_for_shortcodes_modules_and_addons()
1070
+	{
1071
+		//		do_action( 'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons' );
1072
+	}
1073
+
1074
+
1075
+
1076
+	/**
1077
+	 * do_not_cache
1078
+	 * sets no cache headers and defines no cache constants for WP plugins
1079
+	 *
1080
+	 * @access public
1081
+	 * @return void
1082
+	 */
1083
+	public static function do_not_cache()
1084
+	{
1085
+		// set no cache constants
1086
+		if ( ! defined('DONOTCACHEPAGE')) {
1087
+			define('DONOTCACHEPAGE', true);
1088
+		}
1089
+		if ( ! defined('DONOTCACHCEOBJECT')) {
1090
+			define('DONOTCACHCEOBJECT', true);
1091
+		}
1092
+		if ( ! defined('DONOTCACHEDB')) {
1093
+			define('DONOTCACHEDB', true);
1094
+		}
1095
+		// add no cache headers
1096
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1097
+		// plus a little extra for nginx and Google Chrome
1098
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1099
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1100
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1101
+	}
1102
+
1103
+
1104
+
1105
+	/**
1106
+	 *    extra_nocache_headers
1107
+	 *
1108
+	 * @access    public
1109
+	 * @param $headers
1110
+	 * @return    array
1111
+	 */
1112
+	public static function extra_nocache_headers($headers)
1113
+	{
1114
+		// for NGINX
1115
+		$headers['X-Accel-Expires'] = 0;
1116
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1117
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1118
+		return $headers;
1119
+	}
1120
+
1121
+
1122
+
1123
+	/**
1124
+	 *    nocache_headers
1125
+	 *
1126
+	 * @access    public
1127
+	 * @return    void
1128
+	 */
1129
+	public static function nocache_headers()
1130
+	{
1131
+		nocache_headers();
1132
+	}
1133
+
1134
+
1135
+
1136
+	/**
1137
+	 *    espresso_toolbar_items
1138
+	 *
1139
+	 * @access public
1140
+	 * @param  WP_Admin_Bar $admin_bar
1141
+	 * @return void
1142
+	 */
1143
+	public function espresso_toolbar_items(WP_Admin_Bar $admin_bar)
1144
+	{
1145
+		// if in full M-Mode, or its an AJAX request, or user is NOT an admin
1146
+		if (
1147
+			defined('DOING_AJAX')
1148
+			|| ! $this->registry->CAP->current_user_can('ee_read_ee', 'ee_admin_bar_menu_top_level')
1149
+			|| EE_Maintenance_Mode::instance()->level() === EE_Maintenance_Mode::level_2_complete_maintenance
1150
+		) {
1151
+			return;
1152
+		}
1153
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1154
+		$menu_class = 'espresso_menu_item_class';
1155
+		//we don't use the constants EVENTS_ADMIN_URL or REG_ADMIN_URL
1156
+		//because they're only defined in each of their respective constructors
1157
+		//and this might be a frontend request, in which case they aren't available
1158
+		$events_admin_url = admin_url('admin.php?page=espresso_events');
1159
+		$reg_admin_url = admin_url('admin.php?page=espresso_registrations');
1160
+		$extensions_admin_url = admin_url('admin.php?page=espresso_packages');
1161
+		//Top Level
1162
+		$admin_bar->add_menu(array(
1163
+			'id'    => 'espresso-toolbar',
1164
+			'title' => '<span class="ee-icon ee-icon-ee-cup-thick ee-icon-size-20"></span><span class="ab-label">'
1165
+					   . _x('Event Espresso', 'admin bar menu group label', 'event_espresso')
1166
+					   . '</span>',
1167
+			'href'  => $events_admin_url,
1168
+			'meta'  => array(
1169
+				'title' => __('Event Espresso', 'event_espresso'),
1170
+				'class' => $menu_class . 'first',
1171
+			),
1172
+		));
1173
+		//Events
1174
+		if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events')) {
1175
+			$admin_bar->add_menu(array(
1176
+				'id'     => 'espresso-toolbar-events',
1177
+				'parent' => 'espresso-toolbar',
1178
+				'title'  => __('Events', 'event_espresso'),
1179
+				'href'   => $events_admin_url,
1180
+				'meta'   => array(
1181
+					'title'  => __('Events', 'event_espresso'),
1182
+					'target' => '',
1183
+					'class'  => $menu_class,
1184
+				),
1185
+			));
1186
+		}
1187
+		if ($this->registry->CAP->current_user_can('ee_edit_events', 'ee_admin_bar_menu_espresso-toolbar-events-new')) {
1188
+			//Events Add New
1189
+			$admin_bar->add_menu(array(
1190
+				'id'     => 'espresso-toolbar-events-new',
1191
+				'parent' => 'espresso-toolbar-events',
1192
+				'title'  => __('Add New', 'event_espresso'),
1193
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'create_new'), $events_admin_url),
1194
+				'meta'   => array(
1195
+					'title'  => __('Add New', 'event_espresso'),
1196
+					'target' => '',
1197
+					'class'  => $menu_class,
1198
+				),
1199
+			));
1200
+		}
1201
+		if (is_single() && (get_post_type() === 'espresso_events')) {
1202
+			//Current post
1203
+			global $post;
1204
+			if ($this->registry->CAP->current_user_can('ee_edit_event',
1205
+				'ee_admin_bar_menu_espresso-toolbar-events-edit', $post->ID)
1206
+			) {
1207
+				//Events Edit Current Event
1208
+				$admin_bar->add_menu(array(
1209
+					'id'     => 'espresso-toolbar-events-edit',
1210
+					'parent' => 'espresso-toolbar-events',
1211
+					'title'  => __('Edit Event', 'event_espresso'),
1212
+					'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'edit', 'post' => $post->ID),
1213
+						$events_admin_url),
1214
+					'meta'   => array(
1215
+						'title'  => __('Edit Event', 'event_espresso'),
1216
+						'target' => '',
1217
+						'class'  => $menu_class,
1218
+					),
1219
+				));
1220
+			}
1221
+		}
1222
+		//Events View
1223
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1224
+			'ee_admin_bar_menu_espresso-toolbar-events-view')
1225
+		) {
1226
+			$admin_bar->add_menu(array(
1227
+				'id'     => 'espresso-toolbar-events-view',
1228
+				'parent' => 'espresso-toolbar-events',
1229
+				'title'  => __('View', 'event_espresso'),
1230
+				'href'   => $events_admin_url,
1231
+				'meta'   => array(
1232
+					'title'  => __('View', 'event_espresso'),
1233
+					'target' => '',
1234
+					'class'  => $menu_class,
1235
+				),
1236
+			));
1237
+		}
1238
+		if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events-all')) {
1239
+			//Events View All
1240
+			$admin_bar->add_menu(array(
1241
+				'id'     => 'espresso-toolbar-events-all',
1242
+				'parent' => 'espresso-toolbar-events-view',
1243
+				'title'  => __('All', 'event_espresso'),
1244
+				'href'   => $events_admin_url,
1245
+				'meta'   => array(
1246
+					'title'  => __('All', 'event_espresso'),
1247
+					'target' => '',
1248
+					'class'  => $menu_class,
1249
+				),
1250
+			));
1251
+		}
1252
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1253
+			'ee_admin_bar_menu_espresso-toolbar-events-today')
1254
+		) {
1255
+			//Events View Today
1256
+			$admin_bar->add_menu(array(
1257
+				'id'     => 'espresso-toolbar-events-today',
1258
+				'parent' => 'espresso-toolbar-events-view',
1259
+				'title'  => __('Today', 'event_espresso'),
1260
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1261
+					$events_admin_url),
1262
+				'meta'   => array(
1263
+					'title'  => __('Today', 'event_espresso'),
1264
+					'target' => '',
1265
+					'class'  => $menu_class,
1266
+				),
1267
+			));
1268
+		}
1269
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1270
+			'ee_admin_bar_menu_espresso-toolbar-events-month')
1271
+		) {
1272
+			//Events View This Month
1273
+			$admin_bar->add_menu(array(
1274
+				'id'     => 'espresso-toolbar-events-month',
1275
+				'parent' => 'espresso-toolbar-events-view',
1276
+				'title'  => __('This Month', 'event_espresso'),
1277
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1278
+					$events_admin_url),
1279
+				'meta'   => array(
1280
+					'title'  => __('This Month', 'event_espresso'),
1281
+					'target' => '',
1282
+					'class'  => $menu_class,
1283
+				),
1284
+			));
1285
+		}
1286
+		//Registration Overview
1287
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1288
+			'ee_admin_bar_menu_espresso-toolbar-registrations')
1289
+		) {
1290
+			$admin_bar->add_menu(array(
1291
+				'id'     => 'espresso-toolbar-registrations',
1292
+				'parent' => 'espresso-toolbar',
1293
+				'title'  => __('Registrations', 'event_espresso'),
1294
+				'href'   => $reg_admin_url,
1295
+				'meta'   => array(
1296
+					'title'  => __('Registrations', 'event_espresso'),
1297
+					'target' => '',
1298
+					'class'  => $menu_class,
1299
+				),
1300
+			));
1301
+		}
1302
+		//Registration Overview Today
1303
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1304
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today')
1305
+		) {
1306
+			$admin_bar->add_menu(array(
1307
+				'id'     => 'espresso-toolbar-registrations-today',
1308
+				'parent' => 'espresso-toolbar-registrations',
1309
+				'title'  => __('Today', 'event_espresso'),
1310
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1311
+					$reg_admin_url),
1312
+				'meta'   => array(
1313
+					'title'  => __('Today', 'event_espresso'),
1314
+					'target' => '',
1315
+					'class'  => $menu_class,
1316
+				),
1317
+			));
1318
+		}
1319
+		//Registration Overview Today Completed
1320
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1321
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-approved')
1322
+		) {
1323
+			$admin_bar->add_menu(array(
1324
+				'id'     => 'espresso-toolbar-registrations-today-approved',
1325
+				'parent' => 'espresso-toolbar-registrations-today',
1326
+				'title'  => __('Approved', 'event_espresso'),
1327
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1328
+					'action'      => 'default',
1329
+					'status'      => 'today',
1330
+					'_reg_status' => EEM_Registration::status_id_approved,
1331
+				), $reg_admin_url),
1332
+				'meta'   => array(
1333
+					'title'  => __('Approved', 'event_espresso'),
1334
+					'target' => '',
1335
+					'class'  => $menu_class,
1336
+				),
1337
+			));
1338
+		}
1339
+		//Registration Overview Today Pending\
1340
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1341
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-pending')
1342
+		) {
1343
+			$admin_bar->add_menu(array(
1344
+				'id'     => 'espresso-toolbar-registrations-today-pending',
1345
+				'parent' => 'espresso-toolbar-registrations-today',
1346
+				'title'  => __('Pending', 'event_espresso'),
1347
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1348
+					'action'     => 'default',
1349
+					'status'     => 'today',
1350
+					'reg_status' => EEM_Registration::status_id_pending_payment,
1351
+				), $reg_admin_url),
1352
+				'meta'   => array(
1353
+					'title'  => __('Pending Payment', 'event_espresso'),
1354
+					'target' => '',
1355
+					'class'  => $menu_class,
1356
+				),
1357
+			));
1358
+		}
1359
+		//Registration Overview Today Incomplete
1360
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1361
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-not-approved')
1362
+		) {
1363
+			$admin_bar->add_menu(array(
1364
+				'id'     => 'espresso-toolbar-registrations-today-not-approved',
1365
+				'parent' => 'espresso-toolbar-registrations-today',
1366
+				'title'  => __('Not Approved', 'event_espresso'),
1367
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1368
+					'action'      => 'default',
1369
+					'status'      => 'today',
1370
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1371
+				), $reg_admin_url),
1372
+				'meta'   => array(
1373
+					'title'  => __('Not Approved', 'event_espresso'),
1374
+					'target' => '',
1375
+					'class'  => $menu_class,
1376
+				),
1377
+			));
1378
+		}
1379
+		//Registration Overview Today Incomplete
1380
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1381
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-cancelled')
1382
+		) {
1383
+			$admin_bar->add_menu(array(
1384
+				'id'     => 'espresso-toolbar-registrations-today-cancelled',
1385
+				'parent' => 'espresso-toolbar-registrations-today',
1386
+				'title'  => __('Cancelled', 'event_espresso'),
1387
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1388
+					'action'      => 'default',
1389
+					'status'      => 'today',
1390
+					'_reg_status' => EEM_Registration::status_id_cancelled,
1391
+				), $reg_admin_url),
1392
+				'meta'   => array(
1393
+					'title'  => __('Cancelled', 'event_espresso'),
1394
+					'target' => '',
1395
+					'class'  => $menu_class,
1396
+				),
1397
+			));
1398
+		}
1399
+		//Registration Overview This Month
1400
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1401
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month')
1402
+		) {
1403
+			$admin_bar->add_menu(array(
1404
+				'id'     => 'espresso-toolbar-registrations-month',
1405
+				'parent' => 'espresso-toolbar-registrations',
1406
+				'title'  => __('This Month', 'event_espresso'),
1407
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1408
+					$reg_admin_url),
1409
+				'meta'   => array(
1410
+					'title'  => __('This Month', 'event_espresso'),
1411
+					'target' => '',
1412
+					'class'  => $menu_class,
1413
+				),
1414
+			));
1415
+		}
1416
+		//Registration Overview This Month Approved
1417
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1418
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-approved')
1419
+		) {
1420
+			$admin_bar->add_menu(array(
1421
+				'id'     => 'espresso-toolbar-registrations-month-approved',
1422
+				'parent' => 'espresso-toolbar-registrations-month',
1423
+				'title'  => __('Approved', 'event_espresso'),
1424
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1425
+					'action'      => 'default',
1426
+					'status'      => 'month',
1427
+					'_reg_status' => EEM_Registration::status_id_approved,
1428
+				), $reg_admin_url),
1429
+				'meta'   => array(
1430
+					'title'  => __('Approved', 'event_espresso'),
1431
+					'target' => '',
1432
+					'class'  => $menu_class,
1433
+				),
1434
+			));
1435
+		}
1436
+		//Registration Overview This Month Pending
1437
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1438
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-pending')
1439
+		) {
1440
+			$admin_bar->add_menu(array(
1441
+				'id'     => 'espresso-toolbar-registrations-month-pending',
1442
+				'parent' => 'espresso-toolbar-registrations-month',
1443
+				'title'  => __('Pending', 'event_espresso'),
1444
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1445
+					'action'      => 'default',
1446
+					'status'      => 'month',
1447
+					'_reg_status' => EEM_Registration::status_id_pending_payment,
1448
+				), $reg_admin_url),
1449
+				'meta'   => array(
1450
+					'title'  => __('Pending', 'event_espresso'),
1451
+					'target' => '',
1452
+					'class'  => $menu_class,
1453
+				),
1454
+			));
1455
+		}
1456
+		//Registration Overview This Month Not Approved
1457
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1458
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-not-approved')
1459
+		) {
1460
+			$admin_bar->add_menu(array(
1461
+				'id'     => 'espresso-toolbar-registrations-month-not-approved',
1462
+				'parent' => 'espresso-toolbar-registrations-month',
1463
+				'title'  => __('Not Approved', 'event_espresso'),
1464
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1465
+					'action'      => 'default',
1466
+					'status'      => 'month',
1467
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1468
+				), $reg_admin_url),
1469
+				'meta'   => array(
1470
+					'title'  => __('Not Approved', 'event_espresso'),
1471
+					'target' => '',
1472
+					'class'  => $menu_class,
1473
+				),
1474
+			));
1475
+		}
1476
+		//Registration Overview This Month Cancelled
1477
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1478
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-cancelled')
1479
+		) {
1480
+			$admin_bar->add_menu(array(
1481
+				'id'     => 'espresso-toolbar-registrations-month-cancelled',
1482
+				'parent' => 'espresso-toolbar-registrations-month',
1483
+				'title'  => __('Cancelled', 'event_espresso'),
1484
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1485
+					'action'      => 'default',
1486
+					'status'      => 'month',
1487
+					'_reg_status' => EEM_Registration::status_id_cancelled,
1488
+				), $reg_admin_url),
1489
+				'meta'   => array(
1490
+					'title'  => __('Cancelled', 'event_espresso'),
1491
+					'target' => '',
1492
+					'class'  => $menu_class,
1493
+				),
1494
+			));
1495
+		}
1496
+		//Extensions & Services
1497
+		if ($this->registry->CAP->current_user_can('ee_read_ee',
1498
+			'ee_admin_bar_menu_espresso-toolbar-extensions-and-services')
1499
+		) {
1500
+			$admin_bar->add_menu(array(
1501
+				'id'     => 'espresso-toolbar-extensions-and-services',
1502
+				'parent' => 'espresso-toolbar',
1503
+				'title'  => __('Extensions & Services', 'event_espresso'),
1504
+				'href'   => $extensions_admin_url,
1505
+				'meta'   => array(
1506
+					'title'  => __('Extensions & Services', 'event_espresso'),
1507
+					'target' => '',
1508
+					'class'  => $menu_class,
1509
+				),
1510
+			));
1511
+		}
1512
+	}
1513
+
1514
+
1515
+
1516
+	/**
1517
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1518
+	 * never returned with the function.
1519
+	 *
1520
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1521
+	 * @return array
1522
+	 */
1523
+	public function remove_pages_from_wp_list_pages($exclude_array)
1524
+	{
1525
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1526
+	}
1527 1527
 
1528 1528
 
1529 1529
 
Please login to merge, or discard this patch.
admin_pages/registrations/Registrations_Admin_Page.core.php 1 patch
Indentation   +3532 added lines, -3532 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -23,2218 +23,2218 @@  discard block
 block discarded – undo
23 23
 class Registrations_Admin_Page extends EE_Admin_Page_CPT
24 24
 {
25 25
 
26
-    /**
27
-     * @var EE_Registration
28
-     */
29
-    private $_registration;
30
-
31
-    /**
32
-     * @var EE_Event
33
-     */
34
-    private $_reg_event;
35
-
36
-    /**
37
-     * @var EE_Session
38
-     */
39
-    private $_session;
40
-
41
-    private static $_reg_status;
42
-
43
-    /**
44
-     * Form for displaying the custom questions for this registration.
45
-     * This gets used a few times throughout the request so its best to cache it
46
-     *
47
-     * @var EE_Registration_Custom_Questions_Form
48
-     */
49
-    protected $_reg_custom_questions_form = null;
50
-
51
-
52
-    /**
53
-     *        constructor
54
-     *
55
-     * @Constructor
56
-     * @access public
57
-     * @param bool $routing
58
-     * @return Registrations_Admin_Page
59
-     */
60
-    public function __construct($routing = true)
61
-    {
62
-        parent::__construct($routing);
63
-        add_action('wp_loaded', array($this, 'wp_loaded'));
64
-    }
65
-
66
-
67
-    public function wp_loaded()
68
-    {
69
-        // when adding a new registration...
70
-        if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
71
-            EE_System::do_not_cache();
72
-            if (! isset($this->_req_data['processing_registration'])
73
-                 || absint($this->_req_data['processing_registration']) !== 1
74
-            ) {
75
-                // and it's NOT the attendee information reg step
76
-                // force cookie expiration by setting time to last week
77
-                setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
78
-                // and update the global
79
-                $_COOKIE['ee_registration_added'] = 0;
80
-            }
81
-        }
82
-    }
83
-
84
-
85
-    protected function _init_page_props()
86
-    {
87
-        $this->page_slug        = REG_PG_SLUG;
88
-        $this->_admin_base_url  = REG_ADMIN_URL;
89
-        $this->_admin_base_path = REG_ADMIN;
90
-        $this->page_label       = esc_html__('Registrations', 'event_espresso');
91
-        $this->_cpt_routes      = array(
92
-            'add_new_attendee' => 'espresso_attendees',
93
-            'edit_attendee'    => 'espresso_attendees',
94
-            'insert_attendee'  => 'espresso_attendees',
95
-            'update_attendee'  => 'espresso_attendees',
96
-        );
97
-        $this->_cpt_model_names = array(
98
-            'add_new_attendee' => 'EEM_Attendee',
99
-            'edit_attendee'    => 'EEM_Attendee',
100
-        );
101
-        $this->_cpt_edit_routes = array(
102
-            'espresso_attendees' => 'edit_attendee',
103
-        );
104
-        $this->_pagenow_map     = array(
105
-            'add_new_attendee' => 'post-new.php',
106
-            'edit_attendee'    => 'post.php',
107
-            'trash'            => 'post.php',
108
-        );
109
-        add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
110
-        //add filters so that the comment urls don't take users to a confusing 404 page
111
-        add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
112
-    }
113
-
114
-
115
-    public function clear_comment_link($link, $comment, $args)
116
-    {
117
-        //gotta make sure this only happens on this route
118
-        $post_type = get_post_type($comment->comment_post_ID);
119
-        if ($post_type === 'espresso_attendees') {
120
-            return '#commentsdiv';
121
-        }
122
-        return $link;
123
-    }
124
-
125
-
126
-    protected function _ajax_hooks()
127
-    {
128
-        //todo: all hooks for registrations ajax goes in here
129
-        add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
130
-    }
131
-
132
-
133
-    protected function _define_page_props()
134
-    {
135
-        $this->_admin_page_title = $this->page_label;
136
-        $this->_labels           = array(
137
-            'buttons'                      => array(
138
-                'add-registrant'      => esc_html__('Add New Registration', 'event_espresso'),
139
-                'add-attendee'        => esc_html__('Add Contact', 'event_espresso'),
140
-                'edit'                => esc_html__('Edit Contact', 'event_espresso'),
141
-                'report'              => esc_html__("Event Registrations CSV Report", "event_espresso"),
142
-                'report_all'          => esc_html__('All Registrations CSV Report', 'event_espresso'),
143
-                'report_filtered'     => esc_html__('Filtered CSV Report', 'event_espresso'),
144
-                'contact_list_report' => esc_html__('Contact List Report', 'event_espresso'),
145
-                'contact_list_export' => esc_html__("Export Data", "event_espresso"),
146
-            ),
147
-            'publishbox'                   => array(
148
-                'add_new_attendee' => esc_html__("Add Contact Record", 'event_espresso'),
149
-                'edit_attendee'    => esc_html__("Update Contact Record", 'event_espresso'),
150
-            ),
151
-            'hide_add_button_on_cpt_route' => array(
152
-                'edit_attendee' => true,
153
-            ),
154
-        );
155
-    }
156
-
157
-
158
-    /**
159
-     *        grab url requests and route them
160
-     *
161
-     * @access private
162
-     * @return void
163
-     */
164
-    public function _set_page_routes()
165
-    {
166
-        $this->_get_registration_status_array();
167
-        $reg_id             = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
168
-            ? $this->_req_data['_REG_ID'] : 0;
169
-        $reg_id = empty($reg_id) && ! empty($this->_req_data['reg_status_change_form']['REG_ID'])
170
-            ? $this->_req_data['reg_status_change_form']['REG_ID']
171
-            : $reg_id;
172
-        $att_id             = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
173
-            ? $this->_req_data['ATT_ID'] : 0;
174
-        $att_id             = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post'])
175
-            ? $this->_req_data['post']
176
-            : $att_id;
177
-        $this->_page_routes = array(
178
-            'default'                            => array(
179
-                'func'       => '_registrations_overview_list_table',
180
-                'capability' => 'ee_read_registrations',
181
-            ),
182
-            'view_registration'                  => array(
183
-                'func'       => '_registration_details',
184
-                'capability' => 'ee_read_registration',
185
-                'obj_id'     => $reg_id,
186
-            ),
187
-            'edit_registration'                  => array(
188
-                'func'               => '_update_attendee_registration_form',
189
-                'noheader'           => true,
190
-                'headers_sent_route' => 'view_registration',
191
-                'capability'         => 'ee_edit_registration',
192
-                'obj_id'             => $reg_id,
193
-                '_REG_ID'            => $reg_id,
194
-            ),
195
-            'trash_registrations'                => array(
196
-                'func'       => '_trash_or_restore_registrations',
197
-                'args'       => array('trash' => true),
198
-                'noheader'   => true,
199
-                'capability' => 'ee_delete_registrations',
200
-            ),
201
-            'restore_registrations'              => array(
202
-                'func'       => '_trash_or_restore_registrations',
203
-                'args'       => array('trash' => false),
204
-                'noheader'   => true,
205
-                'capability' => 'ee_delete_registrations',
206
-            ),
207
-            'delete_registrations'               => array(
208
-                'func'       => '_delete_registrations',
209
-                'noheader'   => true,
210
-                'capability' => 'ee_delete_registrations',
211
-            ),
212
-            'new_registration'                   => array(
213
-                'func'       => 'new_registration',
214
-                'capability' => 'ee_edit_registrations',
215
-            ),
216
-            'process_reg_step'                   => array(
217
-                'func'       => 'process_reg_step',
218
-                'noheader'   => true,
219
-                'capability' => 'ee_edit_registrations',
220
-            ),
221
-            'redirect_to_txn'                    => array(
222
-                'func'       => 'redirect_to_txn',
223
-                'noheader'   => true,
224
-                'capability' => 'ee_edit_registrations',
225
-            ),
226
-            'change_reg_status'                  => array(
227
-                'func'       => '_change_reg_status',
228
-                'noheader'   => true,
229
-                'capability' => 'ee_edit_registration',
230
-                'obj_id'     => $reg_id,
231
-            ),
232
-            'approve_registration'               => array(
233
-                'func'       => 'approve_registration',
234
-                'noheader'   => true,
235
-                'capability' => 'ee_edit_registration',
236
-                'obj_id'     => $reg_id,
237
-            ),
238
-            'approve_and_notify_registration'    => array(
239
-                'func'       => 'approve_registration',
240
-                'noheader'   => true,
241
-                'args'       => array(true),
242
-                'capability' => 'ee_edit_registration',
243
-                'obj_id'     => $reg_id,
244
-            ),
245
-            'approve_registrations'               => array(
246
-                'func'       => 'bulk_action_on_registrations',
247
-                'noheader'   => true,
248
-                'capability' => 'ee_edit_registrations',
249
-                'args' => array('approve')
250
-            ),
251
-            'approve_and_notify_registrations'               => array(
252
-                'func'       => 'bulk_action_on_registrations',
253
-                'noheader'   => true,
254
-                'capability' => 'ee_edit_registrations',
255
-                'args' => array('approve', true)
256
-            ),
257
-            'decline_registration'               => array(
258
-                'func'       => 'decline_registration',
259
-                'noheader'   => true,
260
-                'capability' => 'ee_edit_registration',
261
-                'obj_id'     => $reg_id,
262
-            ),
263
-            'decline_and_notify_registration'    => array(
264
-                'func'       => 'decline_registration',
265
-                'noheader'   => true,
266
-                'args'       => array(true),
267
-                'capability' => 'ee_edit_registration',
268
-                'obj_id'     => $reg_id,
269
-            ),
270
-            'decline_registrations'               => array(
271
-                'func'       => 'bulk_action_on_registrations',
272
-                'noheader'   => true,
273
-                'capability' => 'ee_edit_registrations',
274
-                'args' => array('decline')
275
-            ),
276
-            'decline_and_notify_registrations'    => array(
277
-                'func'       => 'bulk_action_on_registrations',
278
-                'noheader'   => true,
279
-                'capability' => 'ee_edit_registrations',
280
-                'args' => array('decline', true)
281
-            ),
282
-            'pending_registration'               => array(
283
-                'func'       => 'pending_registration',
284
-                'noheader'   => true,
285
-                'capability' => 'ee_edit_registration',
286
-                'obj_id'     => $reg_id,
287
-            ),
288
-            'pending_and_notify_registration'    => array(
289
-                'func'       => 'pending_registration',
290
-                'noheader'   => true,
291
-                'args'       => array(true),
292
-                'capability' => 'ee_edit_registration',
293
-                'obj_id'     => $reg_id,
294
-            ),
295
-            'pending_registrations'               => array(
296
-                'func'       => 'bulk_action_on_registrations',
297
-                'noheader'   => true,
298
-                'capability' => 'ee_edit_registrations',
299
-                'args' => array('pending')
300
-            ),
301
-            'pending_and_notify_registrations'    => array(
302
-                'func'       => 'bulk_action_on_registrations',
303
-                'noheader'   => true,
304
-                'capability' => 'ee_edit_registrations',
305
-                'args' => array('pending', true)
306
-            ),
307
-            'no_approve_registration'            => array(
308
-                'func'       => 'not_approve_registration',
309
-                'noheader'   => true,
310
-                'capability' => 'ee_edit_registration',
311
-                'obj_id'     => $reg_id,
312
-            ),
313
-            'no_approve_and_notify_registration' => array(
314
-                'func'       => 'not_approve_registration',
315
-                'noheader'   => true,
316
-                'args'       => array(true),
317
-                'capability' => 'ee_edit_registration',
318
-                'obj_id'     => $reg_id,
319
-            ),
320
-            'no_approve_registrations'            => array(
321
-                'func'       => 'bulk_action_on_registrations',
322
-                'noheader'   => true,
323
-                'capability' => 'ee_edit_registrations',
324
-                'args' => array('no_approve')
325
-            ),
326
-            'no_approve_and_notify_registrations' => array(
327
-                'func'       => 'bulk_action_on_registrations',
328
-                'noheader'   => true,
329
-                'capability' => 'ee_edit_registrations',
330
-                'args' => array('no_approve', true)
331
-            ),
332
-            'cancel_registration'                => array(
333
-                'func'       => 'cancel_registration',
334
-                'noheader'   => true,
335
-                'capability' => 'ee_edit_registration',
336
-                'obj_id'     => $reg_id,
337
-            ),
338
-            'cancel_and_notify_registration'     => array(
339
-                'func'       => 'cancel_registration',
340
-                'noheader'   => true,
341
-                'args'       => array(true),
342
-                'capability' => 'ee_edit_registration',
343
-                'obj_id'     => $reg_id,
344
-            ),
345
-            'cancel_registrations'                => array(
346
-                'func'       => 'bulk_action_on_registrations',
347
-                'noheader'   => true,
348
-                'capability' => 'ee_edit_registrations',
349
-                'args' => array('cancel')
350
-            ),
351
-            'cancel_and_notify_registrations'     => array(
352
-                'func'       => 'bulk_action_on_registrations',
353
-                'noheader'   => true,
354
-                'capability' => 'ee_edit_registrations',
355
-                'args' => array('cancel', true)
356
-            ),
357
-            'wait_list_registration' => array(
358
-                'func'       => 'wait_list_registration',
359
-                'noheader'   => true,
360
-                'capability' => 'ee_edit_registration',
361
-                'obj_id'     => $reg_id,
362
-            ),
363
-            'contact_list'                       => array(
364
-                'func'       => '_attendee_contact_list_table',
365
-                'capability' => 'ee_read_contacts',
366
-            ),
367
-            'add_new_attendee'                   => array(
368
-                'func' => '_create_new_cpt_item',
369
-                'args' => array(
370
-                    'new_attendee' => true,
371
-                    'capability'   => 'ee_edit_contacts',
372
-                ),
373
-            ),
374
-            'edit_attendee'                      => array(
375
-                'func'       => '_edit_cpt_item',
376
-                'capability' => 'ee_edit_contacts',
377
-                'obj_id'     => $att_id,
378
-            ),
379
-            'duplicate_attendee'                 => array(
380
-                'func'       => '_duplicate_attendee',
381
-                'noheader'   => true,
382
-                'capability' => 'ee_edit_contacts',
383
-                'obj_id'     => $att_id,
384
-            ),
385
-            'insert_attendee'                    => array(
386
-                'func'       => '_insert_or_update_attendee',
387
-                'args'       => array(
388
-                    'new_attendee' => true,
389
-                ),
390
-                'noheader'   => true,
391
-                'capability' => 'ee_edit_contacts',
392
-            ),
393
-            'update_attendee'                    => array(
394
-                'func'       => '_insert_or_update_attendee',
395
-                'args'       => array(
396
-                    'new_attendee' => false,
397
-                ),
398
-                'noheader'   => true,
399
-                'capability' => 'ee_edit_contacts',
400
-                'obj_id'     => $att_id,
401
-            ),
402
-            'trash_attendees' => array(
403
-                'func' => '_trash_or_restore_attendees',
404
-                'args' => array(
405
-                    'trash' => 'true'
406
-                ),
407
-                'noheader' => true,
408
-                'capability' => 'ee_delete_contacts'
409
-            ),
410
-            'trash_attendee'                    => array(
411
-                'func'       => '_trash_or_restore_attendees',
412
-                'args'       => array(
413
-                    'trash' => true,
414
-                ),
415
-                'noheader'   => true,
416
-                'capability' => 'ee_delete_contacts',
417
-                'obj_id'     => $att_id,
418
-            ),
419
-            'restore_attendees'                  => array(
420
-                'func'       => '_trash_or_restore_attendees',
421
-                'args'       => array(
422
-                    'trash' => false,
423
-                ),
424
-                'noheader'   => true,
425
-                'capability' => 'ee_delete_contacts',
426
-                'obj_id'     => $att_id,
427
-            ),
428
-            'resend_registration'                => array(
429
-                'func'       => '_resend_registration',
430
-                'noheader'   => true,
431
-                'capability' => 'ee_send_message',
432
-            ),
433
-            'registrations_report'               => array(
434
-                'func'       => '_registrations_report',
435
-                'noheader'   => true,
436
-                'capability' => 'ee_read_registrations',
437
-            ),
438
-            'contact_list_export'                => array(
439
-                'func'       => '_contact_list_export',
440
-                'noheader'   => true,
441
-                'capability' => 'export',
442
-            ),
443
-            'contact_list_report'                => array(
444
-                'func'       => '_contact_list_report',
445
-                'noheader'   => true,
446
-                'capability' => 'ee_read_contacts',
447
-            ),
448
-        );
449
-    }
450
-
451
-
452
-    protected function _set_page_config()
453
-    {
454
-        $this->_page_config = array(
455
-            'default'           => array(
456
-                'nav'           => array(
457
-                    'label' => esc_html__('Overview', 'event_espresso'),
458
-                    'order' => 5,
459
-                ),
460
-                'help_tabs'     => array(
461
-                    'registrations_overview_help_tab'                       => array(
462
-                        'title'    => esc_html__('Registrations Overview', 'event_espresso'),
463
-                        'filename' => 'registrations_overview',
464
-                    ),
465
-                    'registrations_overview_table_column_headings_help_tab' => array(
466
-                        'title'    => esc_html__('Registrations Table Column Headings', 'event_espresso'),
467
-                        'filename' => 'registrations_overview_table_column_headings',
468
-                    ),
469
-                    'registrations_overview_filters_help_tab'               => array(
470
-                        'title'    => esc_html__('Registration Filters', 'event_espresso'),
471
-                        'filename' => 'registrations_overview_filters',
472
-                    ),
473
-                    'registrations_overview_views_help_tab'                 => array(
474
-                        'title'    => esc_html__('Registration Views', 'event_espresso'),
475
-                        'filename' => 'registrations_overview_views',
476
-                    ),
477
-                    'registrations_regoverview_other_help_tab'              => array(
478
-                        'title'    => esc_html__('Registrations Other', 'event_espresso'),
479
-                        'filename' => 'registrations_overview_other',
480
-                    ),
481
-                ),
482
-                'help_tour'     => array('Registration_Overview_Help_Tour'),
483
-                'qtips'         => array('Registration_List_Table_Tips'),
484
-                'list_table'    => 'EE_Registrations_List_Table',
485
-                'require_nonce' => false,
486
-            ),
487
-            'view_registration' => array(
488
-                'nav'           => array(
489
-                    'label'      => esc_html__('REG Details', 'event_espresso'),
490
-                    'order'      => 15,
491
-                    'url'        => isset($this->_req_data['_REG_ID'])
492
-                        ? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
493
-                        : $this->_admin_base_url,
494
-                    'persistent' => false,
495
-                ),
496
-                'help_tabs'     => array(
497
-                    'registrations_details_help_tab'                    => array(
498
-                        'title'    => esc_html__('Registration Details', 'event_espresso'),
499
-                        'filename' => 'registrations_details',
500
-                    ),
501
-                    'registrations_details_table_help_tab'              => array(
502
-                        'title'    => esc_html__('Registration Details Table', 'event_espresso'),
503
-                        'filename' => 'registrations_details_table',
504
-                    ),
505
-                    'registrations_details_form_answers_help_tab'       => array(
506
-                        'title'    => esc_html__('Registration Form Answers', 'event_espresso'),
507
-                        'filename' => 'registrations_details_form_answers',
508
-                    ),
509
-                    'registrations_details_registrant_details_help_tab' => array(
510
-                        'title'    => esc_html__('Contact Details', 'event_espresso'),
511
-                        'filename' => 'registrations_details_registrant_details',
512
-                    ),
513
-                ),
514
-                'help_tour'     => array('Registration_Details_Help_Tour'),
515
-                'metaboxes'     => array_merge(
516
-                    $this->_default_espresso_metaboxes,
517
-                    array('_registration_details_metaboxes')
518
-                ),
519
-                'require_nonce' => false,
520
-            ),
521
-            'new_registration'  => array(
522
-                'nav'           => array(
523
-                    'label'      => esc_html__('Add New Registration', 'event_espresso'),
524
-                    'url'        => '#',
525
-                    'order'      => 15,
526
-                    'persistent' => false,
527
-                ),
528
-                'metaboxes'     => $this->_default_espresso_metaboxes,
529
-                'labels'        => array(
530
-                    'publishbox' => esc_html__('Save Registration', 'event_espresso'),
531
-                ),
532
-                'require_nonce' => false,
533
-            ),
534
-            'add_new_attendee'  => array(
535
-                'nav'           => array(
536
-                    'label'      => esc_html__('Add Contact', 'event_espresso'),
537
-                    'order'      => 15,
538
-                    'persistent' => false,
539
-                ),
540
-                'metaboxes'     => array_merge(
541
-                    $this->_default_espresso_metaboxes,
542
-                    array('_publish_post_box', 'attendee_editor_metaboxes')
543
-                ),
544
-                'require_nonce' => false,
545
-            ),
546
-            'edit_attendee'     => array(
547
-                'nav'           => array(
548
-                    'label'      => esc_html__('Edit Contact', 'event_espresso'),
549
-                    'order'      => 15,
550
-                    'persistent' => false,
551
-                    'url'        => isset($this->_req_data['ATT_ID'])
552
-                        ? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
553
-                        : $this->_admin_base_url,
554
-                ),
555
-                'metaboxes'     => array('attendee_editor_metaboxes'),
556
-                'require_nonce' => false,
557
-            ),
558
-            'contact_list'      => array(
559
-                'nav'           => array(
560
-                    'label' => esc_html__('Contact List', 'event_espresso'),
561
-                    'order' => 20,
562
-                ),
563
-                'list_table'    => 'EE_Attendee_Contact_List_Table',
564
-                'help_tabs'     => array(
565
-                    'registrations_contact_list_help_tab'                       => array(
566
-                        'title'    => esc_html__('Registrations Contact List', 'event_espresso'),
567
-                        'filename' => 'registrations_contact_list',
568
-                    ),
569
-                    'registrations_contact-list_table_column_headings_help_tab' => array(
570
-                        'title'    => esc_html__('Contact List Table Column Headings', 'event_espresso'),
571
-                        'filename' => 'registrations_contact_list_table_column_headings',
572
-                    ),
573
-                    'registrations_contact_list_views_help_tab'                 => array(
574
-                        'title'    => esc_html__('Contact List Views', 'event_espresso'),
575
-                        'filename' => 'registrations_contact_list_views',
576
-                    ),
577
-                    'registrations_contact_list_other_help_tab'                 => array(
578
-                        'title'    => esc_html__('Contact List Other', 'event_espresso'),
579
-                        'filename' => 'registrations_contact_list_other',
580
-                    ),
581
-                ),
582
-                'help_tour'     => array('Contact_List_Help_Tour'),
583
-                'metaboxes'     => array(),
584
-                'require_nonce' => false,
585
-            ),
586
-            //override default cpt routes
587
-            'create_new'        => '',
588
-            'edit'              => '',
589
-        );
590
-    }
591
-
592
-
593
-    /**
594
-     * The below methods aren't used by this class currently
595
-     */
596
-    protected function _add_screen_options()
597
-    {
598
-    }
599
-
600
-
601
-    protected function _add_feature_pointers()
602
-    {
603
-    }
604
-
605
-
606
-    public function admin_init()
607
-    {
608
-        EE_Registry::$i18n_js_strings['update_att_qstns'] = esc_html__(
609
-            'click "Update Registration Questions" to save your changes',
610
-            'event_espresso'
611
-        );
612
-    }
613
-
614
-
615
-    public function admin_notices()
616
-    {
617
-    }
618
-
619
-
620
-    public function admin_footer_scripts()
621
-    {
622
-    }
623
-
624
-
625
-    /**
626
-     *        get list of registration statuses
627
-     *
628
-     * @access private
629
-     * @return void
630
-     */
631
-    private function _get_registration_status_array()
632
-    {
633
-        self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
634
-    }
635
-
636
-
637
-    protected function _add_screen_options_default()
638
-    {
639
-        $this->_per_page_screen_option();
640
-    }
641
-
642
-
643
-    protected function _add_screen_options_contact_list()
644
-    {
645
-        $page_title              = $this->_admin_page_title;
646
-        $this->_admin_page_title = esc_html__("Contacts", 'event_espresso');
647
-        $this->_per_page_screen_option();
648
-        $this->_admin_page_title = $page_title;
649
-    }
650
-
651
-
652
-    public function load_scripts_styles()
653
-    {
654
-        //style
655
-        wp_register_style(
656
-            'espresso_reg',
657
-            REG_ASSETS_URL . 'espresso_registrations_admin.css',
658
-            array('ee-admin-css'),
659
-            EVENT_ESPRESSO_VERSION
660
-        );
661
-        wp_enqueue_style('espresso_reg');
662
-        //script
663
-        wp_register_script(
664
-            'espresso_reg',
665
-            REG_ASSETS_URL . 'espresso_registrations_admin.js',
666
-            array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'),
667
-            EVENT_ESPRESSO_VERSION,
668
-            true
669
-        );
670
-        wp_enqueue_script('espresso_reg');
671
-    }
672
-
673
-
674
-    public function load_scripts_styles_edit_attendee()
675
-    {
676
-        //stuff to only show up on our attendee edit details page.
677
-        $attendee_details_translations = array(
678
-            'att_publish_text' => sprintf(
679
-                esc_html__('Created on: <b>%1$s</b>', 'event_espresso'),
680
-                $this->_cpt_model_obj->get_datetime('ATT_created')
681
-            ),
682
-        );
683
-        wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
684
-        wp_enqueue_script('jquery-validate');
685
-    }
686
-
687
-
688
-    public function load_scripts_styles_view_registration()
689
-    {
690
-        //styles
691
-        wp_enqueue_style('espresso-ui-theme');
692
-        //scripts
693
-        $this->_get_reg_custom_questions_form($this->_registration->ID());
694
-        $this->_reg_custom_questions_form->wp_enqueue_scripts(true);
695
-    }
696
-
697
-
698
-    public function load_scripts_styles_contact_list()
699
-    {
700
-        wp_deregister_style('espresso_reg');
701
-        wp_register_style(
702
-            'espresso_att',
703
-            REG_ASSETS_URL . 'espresso_attendees_admin.css',
704
-            array('ee-admin-css'),
705
-            EVENT_ESPRESSO_VERSION
706
-        );
707
-        wp_enqueue_style('espresso_att');
708
-    }
709
-
710
-
711
-    public function load_scripts_styles_new_registration()
712
-    {
713
-        wp_register_script(
714
-            'ee-spco-for-admin',
715
-            REG_ASSETS_URL . 'spco_for_admin.js',
716
-            array('underscore', 'jquery'),
717
-            EVENT_ESPRESSO_VERSION,
718
-            true
719
-        );
720
-        wp_enqueue_script('ee-spco-for-admin');
721
-        add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
722
-        EE_Form_Section_Proper::wp_enqueue_scripts();
723
-        EED_Ticket_Selector::load_tckt_slctr_assets();
724
-        EE_Datepicker_Input::enqueue_styles_and_scripts();
725
-    }
726
-
727
-
728
-    public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
729
-    {
730
-        add_filter('FHEE_load_EE_messages', '__return_true');
731
-    }
732
-
733
-
734
-    public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
735
-    {
736
-        add_filter('FHEE_load_EE_messages', '__return_true');
737
-    }
738
-
739
-
740
-    protected function _set_list_table_views_default()
741
-    {
742
-        //for notification related bulk actions we need to make sure only active messengers have an option.
743
-        EED_Messages::set_autoloaders();
744
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
745
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
746
-        $active_mts               = $message_resource_manager->list_of_active_message_types();
747
-        //key= bulk_action_slug, value= message type.
748
-        $match_array = array(
749
-            'approve_registrations'    => 'registration',
750
-            'decline_registrations'    => 'declined_registration',
751
-            'pending_registrations'    => 'pending_approval',
752
-            'no_approve_registrations' => 'not_approved_registration',
753
-            'cancel_registrations'     => 'cancelled_registration',
754
-        );
755
-        $can_send = EE_Registry::instance()->CAP->current_user_can(
756
-            'ee_send_message',
757
-            'batch_send_messages'
758
-        );
759
-        /** setup reg status bulk actions **/
760
-        $def_reg_status_actions['approve_registrations'] = esc_html__('Approve Registrations', 'event_espresso');
761
-        if ($can_send && in_array($match_array['approve_registrations'], $active_mts, true)) {
762
-                $def_reg_status_actions['approve_and_notify_registrations'] = esc_html__(
763
-                    'Approve and Notify Registrations',
764
-                    'event_espresso'
765
-                );
766
-        }
767
-        $def_reg_status_actions['decline_registrations'] = esc_html__('Decline Registrations', 'event_espresso');
768
-        if ($can_send && in_array($match_array['decline_registrations'], $active_mts, true)) {
769
-                $def_reg_status_actions['decline_and_notify_registrations'] = esc_html__(
770
-                    'Decline and Notify Registrations',
771
-                    'event_espresso'
772
-                );
773
-        }
774
-        $def_reg_status_actions['pending_registrations'] = esc_html__(
775
-            'Set Registrations to Pending Payment',
776
-            'event_espresso'
777
-        );
778
-        if ($can_send && in_array($match_array['pending_registrations'], $active_mts, true)) {
779
-                $def_reg_status_actions['pending_and_notify_registrations'] = esc_html__(
780
-                    'Set Registrations to Pending Payment and Notify',
781
-                    'event_espresso'
782
-                );
783
-        }
784
-        $def_reg_status_actions['no_approve_registrations'] = esc_html__(
785
-            'Set Registrations to Not Approved',
786
-            'event_espresso'
787
-        );
788
-        if ($can_send && in_array($match_array['no_approve_registrations'], $active_mts, true)) {
789
-                $def_reg_status_actions['no_approve_and_notify_registrations'] = esc_html__(
790
-                    'Set Registrations to Not Approved and Notify',
791
-                    'event_espresso'
792
-                );
793
-        }
794
-        $def_reg_status_actions['cancel_registrations'] = esc_html__('Cancel Registrations', 'event_espresso');
795
-        if ($can_send && in_array($match_array['cancel_registrations'], $active_mts, true)) {
796
-                $def_reg_status_actions['cancel_and_notify_registrations'] = esc_html__(
797
-                    'Cancel Registrations and Notify',
798
-                    'event_espresso'
799
-                );
800
-        }
801
-        $def_reg_status_actions = apply_filters(
802
-            'FHEE__Registrations_Admin_Page___set_list_table_views_default__def_reg_status_actions_array',
803
-            $def_reg_status_actions,
804
-            $active_mts
805
-        );
806
-
807
-        $this->_views = array(
808
-            'all'   => array(
809
-                'slug'        => 'all',
810
-                'label'       => esc_html__('View All Registrations', 'event_espresso'),
811
-                'count'       => 0,
812
-                'bulk_action' => array_merge($def_reg_status_actions, array(
813
-                    'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
814
-                )),
815
-            ),
816
-            'month' => array(
817
-                'slug'        => 'month',
818
-                'label'       => esc_html__('This Month', 'event_espresso'),
819
-                'count'       => 0,
820
-                'bulk_action' => array_merge($def_reg_status_actions, array(
821
-                    'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
822
-                )),
823
-            ),
824
-            'today' => array(
825
-                'slug'        => 'today',
826
-                'label'       => sprintf(
827
-                    esc_html__('Today - %s', 'event_espresso'),
828
-                    date('M d, Y', current_time('timestamp'))
829
-                ),
830
-                'count'       => 0,
831
-                'bulk_action' => array_merge($def_reg_status_actions, array(
832
-                    'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
833
-                )),
834
-            ),
835
-        );
836
-        if (EE_Registry::instance()->CAP->current_user_can(
837
-            'ee_delete_registrations',
838
-            'espresso_registrations_delete_registration'
839
-        )) {
840
-            $this->_views['incomplete'] = array(
841
-                'slug'        => 'incomplete',
842
-                'label'       => esc_html__('Incomplete', 'event_espresso'),
843
-                'count'       => 0,
844
-                'bulk_action' => array(
845
-                    'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
846
-                ),
847
-            );
848
-            $this->_views['trash']      = array(
849
-                'slug'        => 'trash',
850
-                'label'       => esc_html__('Trash', 'event_espresso'),
851
-                'count'       => 0,
852
-                'bulk_action' => array(
853
-                    'restore_registrations' => esc_html__('Restore Registrations', 'event_espresso'),
854
-                    'delete_registrations'  => esc_html__('Delete Registrations Permanently', 'event_espresso'),
855
-                ),
856
-            );
857
-        }
858
-    }
859
-
860
-
861
-    protected function _set_list_table_views_contact_list()
862
-    {
863
-        $this->_views = array(
864
-            'in_use' => array(
865
-                'slug'        => 'in_use',
866
-                'label'       => esc_html__('In Use', 'event_espresso'),
867
-                'count'       => 0,
868
-                'bulk_action' => array(
869
-                    'trash_attendees' => esc_html__('Move to Trash', 'event_espresso'),
870
-                ),
871
-            ),
872
-        );
873
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_contacts',
874
-            'espresso_registrations_trash_attendees')
875
-        ) {
876
-            $this->_views['trash'] = array(
877
-                'slug'        => 'trash',
878
-                'label'       => esc_html__('Trash', 'event_espresso'),
879
-                'count'       => 0,
880
-                'bulk_action' => array(
881
-                    'restore_attendees' => esc_html__('Restore from Trash', 'event_espresso'),
882
-                ),
883
-            );
884
-        }
885
-    }
886
-
887
-
888
-    protected function _registration_legend_items()
889
-    {
890
-        $fc_items = array(
891
-            'star-icon'        => array(
892
-                'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
893
-                'desc'  => esc_html__('This is the Primary Registrant', 'event_espresso'),
894
-            ),
895
-            'view_details'     => array(
896
-                'class' => 'dashicons dashicons-clipboard',
897
-                'desc'  => esc_html__('View Registration Details', 'event_espresso'),
898
-            ),
899
-            'edit_attendee'    => array(
900
-                'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
901
-                'desc'  => esc_html__('Edit Contact Details', 'event_espresso'),
902
-            ),
903
-            'view_transaction' => array(
904
-                'class' => 'dashicons dashicons-cart',
905
-                'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
906
-            ),
907
-            'view_invoice'     => array(
908
-                'class' => 'dashicons dashicons-media-spreadsheet',
909
-                'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
910
-            ),
911
-        );
912
-        if (EE_Registry::instance()->CAP->current_user_can(
913
-            'ee_send_message',
914
-            'espresso_registrations_resend_registration'
915
-        )) {
916
-            $fc_items['resend_registration'] = array(
917
-                'class' => 'dashicons dashicons-email-alt',
918
-                'desc'  => esc_html__('Resend Registration Details', 'event_espresso'),
919
-            );
920
-        } else {
921
-            $fc_items['blank'] = array('class' => 'blank', 'desc' => '');
922
-        }
923
-        if (EE_Registry::instance()->CAP->current_user_can(
924
-            'ee_read_global_messages',
925
-            'view_filtered_messages'
926
-        )) {
927
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
928
-            if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
929
-                $fc_items['view_related_messages'] = array(
930
-                    'class' => $related_for_icon['css_class'],
931
-                    'desc'  => $related_for_icon['label'],
932
-                );
933
-            }
934
-        }
935
-        $sc_items = array(
936
-            'approved_status'   => array(
937
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
938
-                'desc'  => EEH_Template::pretty_status(
939
-                    EEM_Registration::status_id_approved,
940
-                    false,
941
-                    'sentence'
942
-                ),
943
-            ),
944
-            'pending_status'    => array(
945
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
946
-                'desc'  => EEH_Template::pretty_status(
947
-                    EEM_Registration::status_id_pending_payment,
948
-                    false,
949
-                    'sentence'
950
-                ),
951
-            ),
952
-            'wait_list'         => array(
953
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
954
-                'desc'  => EEH_Template::pretty_status(
955
-                    EEM_Registration::status_id_wait_list,
956
-                    false,
957
-                    'sentence'
958
-                ),
959
-            ),
960
-            'incomplete_status' => array(
961
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
962
-                'desc'  => EEH_Template::pretty_status(
963
-                    EEM_Registration::status_id_incomplete,
964
-                    false,
965
-                    'sentence'
966
-                ),
967
-            ),
968
-            'not_approved'      => array(
969
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
970
-                'desc'  => EEH_Template::pretty_status(
971
-                    EEM_Registration::status_id_not_approved,
972
-                    false,
973
-                    'sentence'
974
-                ),
975
-            ),
976
-            'declined_status'   => array(
977
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
978
-                'desc'  => EEH_Template::pretty_status(
979
-                    EEM_Registration::status_id_declined,
980
-                    false,
981
-                    'sentence'
982
-                ),
983
-            ),
984
-            'cancelled_status'  => array(
985
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
986
-                'desc'  => EEH_Template::pretty_status(
987
-                    EEM_Registration::status_id_cancelled,
988
-                    false,
989
-                    'sentence'
990
-                ),
991
-            ),
992
-        );
993
-        return array_merge($fc_items, $sc_items);
994
-    }
995
-
996
-
997
-
998
-    /***************************************        REGISTRATION OVERVIEW        **************************************/
999
-    /**
1000
-     * @throws \EE_Error
1001
-     */
1002
-    protected function _registrations_overview_list_table()
1003
-    {
1004
-        $this->_template_args['admin_page_header'] = '';
1005
-        $EVT_ID                                    = ! empty($this->_req_data['event_id'])
1006
-            ? absint($this->_req_data['event_id'])
1007
-            : 0;
1008
-        if ($EVT_ID) {
1009
-            if (EE_Registry::instance()->CAP->current_user_can(
1010
-                'ee_edit_registrations',
1011
-                'espresso_registrations_new_registration',
1012
-                $EVT_ID
1013
-            )) {
1014
-                $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
1015
-                    'new_registration',
1016
-                    'add-registrant',
1017
-                    array('event_id' => $EVT_ID),
1018
-                    'add-new-h2'
1019
-                );
1020
-            }
1021
-            $event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
1022
-            if ($event instanceof EE_Event) {
1023
-                $this->_template_args['admin_page_header'] = sprintf(
1024
-                    esc_html__(
1025
-                        '%s Viewing registrations for the event: %s%s',
1026
-                        'event_espresso'
1027
-                    ),
1028
-                    '<h3 style="line-height:1.5em;">',
1029
-                    '<br /><a href="'
1030
-                        . EE_Admin_Page::add_query_args_and_nonce(
1031
-                            array(
1032
-                                'action' => 'edit',
1033
-                                'post'   => $event->ID(),
1034
-                            ),
1035
-                            EVENTS_ADMIN_URL
1036
-                        )
1037
-                        . '">&nbsp;'
1038
-                        . $event->get('EVT_name')
1039
-                        . '&nbsp;</a>&nbsp;',
1040
-                    '</h3>'
1041
-                );
1042
-            }
1043
-            $DTT_ID   = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
1044
-            $datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1045
-            if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
1046
-                $this->_template_args['admin_page_header'] = substr(
1047
-                    $this->_template_args['admin_page_header'],
1048
-                    0,
1049
-                    -5
1050
-                );
1051
-                $this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
1052
-                $this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
1053
-                $this->_template_args['admin_page_header'] .= $datetime->name();
1054
-                $this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
1055
-                $this->_template_args['admin_page_header'] .= '</span></h3>';
1056
-            }
1057
-        }
1058
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
1059
-        $this->display_admin_list_table_page_with_no_sidebar();
1060
-    }
1061
-
1062
-
1063
-    /**
1064
-     * This sets the _registration property for the registration details screen
1065
-     *
1066
-     * @access private
1067
-     * @return bool
1068
-     */
1069
-    private function _set_registration_object()
1070
-    {
1071
-        //get out if we've already set the object
1072
-        if (is_object($this->_registration)) {
1073
-            return true;
1074
-        }
1075
-        $REG    = EEM_Registration::instance();
1076
-        $REG_ID = ( ! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
1077
-        if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
1078
-            return true;
1079
-        } else {
1080
-            $error_msg = sprintf(
1081
-                esc_html__(
1082
-                    'An error occurred and the details for Registration ID #%s could not be retrieved.',
1083
-                    'event_espresso'
1084
-                ),
1085
-                $REG_ID
1086
-            );
1087
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
1088
-            $this->_registration = null;
1089
-            return false;
1090
-        }
1091
-    }
1092
-
1093
-
1094
-    /**
1095
-     * Used to retrieve registrations for the list table.
1096
-     *
1097
-     * @param int  $per_page
1098
-     * @param bool $count
1099
-     * @param bool $this_month
1100
-     * @param bool $today
1101
-     * @return EE_Registration[]|int
1102
-     * @throws EE_Error
1103
-     */
1104
-    public function get_registrations(
1105
-        $per_page = 10,
1106
-        $count = false,
1107
-        $this_month = false,
1108
-        $today = false
1109
-    ) {
1110
-        if ($this_month) {
1111
-            $this->_req_data['status'] = 'month';
1112
-        }
1113
-        if ($today) {
1114
-            $this->_req_data['status'] = 'today';
1115
-        }
1116
-        $query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
1117
-        /**
1118
-         * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1119
-         * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1120
-         * @see EEM_Base::get_all()
1121
-         */
1122
-        $query_params['group_by'] = '';
1123
-
1124
-        return $count
1125
-            ? EEM_Registration::instance()->count($query_params)
1126
-            /** @type EE_Registration[] */
1127
-            : EEM_Registration::instance()->get_all($query_params);
1128
-    }
1129
-
1130
-
1131
-
1132
-    /**
1133
-     * Retrieves the query parameters to be used by the Registration model for getting registrations.
1134
-     * Note: this listens to values on the request for some of the query parameters.
1135
-     *
1136
-     * @param array $request
1137
-     * @param int    $per_page
1138
-     * @param bool   $count
1139
-     * @return array
1140
-     */
1141
-    protected function _get_registration_query_parameters(
1142
-        $request = array(),
1143
-        $per_page = 10,
1144
-        $count = false
1145
-    ) {
1146
-
1147
-        $query_params = array(
1148
-            0                          => $this->_get_where_conditions_for_registrations_query(
1149
-                $request
1150
-            ),
1151
-            'caps'                     => EEM_Registration::caps_read_admin,
1152
-            'default_where_conditions' => 'this_model_only',
1153
-        );
1154
-        if (! $count) {
1155
-            $query_params = array_merge(
1156
-                $query_params,
1157
-                $this->_get_orderby_for_registrations_query(),
1158
-                $this->_get_limit($per_page)
1159
-            );
1160
-        }
1161
-
1162
-        return $query_params;
1163
-    }
1164
-
1165
-
1166
-    /**
1167
-     * This will add EVT_ID to the provided $where array for EE model query parameters.
1168
-     *
1169
-     * @param array $request usually the same as $this->_req_data but not necessarily
1170
-     * @return array
1171
-     */
1172
-    protected function _add_event_id_to_where_conditions(array $request)
1173
-    {
1174
-        $where = array();
1175
-        if (! empty($request['event_id'])) {
1176
-            $where['EVT_ID'] = absint($request['event_id']);
1177
-        }
1178
-        return $where;
1179
-    }
1180
-
1181
-
1182
-    /**
1183
-     * Adds category ID if it exists in the request to the where conditions for the registrations query.
1184
-     *
1185
-     * @param array $request usually the same as $this->_req_data but not necessarily
1186
-     * @return array
1187
-     */
1188
-    protected function _add_category_id_to_where_conditions(array $request)
1189
-    {
1190
-        $where = array();
1191
-        if (! empty($request['EVT_CAT']) && (int)$request['EVT_CAT'] !== -1) {
1192
-            $where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1193
-        }
1194
-        return $where;
1195
-    }
1196
-
1197
-
1198
-    /**
1199
-     * Adds the datetime ID if it exists in the request to the where conditions for the registrations query.
1200
-     *
1201
-     * @param array $request usually the same as $this->_req_data but not necessarily
1202
-     * @return array
1203
-     */
1204
-    protected function _add_datetime_id_to_where_conditions(array $request)
1205
-    {
1206
-        $where = array();
1207
-        if (! empty($request['datetime_id'])) {
1208
-            $where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1209
-        }
1210
-        if (! empty($request['DTT_ID'])) {
1211
-            $where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1212
-        }
1213
-        return $where;
1214
-    }
1215
-
1216
-
1217
-    /**
1218
-     * Adds the correct registration status to the where conditions for the registrations query.
1219
-     *
1220
-     * @param array $request usually the same as $this->_req_data but not necessarily
1221
-     * @return array
1222
-     */
1223
-    protected function _add_registration_status_to_where_conditions(array $request)
1224
-    {
1225
-        $where = array();
1226
-        $view = EEH_Array::is_set($request, 'status', '');
1227
-        $registration_status = ! empty($request['_reg_status'])
1228
-            ? sanitize_text_field($request['_reg_status'])
1229
-            : '';
1230
-
1231
-        /*
26
+	/**
27
+	 * @var EE_Registration
28
+	 */
29
+	private $_registration;
30
+
31
+	/**
32
+	 * @var EE_Event
33
+	 */
34
+	private $_reg_event;
35
+
36
+	/**
37
+	 * @var EE_Session
38
+	 */
39
+	private $_session;
40
+
41
+	private static $_reg_status;
42
+
43
+	/**
44
+	 * Form for displaying the custom questions for this registration.
45
+	 * This gets used a few times throughout the request so its best to cache it
46
+	 *
47
+	 * @var EE_Registration_Custom_Questions_Form
48
+	 */
49
+	protected $_reg_custom_questions_form = null;
50
+
51
+
52
+	/**
53
+	 *        constructor
54
+	 *
55
+	 * @Constructor
56
+	 * @access public
57
+	 * @param bool $routing
58
+	 * @return Registrations_Admin_Page
59
+	 */
60
+	public function __construct($routing = true)
61
+	{
62
+		parent::__construct($routing);
63
+		add_action('wp_loaded', array($this, 'wp_loaded'));
64
+	}
65
+
66
+
67
+	public function wp_loaded()
68
+	{
69
+		// when adding a new registration...
70
+		if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
71
+			EE_System::do_not_cache();
72
+			if (! isset($this->_req_data['processing_registration'])
73
+				 || absint($this->_req_data['processing_registration']) !== 1
74
+			) {
75
+				// and it's NOT the attendee information reg step
76
+				// force cookie expiration by setting time to last week
77
+				setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
78
+				// and update the global
79
+				$_COOKIE['ee_registration_added'] = 0;
80
+			}
81
+		}
82
+	}
83
+
84
+
85
+	protected function _init_page_props()
86
+	{
87
+		$this->page_slug        = REG_PG_SLUG;
88
+		$this->_admin_base_url  = REG_ADMIN_URL;
89
+		$this->_admin_base_path = REG_ADMIN;
90
+		$this->page_label       = esc_html__('Registrations', 'event_espresso');
91
+		$this->_cpt_routes      = array(
92
+			'add_new_attendee' => 'espresso_attendees',
93
+			'edit_attendee'    => 'espresso_attendees',
94
+			'insert_attendee'  => 'espresso_attendees',
95
+			'update_attendee'  => 'espresso_attendees',
96
+		);
97
+		$this->_cpt_model_names = array(
98
+			'add_new_attendee' => 'EEM_Attendee',
99
+			'edit_attendee'    => 'EEM_Attendee',
100
+		);
101
+		$this->_cpt_edit_routes = array(
102
+			'espresso_attendees' => 'edit_attendee',
103
+		);
104
+		$this->_pagenow_map     = array(
105
+			'add_new_attendee' => 'post-new.php',
106
+			'edit_attendee'    => 'post.php',
107
+			'trash'            => 'post.php',
108
+		);
109
+		add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
110
+		//add filters so that the comment urls don't take users to a confusing 404 page
111
+		add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
112
+	}
113
+
114
+
115
+	public function clear_comment_link($link, $comment, $args)
116
+	{
117
+		//gotta make sure this only happens on this route
118
+		$post_type = get_post_type($comment->comment_post_ID);
119
+		if ($post_type === 'espresso_attendees') {
120
+			return '#commentsdiv';
121
+		}
122
+		return $link;
123
+	}
124
+
125
+
126
+	protected function _ajax_hooks()
127
+	{
128
+		//todo: all hooks for registrations ajax goes in here
129
+		add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
130
+	}
131
+
132
+
133
+	protected function _define_page_props()
134
+	{
135
+		$this->_admin_page_title = $this->page_label;
136
+		$this->_labels           = array(
137
+			'buttons'                      => array(
138
+				'add-registrant'      => esc_html__('Add New Registration', 'event_espresso'),
139
+				'add-attendee'        => esc_html__('Add Contact', 'event_espresso'),
140
+				'edit'                => esc_html__('Edit Contact', 'event_espresso'),
141
+				'report'              => esc_html__("Event Registrations CSV Report", "event_espresso"),
142
+				'report_all'          => esc_html__('All Registrations CSV Report', 'event_espresso'),
143
+				'report_filtered'     => esc_html__('Filtered CSV Report', 'event_espresso'),
144
+				'contact_list_report' => esc_html__('Contact List Report', 'event_espresso'),
145
+				'contact_list_export' => esc_html__("Export Data", "event_espresso"),
146
+			),
147
+			'publishbox'                   => array(
148
+				'add_new_attendee' => esc_html__("Add Contact Record", 'event_espresso'),
149
+				'edit_attendee'    => esc_html__("Update Contact Record", 'event_espresso'),
150
+			),
151
+			'hide_add_button_on_cpt_route' => array(
152
+				'edit_attendee' => true,
153
+			),
154
+		);
155
+	}
156
+
157
+
158
+	/**
159
+	 *        grab url requests and route them
160
+	 *
161
+	 * @access private
162
+	 * @return void
163
+	 */
164
+	public function _set_page_routes()
165
+	{
166
+		$this->_get_registration_status_array();
167
+		$reg_id             = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
168
+			? $this->_req_data['_REG_ID'] : 0;
169
+		$reg_id = empty($reg_id) && ! empty($this->_req_data['reg_status_change_form']['REG_ID'])
170
+			? $this->_req_data['reg_status_change_form']['REG_ID']
171
+			: $reg_id;
172
+		$att_id             = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
173
+			? $this->_req_data['ATT_ID'] : 0;
174
+		$att_id             = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post'])
175
+			? $this->_req_data['post']
176
+			: $att_id;
177
+		$this->_page_routes = array(
178
+			'default'                            => array(
179
+				'func'       => '_registrations_overview_list_table',
180
+				'capability' => 'ee_read_registrations',
181
+			),
182
+			'view_registration'                  => array(
183
+				'func'       => '_registration_details',
184
+				'capability' => 'ee_read_registration',
185
+				'obj_id'     => $reg_id,
186
+			),
187
+			'edit_registration'                  => array(
188
+				'func'               => '_update_attendee_registration_form',
189
+				'noheader'           => true,
190
+				'headers_sent_route' => 'view_registration',
191
+				'capability'         => 'ee_edit_registration',
192
+				'obj_id'             => $reg_id,
193
+				'_REG_ID'            => $reg_id,
194
+			),
195
+			'trash_registrations'                => array(
196
+				'func'       => '_trash_or_restore_registrations',
197
+				'args'       => array('trash' => true),
198
+				'noheader'   => true,
199
+				'capability' => 'ee_delete_registrations',
200
+			),
201
+			'restore_registrations'              => array(
202
+				'func'       => '_trash_or_restore_registrations',
203
+				'args'       => array('trash' => false),
204
+				'noheader'   => true,
205
+				'capability' => 'ee_delete_registrations',
206
+			),
207
+			'delete_registrations'               => array(
208
+				'func'       => '_delete_registrations',
209
+				'noheader'   => true,
210
+				'capability' => 'ee_delete_registrations',
211
+			),
212
+			'new_registration'                   => array(
213
+				'func'       => 'new_registration',
214
+				'capability' => 'ee_edit_registrations',
215
+			),
216
+			'process_reg_step'                   => array(
217
+				'func'       => 'process_reg_step',
218
+				'noheader'   => true,
219
+				'capability' => 'ee_edit_registrations',
220
+			),
221
+			'redirect_to_txn'                    => array(
222
+				'func'       => 'redirect_to_txn',
223
+				'noheader'   => true,
224
+				'capability' => 'ee_edit_registrations',
225
+			),
226
+			'change_reg_status'                  => array(
227
+				'func'       => '_change_reg_status',
228
+				'noheader'   => true,
229
+				'capability' => 'ee_edit_registration',
230
+				'obj_id'     => $reg_id,
231
+			),
232
+			'approve_registration'               => array(
233
+				'func'       => 'approve_registration',
234
+				'noheader'   => true,
235
+				'capability' => 'ee_edit_registration',
236
+				'obj_id'     => $reg_id,
237
+			),
238
+			'approve_and_notify_registration'    => array(
239
+				'func'       => 'approve_registration',
240
+				'noheader'   => true,
241
+				'args'       => array(true),
242
+				'capability' => 'ee_edit_registration',
243
+				'obj_id'     => $reg_id,
244
+			),
245
+			'approve_registrations'               => array(
246
+				'func'       => 'bulk_action_on_registrations',
247
+				'noheader'   => true,
248
+				'capability' => 'ee_edit_registrations',
249
+				'args' => array('approve')
250
+			),
251
+			'approve_and_notify_registrations'               => array(
252
+				'func'       => 'bulk_action_on_registrations',
253
+				'noheader'   => true,
254
+				'capability' => 'ee_edit_registrations',
255
+				'args' => array('approve', true)
256
+			),
257
+			'decline_registration'               => array(
258
+				'func'       => 'decline_registration',
259
+				'noheader'   => true,
260
+				'capability' => 'ee_edit_registration',
261
+				'obj_id'     => $reg_id,
262
+			),
263
+			'decline_and_notify_registration'    => array(
264
+				'func'       => 'decline_registration',
265
+				'noheader'   => true,
266
+				'args'       => array(true),
267
+				'capability' => 'ee_edit_registration',
268
+				'obj_id'     => $reg_id,
269
+			),
270
+			'decline_registrations'               => array(
271
+				'func'       => 'bulk_action_on_registrations',
272
+				'noheader'   => true,
273
+				'capability' => 'ee_edit_registrations',
274
+				'args' => array('decline')
275
+			),
276
+			'decline_and_notify_registrations'    => array(
277
+				'func'       => 'bulk_action_on_registrations',
278
+				'noheader'   => true,
279
+				'capability' => 'ee_edit_registrations',
280
+				'args' => array('decline', true)
281
+			),
282
+			'pending_registration'               => array(
283
+				'func'       => 'pending_registration',
284
+				'noheader'   => true,
285
+				'capability' => 'ee_edit_registration',
286
+				'obj_id'     => $reg_id,
287
+			),
288
+			'pending_and_notify_registration'    => array(
289
+				'func'       => 'pending_registration',
290
+				'noheader'   => true,
291
+				'args'       => array(true),
292
+				'capability' => 'ee_edit_registration',
293
+				'obj_id'     => $reg_id,
294
+			),
295
+			'pending_registrations'               => array(
296
+				'func'       => 'bulk_action_on_registrations',
297
+				'noheader'   => true,
298
+				'capability' => 'ee_edit_registrations',
299
+				'args' => array('pending')
300
+			),
301
+			'pending_and_notify_registrations'    => array(
302
+				'func'       => 'bulk_action_on_registrations',
303
+				'noheader'   => true,
304
+				'capability' => 'ee_edit_registrations',
305
+				'args' => array('pending', true)
306
+			),
307
+			'no_approve_registration'            => array(
308
+				'func'       => 'not_approve_registration',
309
+				'noheader'   => true,
310
+				'capability' => 'ee_edit_registration',
311
+				'obj_id'     => $reg_id,
312
+			),
313
+			'no_approve_and_notify_registration' => array(
314
+				'func'       => 'not_approve_registration',
315
+				'noheader'   => true,
316
+				'args'       => array(true),
317
+				'capability' => 'ee_edit_registration',
318
+				'obj_id'     => $reg_id,
319
+			),
320
+			'no_approve_registrations'            => array(
321
+				'func'       => 'bulk_action_on_registrations',
322
+				'noheader'   => true,
323
+				'capability' => 'ee_edit_registrations',
324
+				'args' => array('no_approve')
325
+			),
326
+			'no_approve_and_notify_registrations' => array(
327
+				'func'       => 'bulk_action_on_registrations',
328
+				'noheader'   => true,
329
+				'capability' => 'ee_edit_registrations',
330
+				'args' => array('no_approve', true)
331
+			),
332
+			'cancel_registration'                => array(
333
+				'func'       => 'cancel_registration',
334
+				'noheader'   => true,
335
+				'capability' => 'ee_edit_registration',
336
+				'obj_id'     => $reg_id,
337
+			),
338
+			'cancel_and_notify_registration'     => array(
339
+				'func'       => 'cancel_registration',
340
+				'noheader'   => true,
341
+				'args'       => array(true),
342
+				'capability' => 'ee_edit_registration',
343
+				'obj_id'     => $reg_id,
344
+			),
345
+			'cancel_registrations'                => array(
346
+				'func'       => 'bulk_action_on_registrations',
347
+				'noheader'   => true,
348
+				'capability' => 'ee_edit_registrations',
349
+				'args' => array('cancel')
350
+			),
351
+			'cancel_and_notify_registrations'     => array(
352
+				'func'       => 'bulk_action_on_registrations',
353
+				'noheader'   => true,
354
+				'capability' => 'ee_edit_registrations',
355
+				'args' => array('cancel', true)
356
+			),
357
+			'wait_list_registration' => array(
358
+				'func'       => 'wait_list_registration',
359
+				'noheader'   => true,
360
+				'capability' => 'ee_edit_registration',
361
+				'obj_id'     => $reg_id,
362
+			),
363
+			'contact_list'                       => array(
364
+				'func'       => '_attendee_contact_list_table',
365
+				'capability' => 'ee_read_contacts',
366
+			),
367
+			'add_new_attendee'                   => array(
368
+				'func' => '_create_new_cpt_item',
369
+				'args' => array(
370
+					'new_attendee' => true,
371
+					'capability'   => 'ee_edit_contacts',
372
+				),
373
+			),
374
+			'edit_attendee'                      => array(
375
+				'func'       => '_edit_cpt_item',
376
+				'capability' => 'ee_edit_contacts',
377
+				'obj_id'     => $att_id,
378
+			),
379
+			'duplicate_attendee'                 => array(
380
+				'func'       => '_duplicate_attendee',
381
+				'noheader'   => true,
382
+				'capability' => 'ee_edit_contacts',
383
+				'obj_id'     => $att_id,
384
+			),
385
+			'insert_attendee'                    => array(
386
+				'func'       => '_insert_or_update_attendee',
387
+				'args'       => array(
388
+					'new_attendee' => true,
389
+				),
390
+				'noheader'   => true,
391
+				'capability' => 'ee_edit_contacts',
392
+			),
393
+			'update_attendee'                    => array(
394
+				'func'       => '_insert_or_update_attendee',
395
+				'args'       => array(
396
+					'new_attendee' => false,
397
+				),
398
+				'noheader'   => true,
399
+				'capability' => 'ee_edit_contacts',
400
+				'obj_id'     => $att_id,
401
+			),
402
+			'trash_attendees' => array(
403
+				'func' => '_trash_or_restore_attendees',
404
+				'args' => array(
405
+					'trash' => 'true'
406
+				),
407
+				'noheader' => true,
408
+				'capability' => 'ee_delete_contacts'
409
+			),
410
+			'trash_attendee'                    => array(
411
+				'func'       => '_trash_or_restore_attendees',
412
+				'args'       => array(
413
+					'trash' => true,
414
+				),
415
+				'noheader'   => true,
416
+				'capability' => 'ee_delete_contacts',
417
+				'obj_id'     => $att_id,
418
+			),
419
+			'restore_attendees'                  => array(
420
+				'func'       => '_trash_or_restore_attendees',
421
+				'args'       => array(
422
+					'trash' => false,
423
+				),
424
+				'noheader'   => true,
425
+				'capability' => 'ee_delete_contacts',
426
+				'obj_id'     => $att_id,
427
+			),
428
+			'resend_registration'                => array(
429
+				'func'       => '_resend_registration',
430
+				'noheader'   => true,
431
+				'capability' => 'ee_send_message',
432
+			),
433
+			'registrations_report'               => array(
434
+				'func'       => '_registrations_report',
435
+				'noheader'   => true,
436
+				'capability' => 'ee_read_registrations',
437
+			),
438
+			'contact_list_export'                => array(
439
+				'func'       => '_contact_list_export',
440
+				'noheader'   => true,
441
+				'capability' => 'export',
442
+			),
443
+			'contact_list_report'                => array(
444
+				'func'       => '_contact_list_report',
445
+				'noheader'   => true,
446
+				'capability' => 'ee_read_contacts',
447
+			),
448
+		);
449
+	}
450
+
451
+
452
+	protected function _set_page_config()
453
+	{
454
+		$this->_page_config = array(
455
+			'default'           => array(
456
+				'nav'           => array(
457
+					'label' => esc_html__('Overview', 'event_espresso'),
458
+					'order' => 5,
459
+				),
460
+				'help_tabs'     => array(
461
+					'registrations_overview_help_tab'                       => array(
462
+						'title'    => esc_html__('Registrations Overview', 'event_espresso'),
463
+						'filename' => 'registrations_overview',
464
+					),
465
+					'registrations_overview_table_column_headings_help_tab' => array(
466
+						'title'    => esc_html__('Registrations Table Column Headings', 'event_espresso'),
467
+						'filename' => 'registrations_overview_table_column_headings',
468
+					),
469
+					'registrations_overview_filters_help_tab'               => array(
470
+						'title'    => esc_html__('Registration Filters', 'event_espresso'),
471
+						'filename' => 'registrations_overview_filters',
472
+					),
473
+					'registrations_overview_views_help_tab'                 => array(
474
+						'title'    => esc_html__('Registration Views', 'event_espresso'),
475
+						'filename' => 'registrations_overview_views',
476
+					),
477
+					'registrations_regoverview_other_help_tab'              => array(
478
+						'title'    => esc_html__('Registrations Other', 'event_espresso'),
479
+						'filename' => 'registrations_overview_other',
480
+					),
481
+				),
482
+				'help_tour'     => array('Registration_Overview_Help_Tour'),
483
+				'qtips'         => array('Registration_List_Table_Tips'),
484
+				'list_table'    => 'EE_Registrations_List_Table',
485
+				'require_nonce' => false,
486
+			),
487
+			'view_registration' => array(
488
+				'nav'           => array(
489
+					'label'      => esc_html__('REG Details', 'event_espresso'),
490
+					'order'      => 15,
491
+					'url'        => isset($this->_req_data['_REG_ID'])
492
+						? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
493
+						: $this->_admin_base_url,
494
+					'persistent' => false,
495
+				),
496
+				'help_tabs'     => array(
497
+					'registrations_details_help_tab'                    => array(
498
+						'title'    => esc_html__('Registration Details', 'event_espresso'),
499
+						'filename' => 'registrations_details',
500
+					),
501
+					'registrations_details_table_help_tab'              => array(
502
+						'title'    => esc_html__('Registration Details Table', 'event_espresso'),
503
+						'filename' => 'registrations_details_table',
504
+					),
505
+					'registrations_details_form_answers_help_tab'       => array(
506
+						'title'    => esc_html__('Registration Form Answers', 'event_espresso'),
507
+						'filename' => 'registrations_details_form_answers',
508
+					),
509
+					'registrations_details_registrant_details_help_tab' => array(
510
+						'title'    => esc_html__('Contact Details', 'event_espresso'),
511
+						'filename' => 'registrations_details_registrant_details',
512
+					),
513
+				),
514
+				'help_tour'     => array('Registration_Details_Help_Tour'),
515
+				'metaboxes'     => array_merge(
516
+					$this->_default_espresso_metaboxes,
517
+					array('_registration_details_metaboxes')
518
+				),
519
+				'require_nonce' => false,
520
+			),
521
+			'new_registration'  => array(
522
+				'nav'           => array(
523
+					'label'      => esc_html__('Add New Registration', 'event_espresso'),
524
+					'url'        => '#',
525
+					'order'      => 15,
526
+					'persistent' => false,
527
+				),
528
+				'metaboxes'     => $this->_default_espresso_metaboxes,
529
+				'labels'        => array(
530
+					'publishbox' => esc_html__('Save Registration', 'event_espresso'),
531
+				),
532
+				'require_nonce' => false,
533
+			),
534
+			'add_new_attendee'  => array(
535
+				'nav'           => array(
536
+					'label'      => esc_html__('Add Contact', 'event_espresso'),
537
+					'order'      => 15,
538
+					'persistent' => false,
539
+				),
540
+				'metaboxes'     => array_merge(
541
+					$this->_default_espresso_metaboxes,
542
+					array('_publish_post_box', 'attendee_editor_metaboxes')
543
+				),
544
+				'require_nonce' => false,
545
+			),
546
+			'edit_attendee'     => array(
547
+				'nav'           => array(
548
+					'label'      => esc_html__('Edit Contact', 'event_espresso'),
549
+					'order'      => 15,
550
+					'persistent' => false,
551
+					'url'        => isset($this->_req_data['ATT_ID'])
552
+						? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
553
+						: $this->_admin_base_url,
554
+				),
555
+				'metaboxes'     => array('attendee_editor_metaboxes'),
556
+				'require_nonce' => false,
557
+			),
558
+			'contact_list'      => array(
559
+				'nav'           => array(
560
+					'label' => esc_html__('Contact List', 'event_espresso'),
561
+					'order' => 20,
562
+				),
563
+				'list_table'    => 'EE_Attendee_Contact_List_Table',
564
+				'help_tabs'     => array(
565
+					'registrations_contact_list_help_tab'                       => array(
566
+						'title'    => esc_html__('Registrations Contact List', 'event_espresso'),
567
+						'filename' => 'registrations_contact_list',
568
+					),
569
+					'registrations_contact-list_table_column_headings_help_tab' => array(
570
+						'title'    => esc_html__('Contact List Table Column Headings', 'event_espresso'),
571
+						'filename' => 'registrations_contact_list_table_column_headings',
572
+					),
573
+					'registrations_contact_list_views_help_tab'                 => array(
574
+						'title'    => esc_html__('Contact List Views', 'event_espresso'),
575
+						'filename' => 'registrations_contact_list_views',
576
+					),
577
+					'registrations_contact_list_other_help_tab'                 => array(
578
+						'title'    => esc_html__('Contact List Other', 'event_espresso'),
579
+						'filename' => 'registrations_contact_list_other',
580
+					),
581
+				),
582
+				'help_tour'     => array('Contact_List_Help_Tour'),
583
+				'metaboxes'     => array(),
584
+				'require_nonce' => false,
585
+			),
586
+			//override default cpt routes
587
+			'create_new'        => '',
588
+			'edit'              => '',
589
+		);
590
+	}
591
+
592
+
593
+	/**
594
+	 * The below methods aren't used by this class currently
595
+	 */
596
+	protected function _add_screen_options()
597
+	{
598
+	}
599
+
600
+
601
+	protected function _add_feature_pointers()
602
+	{
603
+	}
604
+
605
+
606
+	public function admin_init()
607
+	{
608
+		EE_Registry::$i18n_js_strings['update_att_qstns'] = esc_html__(
609
+			'click "Update Registration Questions" to save your changes',
610
+			'event_espresso'
611
+		);
612
+	}
613
+
614
+
615
+	public function admin_notices()
616
+	{
617
+	}
618
+
619
+
620
+	public function admin_footer_scripts()
621
+	{
622
+	}
623
+
624
+
625
+	/**
626
+	 *        get list of registration statuses
627
+	 *
628
+	 * @access private
629
+	 * @return void
630
+	 */
631
+	private function _get_registration_status_array()
632
+	{
633
+		self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
634
+	}
635
+
636
+
637
+	protected function _add_screen_options_default()
638
+	{
639
+		$this->_per_page_screen_option();
640
+	}
641
+
642
+
643
+	protected function _add_screen_options_contact_list()
644
+	{
645
+		$page_title              = $this->_admin_page_title;
646
+		$this->_admin_page_title = esc_html__("Contacts", 'event_espresso');
647
+		$this->_per_page_screen_option();
648
+		$this->_admin_page_title = $page_title;
649
+	}
650
+
651
+
652
+	public function load_scripts_styles()
653
+	{
654
+		//style
655
+		wp_register_style(
656
+			'espresso_reg',
657
+			REG_ASSETS_URL . 'espresso_registrations_admin.css',
658
+			array('ee-admin-css'),
659
+			EVENT_ESPRESSO_VERSION
660
+		);
661
+		wp_enqueue_style('espresso_reg');
662
+		//script
663
+		wp_register_script(
664
+			'espresso_reg',
665
+			REG_ASSETS_URL . 'espresso_registrations_admin.js',
666
+			array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'),
667
+			EVENT_ESPRESSO_VERSION,
668
+			true
669
+		);
670
+		wp_enqueue_script('espresso_reg');
671
+	}
672
+
673
+
674
+	public function load_scripts_styles_edit_attendee()
675
+	{
676
+		//stuff to only show up on our attendee edit details page.
677
+		$attendee_details_translations = array(
678
+			'att_publish_text' => sprintf(
679
+				esc_html__('Created on: <b>%1$s</b>', 'event_espresso'),
680
+				$this->_cpt_model_obj->get_datetime('ATT_created')
681
+			),
682
+		);
683
+		wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
684
+		wp_enqueue_script('jquery-validate');
685
+	}
686
+
687
+
688
+	public function load_scripts_styles_view_registration()
689
+	{
690
+		//styles
691
+		wp_enqueue_style('espresso-ui-theme');
692
+		//scripts
693
+		$this->_get_reg_custom_questions_form($this->_registration->ID());
694
+		$this->_reg_custom_questions_form->wp_enqueue_scripts(true);
695
+	}
696
+
697
+
698
+	public function load_scripts_styles_contact_list()
699
+	{
700
+		wp_deregister_style('espresso_reg');
701
+		wp_register_style(
702
+			'espresso_att',
703
+			REG_ASSETS_URL . 'espresso_attendees_admin.css',
704
+			array('ee-admin-css'),
705
+			EVENT_ESPRESSO_VERSION
706
+		);
707
+		wp_enqueue_style('espresso_att');
708
+	}
709
+
710
+
711
+	public function load_scripts_styles_new_registration()
712
+	{
713
+		wp_register_script(
714
+			'ee-spco-for-admin',
715
+			REG_ASSETS_URL . 'spco_for_admin.js',
716
+			array('underscore', 'jquery'),
717
+			EVENT_ESPRESSO_VERSION,
718
+			true
719
+		);
720
+		wp_enqueue_script('ee-spco-for-admin');
721
+		add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
722
+		EE_Form_Section_Proper::wp_enqueue_scripts();
723
+		EED_Ticket_Selector::load_tckt_slctr_assets();
724
+		EE_Datepicker_Input::enqueue_styles_and_scripts();
725
+	}
726
+
727
+
728
+	public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
729
+	{
730
+		add_filter('FHEE_load_EE_messages', '__return_true');
731
+	}
732
+
733
+
734
+	public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
735
+	{
736
+		add_filter('FHEE_load_EE_messages', '__return_true');
737
+	}
738
+
739
+
740
+	protected function _set_list_table_views_default()
741
+	{
742
+		//for notification related bulk actions we need to make sure only active messengers have an option.
743
+		EED_Messages::set_autoloaders();
744
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
745
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
746
+		$active_mts               = $message_resource_manager->list_of_active_message_types();
747
+		//key= bulk_action_slug, value= message type.
748
+		$match_array = array(
749
+			'approve_registrations'    => 'registration',
750
+			'decline_registrations'    => 'declined_registration',
751
+			'pending_registrations'    => 'pending_approval',
752
+			'no_approve_registrations' => 'not_approved_registration',
753
+			'cancel_registrations'     => 'cancelled_registration',
754
+		);
755
+		$can_send = EE_Registry::instance()->CAP->current_user_can(
756
+			'ee_send_message',
757
+			'batch_send_messages'
758
+		);
759
+		/** setup reg status bulk actions **/
760
+		$def_reg_status_actions['approve_registrations'] = esc_html__('Approve Registrations', 'event_espresso');
761
+		if ($can_send && in_array($match_array['approve_registrations'], $active_mts, true)) {
762
+				$def_reg_status_actions['approve_and_notify_registrations'] = esc_html__(
763
+					'Approve and Notify Registrations',
764
+					'event_espresso'
765
+				);
766
+		}
767
+		$def_reg_status_actions['decline_registrations'] = esc_html__('Decline Registrations', 'event_espresso');
768
+		if ($can_send && in_array($match_array['decline_registrations'], $active_mts, true)) {
769
+				$def_reg_status_actions['decline_and_notify_registrations'] = esc_html__(
770
+					'Decline and Notify Registrations',
771
+					'event_espresso'
772
+				);
773
+		}
774
+		$def_reg_status_actions['pending_registrations'] = esc_html__(
775
+			'Set Registrations to Pending Payment',
776
+			'event_espresso'
777
+		);
778
+		if ($can_send && in_array($match_array['pending_registrations'], $active_mts, true)) {
779
+				$def_reg_status_actions['pending_and_notify_registrations'] = esc_html__(
780
+					'Set Registrations to Pending Payment and Notify',
781
+					'event_espresso'
782
+				);
783
+		}
784
+		$def_reg_status_actions['no_approve_registrations'] = esc_html__(
785
+			'Set Registrations to Not Approved',
786
+			'event_espresso'
787
+		);
788
+		if ($can_send && in_array($match_array['no_approve_registrations'], $active_mts, true)) {
789
+				$def_reg_status_actions['no_approve_and_notify_registrations'] = esc_html__(
790
+					'Set Registrations to Not Approved and Notify',
791
+					'event_espresso'
792
+				);
793
+		}
794
+		$def_reg_status_actions['cancel_registrations'] = esc_html__('Cancel Registrations', 'event_espresso');
795
+		if ($can_send && in_array($match_array['cancel_registrations'], $active_mts, true)) {
796
+				$def_reg_status_actions['cancel_and_notify_registrations'] = esc_html__(
797
+					'Cancel Registrations and Notify',
798
+					'event_espresso'
799
+				);
800
+		}
801
+		$def_reg_status_actions = apply_filters(
802
+			'FHEE__Registrations_Admin_Page___set_list_table_views_default__def_reg_status_actions_array',
803
+			$def_reg_status_actions,
804
+			$active_mts
805
+		);
806
+
807
+		$this->_views = array(
808
+			'all'   => array(
809
+				'slug'        => 'all',
810
+				'label'       => esc_html__('View All Registrations', 'event_espresso'),
811
+				'count'       => 0,
812
+				'bulk_action' => array_merge($def_reg_status_actions, array(
813
+					'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
814
+				)),
815
+			),
816
+			'month' => array(
817
+				'slug'        => 'month',
818
+				'label'       => esc_html__('This Month', 'event_espresso'),
819
+				'count'       => 0,
820
+				'bulk_action' => array_merge($def_reg_status_actions, array(
821
+					'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
822
+				)),
823
+			),
824
+			'today' => array(
825
+				'slug'        => 'today',
826
+				'label'       => sprintf(
827
+					esc_html__('Today - %s', 'event_espresso'),
828
+					date('M d, Y', current_time('timestamp'))
829
+				),
830
+				'count'       => 0,
831
+				'bulk_action' => array_merge($def_reg_status_actions, array(
832
+					'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
833
+				)),
834
+			),
835
+		);
836
+		if (EE_Registry::instance()->CAP->current_user_can(
837
+			'ee_delete_registrations',
838
+			'espresso_registrations_delete_registration'
839
+		)) {
840
+			$this->_views['incomplete'] = array(
841
+				'slug'        => 'incomplete',
842
+				'label'       => esc_html__('Incomplete', 'event_espresso'),
843
+				'count'       => 0,
844
+				'bulk_action' => array(
845
+					'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
846
+				),
847
+			);
848
+			$this->_views['trash']      = array(
849
+				'slug'        => 'trash',
850
+				'label'       => esc_html__('Trash', 'event_espresso'),
851
+				'count'       => 0,
852
+				'bulk_action' => array(
853
+					'restore_registrations' => esc_html__('Restore Registrations', 'event_espresso'),
854
+					'delete_registrations'  => esc_html__('Delete Registrations Permanently', 'event_espresso'),
855
+				),
856
+			);
857
+		}
858
+	}
859
+
860
+
861
+	protected function _set_list_table_views_contact_list()
862
+	{
863
+		$this->_views = array(
864
+			'in_use' => array(
865
+				'slug'        => 'in_use',
866
+				'label'       => esc_html__('In Use', 'event_espresso'),
867
+				'count'       => 0,
868
+				'bulk_action' => array(
869
+					'trash_attendees' => esc_html__('Move to Trash', 'event_espresso'),
870
+				),
871
+			),
872
+		);
873
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_contacts',
874
+			'espresso_registrations_trash_attendees')
875
+		) {
876
+			$this->_views['trash'] = array(
877
+				'slug'        => 'trash',
878
+				'label'       => esc_html__('Trash', 'event_espresso'),
879
+				'count'       => 0,
880
+				'bulk_action' => array(
881
+					'restore_attendees' => esc_html__('Restore from Trash', 'event_espresso'),
882
+				),
883
+			);
884
+		}
885
+	}
886
+
887
+
888
+	protected function _registration_legend_items()
889
+	{
890
+		$fc_items = array(
891
+			'star-icon'        => array(
892
+				'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
893
+				'desc'  => esc_html__('This is the Primary Registrant', 'event_espresso'),
894
+			),
895
+			'view_details'     => array(
896
+				'class' => 'dashicons dashicons-clipboard',
897
+				'desc'  => esc_html__('View Registration Details', 'event_espresso'),
898
+			),
899
+			'edit_attendee'    => array(
900
+				'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
901
+				'desc'  => esc_html__('Edit Contact Details', 'event_espresso'),
902
+			),
903
+			'view_transaction' => array(
904
+				'class' => 'dashicons dashicons-cart',
905
+				'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
906
+			),
907
+			'view_invoice'     => array(
908
+				'class' => 'dashicons dashicons-media-spreadsheet',
909
+				'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
910
+			),
911
+		);
912
+		if (EE_Registry::instance()->CAP->current_user_can(
913
+			'ee_send_message',
914
+			'espresso_registrations_resend_registration'
915
+		)) {
916
+			$fc_items['resend_registration'] = array(
917
+				'class' => 'dashicons dashicons-email-alt',
918
+				'desc'  => esc_html__('Resend Registration Details', 'event_espresso'),
919
+			);
920
+		} else {
921
+			$fc_items['blank'] = array('class' => 'blank', 'desc' => '');
922
+		}
923
+		if (EE_Registry::instance()->CAP->current_user_can(
924
+			'ee_read_global_messages',
925
+			'view_filtered_messages'
926
+		)) {
927
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
928
+			if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
929
+				$fc_items['view_related_messages'] = array(
930
+					'class' => $related_for_icon['css_class'],
931
+					'desc'  => $related_for_icon['label'],
932
+				);
933
+			}
934
+		}
935
+		$sc_items = array(
936
+			'approved_status'   => array(
937
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
938
+				'desc'  => EEH_Template::pretty_status(
939
+					EEM_Registration::status_id_approved,
940
+					false,
941
+					'sentence'
942
+				),
943
+			),
944
+			'pending_status'    => array(
945
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
946
+				'desc'  => EEH_Template::pretty_status(
947
+					EEM_Registration::status_id_pending_payment,
948
+					false,
949
+					'sentence'
950
+				),
951
+			),
952
+			'wait_list'         => array(
953
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
954
+				'desc'  => EEH_Template::pretty_status(
955
+					EEM_Registration::status_id_wait_list,
956
+					false,
957
+					'sentence'
958
+				),
959
+			),
960
+			'incomplete_status' => array(
961
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
962
+				'desc'  => EEH_Template::pretty_status(
963
+					EEM_Registration::status_id_incomplete,
964
+					false,
965
+					'sentence'
966
+				),
967
+			),
968
+			'not_approved'      => array(
969
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
970
+				'desc'  => EEH_Template::pretty_status(
971
+					EEM_Registration::status_id_not_approved,
972
+					false,
973
+					'sentence'
974
+				),
975
+			),
976
+			'declined_status'   => array(
977
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
978
+				'desc'  => EEH_Template::pretty_status(
979
+					EEM_Registration::status_id_declined,
980
+					false,
981
+					'sentence'
982
+				),
983
+			),
984
+			'cancelled_status'  => array(
985
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
986
+				'desc'  => EEH_Template::pretty_status(
987
+					EEM_Registration::status_id_cancelled,
988
+					false,
989
+					'sentence'
990
+				),
991
+			),
992
+		);
993
+		return array_merge($fc_items, $sc_items);
994
+	}
995
+
996
+
997
+
998
+	/***************************************        REGISTRATION OVERVIEW        **************************************/
999
+	/**
1000
+	 * @throws \EE_Error
1001
+	 */
1002
+	protected function _registrations_overview_list_table()
1003
+	{
1004
+		$this->_template_args['admin_page_header'] = '';
1005
+		$EVT_ID                                    = ! empty($this->_req_data['event_id'])
1006
+			? absint($this->_req_data['event_id'])
1007
+			: 0;
1008
+		if ($EVT_ID) {
1009
+			if (EE_Registry::instance()->CAP->current_user_can(
1010
+				'ee_edit_registrations',
1011
+				'espresso_registrations_new_registration',
1012
+				$EVT_ID
1013
+			)) {
1014
+				$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
1015
+					'new_registration',
1016
+					'add-registrant',
1017
+					array('event_id' => $EVT_ID),
1018
+					'add-new-h2'
1019
+				);
1020
+			}
1021
+			$event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
1022
+			if ($event instanceof EE_Event) {
1023
+				$this->_template_args['admin_page_header'] = sprintf(
1024
+					esc_html__(
1025
+						'%s Viewing registrations for the event: %s%s',
1026
+						'event_espresso'
1027
+					),
1028
+					'<h3 style="line-height:1.5em;">',
1029
+					'<br /><a href="'
1030
+						. EE_Admin_Page::add_query_args_and_nonce(
1031
+							array(
1032
+								'action' => 'edit',
1033
+								'post'   => $event->ID(),
1034
+							),
1035
+							EVENTS_ADMIN_URL
1036
+						)
1037
+						. '">&nbsp;'
1038
+						. $event->get('EVT_name')
1039
+						. '&nbsp;</a>&nbsp;',
1040
+					'</h3>'
1041
+				);
1042
+			}
1043
+			$DTT_ID   = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
1044
+			$datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1045
+			if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
1046
+				$this->_template_args['admin_page_header'] = substr(
1047
+					$this->_template_args['admin_page_header'],
1048
+					0,
1049
+					-5
1050
+				);
1051
+				$this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
1052
+				$this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
1053
+				$this->_template_args['admin_page_header'] .= $datetime->name();
1054
+				$this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
1055
+				$this->_template_args['admin_page_header'] .= '</span></h3>';
1056
+			}
1057
+		}
1058
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
1059
+		$this->display_admin_list_table_page_with_no_sidebar();
1060
+	}
1061
+
1062
+
1063
+	/**
1064
+	 * This sets the _registration property for the registration details screen
1065
+	 *
1066
+	 * @access private
1067
+	 * @return bool
1068
+	 */
1069
+	private function _set_registration_object()
1070
+	{
1071
+		//get out if we've already set the object
1072
+		if (is_object($this->_registration)) {
1073
+			return true;
1074
+		}
1075
+		$REG    = EEM_Registration::instance();
1076
+		$REG_ID = ( ! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
1077
+		if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
1078
+			return true;
1079
+		} else {
1080
+			$error_msg = sprintf(
1081
+				esc_html__(
1082
+					'An error occurred and the details for Registration ID #%s could not be retrieved.',
1083
+					'event_espresso'
1084
+				),
1085
+				$REG_ID
1086
+			);
1087
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
1088
+			$this->_registration = null;
1089
+			return false;
1090
+		}
1091
+	}
1092
+
1093
+
1094
+	/**
1095
+	 * Used to retrieve registrations for the list table.
1096
+	 *
1097
+	 * @param int  $per_page
1098
+	 * @param bool $count
1099
+	 * @param bool $this_month
1100
+	 * @param bool $today
1101
+	 * @return EE_Registration[]|int
1102
+	 * @throws EE_Error
1103
+	 */
1104
+	public function get_registrations(
1105
+		$per_page = 10,
1106
+		$count = false,
1107
+		$this_month = false,
1108
+		$today = false
1109
+	) {
1110
+		if ($this_month) {
1111
+			$this->_req_data['status'] = 'month';
1112
+		}
1113
+		if ($today) {
1114
+			$this->_req_data['status'] = 'today';
1115
+		}
1116
+		$query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
1117
+		/**
1118
+		 * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1119
+		 * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1120
+		 * @see EEM_Base::get_all()
1121
+		 */
1122
+		$query_params['group_by'] = '';
1123
+
1124
+		return $count
1125
+			? EEM_Registration::instance()->count($query_params)
1126
+			/** @type EE_Registration[] */
1127
+			: EEM_Registration::instance()->get_all($query_params);
1128
+	}
1129
+
1130
+
1131
+
1132
+	/**
1133
+	 * Retrieves the query parameters to be used by the Registration model for getting registrations.
1134
+	 * Note: this listens to values on the request for some of the query parameters.
1135
+	 *
1136
+	 * @param array $request
1137
+	 * @param int    $per_page
1138
+	 * @param bool   $count
1139
+	 * @return array
1140
+	 */
1141
+	protected function _get_registration_query_parameters(
1142
+		$request = array(),
1143
+		$per_page = 10,
1144
+		$count = false
1145
+	) {
1146
+
1147
+		$query_params = array(
1148
+			0                          => $this->_get_where_conditions_for_registrations_query(
1149
+				$request
1150
+			),
1151
+			'caps'                     => EEM_Registration::caps_read_admin,
1152
+			'default_where_conditions' => 'this_model_only',
1153
+		);
1154
+		if (! $count) {
1155
+			$query_params = array_merge(
1156
+				$query_params,
1157
+				$this->_get_orderby_for_registrations_query(),
1158
+				$this->_get_limit($per_page)
1159
+			);
1160
+		}
1161
+
1162
+		return $query_params;
1163
+	}
1164
+
1165
+
1166
+	/**
1167
+	 * This will add EVT_ID to the provided $where array for EE model query parameters.
1168
+	 *
1169
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1170
+	 * @return array
1171
+	 */
1172
+	protected function _add_event_id_to_where_conditions(array $request)
1173
+	{
1174
+		$where = array();
1175
+		if (! empty($request['event_id'])) {
1176
+			$where['EVT_ID'] = absint($request['event_id']);
1177
+		}
1178
+		return $where;
1179
+	}
1180
+
1181
+
1182
+	/**
1183
+	 * Adds category ID if it exists in the request to the where conditions for the registrations query.
1184
+	 *
1185
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1186
+	 * @return array
1187
+	 */
1188
+	protected function _add_category_id_to_where_conditions(array $request)
1189
+	{
1190
+		$where = array();
1191
+		if (! empty($request['EVT_CAT']) && (int)$request['EVT_CAT'] !== -1) {
1192
+			$where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1193
+		}
1194
+		return $where;
1195
+	}
1196
+
1197
+
1198
+	/**
1199
+	 * Adds the datetime ID if it exists in the request to the where conditions for the registrations query.
1200
+	 *
1201
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1202
+	 * @return array
1203
+	 */
1204
+	protected function _add_datetime_id_to_where_conditions(array $request)
1205
+	{
1206
+		$where = array();
1207
+		if (! empty($request['datetime_id'])) {
1208
+			$where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1209
+		}
1210
+		if (! empty($request['DTT_ID'])) {
1211
+			$where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1212
+		}
1213
+		return $where;
1214
+	}
1215
+
1216
+
1217
+	/**
1218
+	 * Adds the correct registration status to the where conditions for the registrations query.
1219
+	 *
1220
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1221
+	 * @return array
1222
+	 */
1223
+	protected function _add_registration_status_to_where_conditions(array $request)
1224
+	{
1225
+		$where = array();
1226
+		$view = EEH_Array::is_set($request, 'status', '');
1227
+		$registration_status = ! empty($request['_reg_status'])
1228
+			? sanitize_text_field($request['_reg_status'])
1229
+			: '';
1230
+
1231
+		/*
1232 1232
          * If filtering by registration status, then we show registrations matching that status.
1233 1233
          * If not filtering by specified status, then we show all registrations excluding incomplete registrations
1234 1234
          * UNLESS viewing trashed registrations.
1235 1235
          */
1236
-        if (! empty($registration_status)) {
1237
-            $where['STS_ID'] = $registration_status;
1238
-        } else {
1239
-            //make sure we exclude incomplete registrations, but only if not trashed.
1240
-            if ($view === 'trash') {
1241
-                $where['REG_deleted'] = true;
1242
-            } elseif ($view === 'incomplete') {
1243
-                $where['STS_ID'] = EEM_Registration::status_id_incomplete;
1244
-            } else {
1245
-                $where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1246
-            }
1247
-        }
1248
-        return $where;
1249
-    }
1250
-
1251
-
1252
-    /**
1253
-     * Adds any provided date restraints to the where conditions for the registrations query.
1254
-     *
1255
-     * @param array $request usually the same as $this->_req_data but not necessarily
1256
-     * @return array
1257
-     * @throws EE_Error
1258
-     */
1259
-    protected function _add_date_to_where_conditions(array $request)
1260
-    {
1261
-        $where = array();
1262
-        $view = EEH_Array::is_set($request, 'status', '');
1263
-        $month_range             = ! empty($request['month_range'])
1264
-            ? sanitize_text_field($request['month_range'])
1265
-            : '';
1266
-        $retrieve_for_today      = $view === 'today';
1267
-        $retrieve_for_this_month = $view === 'month';
1268
-
1269
-        if ($retrieve_for_today) {
1270
-            $now               = date('Y-m-d', current_time('timestamp'));
1271
-            $where['REG_date'] = array(
1272
-                'BETWEEN',
1273
-                array(
1274
-                    EEM_Registration::instance()->convert_datetime_for_query(
1275
-                        'REG_date',
1276
-                        $now . ' 00:00:00',
1277
-                        'Y-m-d H:i:s'
1278
-                    ),
1279
-                    EEM_Registration::instance()->convert_datetime_for_query(
1280
-                        'REG_date',
1281
-                        $now . ' 23:59:59',
1282
-                        'Y-m-d H:i:s'
1283
-                    ),
1284
-                ),
1285
-            );
1286
-        } elseif ($retrieve_for_this_month) {
1287
-            $current_year_and_month = date('Y-m', current_time('timestamp'));
1288
-            $days_this_month        = date('t', current_time('timestamp'));
1289
-            $where['REG_date']      = array(
1290
-                'BETWEEN',
1291
-                array(
1292
-                    EEM_Registration::instance()->convert_datetime_for_query(
1293
-                        'REG_date',
1294
-                        $current_year_and_month . '-01 00:00:00',
1295
-                        'Y-m-d H:i:s'
1296
-                    ),
1297
-                    EEM_Registration::instance()->convert_datetime_for_query(
1298
-                        'REG_date',
1299
-                        $current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1300
-                        'Y-m-d H:i:s'
1301
-                    ),
1302
-                ),
1303
-            );
1304
-        } elseif ($month_range) {
1305
-            $pieces          = explode(' ', $month_range, 3);
1306
-            $month_requested = ! empty($pieces[0])
1307
-                ? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0]))
1308
-                : '';
1309
-            $year_requested  = ! empty($pieces[1])
1310
-                ? $pieces[1]
1311
-                : '';
1312
-            //if there is not a month or year then we can't go further
1313
-            if ($month_requested && $year_requested) {
1314
-                $days_in_month     = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1315
-                $where['REG_date'] = array(
1316
-                    'BETWEEN',
1317
-                    array(
1318
-                        EEM_Registration::instance()->convert_datetime_for_query(
1319
-                            'REG_date',
1320
-                            $year_requested . '-' . $month_requested . '-01 00:00:00',
1321
-                            'Y-m-d H:i:s'
1322
-                        ),
1323
-                        EEM_Registration::instance()->convert_datetime_for_query(
1324
-                            'REG_date',
1325
-                            $year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1326
-                            'Y-m-d H:i:s'
1327
-                        ),
1328
-                    ),
1329
-                );
1330
-            }
1331
-        }
1332
-        return $where;
1333
-    }
1334
-
1335
-
1336
-    /**
1337
-     * Adds any provided search restraints to the where conditions for the registrations query
1338
-     *
1339
-     * @param array $request usually the same as $this->_req_data but not necessarily
1340
-     * @return array
1341
-     */
1342
-    protected function _add_search_to_where_conditions(array $request)
1343
-    {
1344
-        $where = array();
1345
-        if (! empty($request['s'])) {
1346
-            $search_string = '%' . sanitize_text_field($request['s']) . '%';
1347
-            $where['OR*search_conditions'] = array(
1348
-                'Event.EVT_name'                          => array('LIKE', $search_string),
1349
-                'Event.EVT_desc'                          => array('LIKE', $search_string),
1350
-                'Event.EVT_short_desc'                    => array('LIKE', $search_string),
1351
-                'Attendee.ATT_full_name'                  => array('LIKE', $search_string),
1352
-                'Attendee.ATT_fname'                      => array('LIKE', $search_string),
1353
-                'Attendee.ATT_lname'                      => array('LIKE', $search_string),
1354
-                'Attendee.ATT_short_bio'                  => array('LIKE', $search_string),
1355
-                'Attendee.ATT_email'                      => array('LIKE', $search_string),
1356
-                'Attendee.ATT_address'                    => array('LIKE', $search_string),
1357
-                'Attendee.ATT_address2'                   => array('LIKE', $search_string),
1358
-                'Attendee.ATT_city'                       => array('LIKE', $search_string),
1359
-                'REG_final_price'                         => array('LIKE', $search_string),
1360
-                'REG_code'                                => array('LIKE', $search_string),
1361
-                'REG_count'                               => array('LIKE', $search_string),
1362
-                'REG_group_size'                          => array('LIKE', $search_string),
1363
-                'Ticket.TKT_name'                         => array('LIKE', $search_string),
1364
-                'Ticket.TKT_description'                  => array('LIKE', $search_string),
1365
-                'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $search_string),
1366
-            );
1367
-        }
1368
-        return $where;
1369
-    }
1370
-
1371
-
1372
-    /**
1373
-     * Sets up the where conditions for the registrations query.
1374
-     *
1375
-     * @param array $request
1376
-     * @return array
1377
-     * @throws EE_Error
1378
-     */
1379
-    protected function _get_where_conditions_for_registrations_query($request)
1380
-    {
1381
-        return apply_filters(
1382
-            'FHEE__Registrations_Admin_Page___get_where_conditions_for_registrations_query',
1383
-            array_merge(
1384
-                $this->_add_event_id_to_where_conditions($request),
1385
-                $this->_add_category_id_to_where_conditions($request),
1386
-                $this->_add_datetime_id_to_where_conditions($request),
1387
-                $this->_add_registration_status_to_where_conditions($request),
1388
-                $this->_add_date_to_where_conditions($request),
1389
-                $this->_add_search_to_where_conditions($request)
1390
-            ),
1391
-            $request
1392
-        );
1393
-    }
1394
-
1395
-
1396
-    /**
1397
-     * Sets up the orderby for the registrations query.
1398
-     *
1399
-     * @return array
1400
-     */
1401
-    protected function _get_orderby_for_registrations_query()
1402
-    {
1403
-        $orderby_field = ! empty($this->_req_data['orderby'])
1404
-            ? sanitize_text_field($this->_req_data['orderby'])
1405
-            : '';
1406
-        switch ($orderby_field) {
1407
-            case '_REG_ID':
1408
-                $orderby_field = 'REG_ID';
1409
-                break;
1410
-            case '_Reg_status':
1411
-                $orderby_field = 'STS_ID';
1412
-                break;
1413
-            case 'ATT_fname':
1414
-                $orderby_field = array('Attendee.ATT_fname', 'Attendee.ATT_lname');
1415
-                break;
1416
-            case 'ATT_lname':
1417
-                $orderby_field = array('Attendee.ATT_lname', 'Attendee.ATT_fname');
1418
-                break;
1419
-            case 'event_name':
1420
-                $orderby_field = 'Event.EVT_name';
1421
-                break;
1422
-            case 'DTT_EVT_start':
1423
-                $orderby_field = 'Event.Datetime.DTT_EVT_start';
1424
-                break;
1425
-            default: //'REG_date'
1426
-                $orderby_field = 'REG_date';
1427
-        }
1428
-
1429
-        //order
1430
-        $order = ! empty($this->_req_data['order'])
1431
-            ? sanitize_text_field($this->_req_data['order'])
1432
-            : 'DESC';
1433
-
1434
-        //mutate orderby_field
1435
-        $orderby_field = array_combine(
1436
-            (array) $orderby_field,
1437
-            array_fill(0, count($orderby_field), $order)
1438
-        );
1439
-        return array('order_by' => $orderby_field);
1440
-    }
1441
-
1442
-
1443
-    /**
1444
-     * Sets up the limit for the registrations query.
1445
-     *
1446
-     * @param $per_page
1447
-     * @return array
1448
-     */
1449
-    protected function _get_limit($per_page)
1450
-    {
1451
-        $current_page = ! empty($this->_req_data['paged'])
1452
-            ? absint($this->_req_data['paged'])
1453
-            : 1;
1454
-        $per_page     = ! empty($this->_req_data['perpage'])
1455
-            ? $this->_req_data['perpage']
1456
-            : $per_page;
1457
-
1458
-        //-1 means return all results so get out if that's set.
1459
-        if ((int)$per_page === -1) {
1460
-            return array();
1461
-        }
1462
-        $per_page = absint($per_page);
1463
-        $offset   = ($current_page - 1) * $per_page;
1464
-        return array('limit' => array($offset, $per_page));
1465
-    }
1466
-
1467
-
1468
-    public function get_registration_status_array()
1469
-    {
1470
-        return self::$_reg_status;
1471
-    }
1472
-
1473
-
1474
-
1475
-
1476
-    /***************************************        REGISTRATION DETAILS        ***************************************/
1477
-    /**
1478
-     *        generates HTML for the View Registration Details Admin page
1479
-     *
1480
-     * @access protected
1481
-     * @return void
1482
-     * @throws DomainException
1483
-     * @throws EE_Error
1484
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1485
-     */
1486
-    protected function _registration_details()
1487
-    {
1488
-        $this->_template_args = array();
1489
-        $this->_set_registration_object();
1490
-        if (is_object($this->_registration)) {
1491
-            $transaction                                   = $this->_registration->transaction()
1492
-                ? $this->_registration->transaction()
1493
-                : EE_Transaction::new_instance();
1494
-            $this->_session                                = $transaction->session_data();
1495
-            $event_id                                      = $this->_registration->event_ID();
1496
-            $this->_template_args['reg_nmbr']['value']     = $this->_registration->ID();
1497
-            $this->_template_args['reg_nmbr']['label']     = esc_html__('Registration Number', 'event_espresso');
1498
-            $this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1499
-            $this->_template_args['reg_datetime']['label'] = esc_html__('Date', 'event_espresso');
1500
-            $this->_template_args['grand_total']           = $transaction->total();
1501
-            $this->_template_args['currency_sign']         = EE_Registry::instance()->CFG->currency->sign;
1502
-            // link back to overview
1503
-            $this->_template_args['reg_overview_url']            = REG_ADMIN_URL;
1504
-            $this->_template_args['registration']                = $this->_registration;
1505
-            $this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(
1506
-                array(
1507
-                    'action'   => 'default',
1508
-                    'event_id' => $event_id,
1509
-                ),
1510
-                REG_ADMIN_URL
1511
-            );
1512
-            $this->_template_args['filtered_transactions_link']  = EE_Admin_Page::add_query_args_and_nonce(
1513
-                array(
1514
-                    'action' => 'default',
1515
-                    'EVT_ID' => $event_id,
1516
-                    'page'   => 'espresso_transactions',
1517
-                ),
1518
-                admin_url('admin.php')
1519
-            );
1520
-            $this->_template_args['event_link']                  = EE_Admin_Page::add_query_args_and_nonce(
1521
-                array(
1522
-                    'page'   => 'espresso_events',
1523
-                    'action' => 'edit',
1524
-                    'post'   => $event_id,
1525
-                ),
1526
-                admin_url('admin.php')
1527
-            );
1528
-            //next and previous links
1529
-            $next_reg                                      = $this->_registration->next(
1530
-                null,
1531
-                array(),
1532
-                'REG_ID'
1533
-            );
1534
-            $this->_template_args['next_registration']     = $next_reg
1535
-                ? $this->_next_link(
1536
-                    EE_Admin_Page::add_query_args_and_nonce(
1537
-                        array(
1538
-                            'action'  => 'view_registration',
1539
-                            '_REG_ID' => $next_reg['REG_ID'],
1540
-                        ),
1541
-                        REG_ADMIN_URL
1542
-                    ),
1543
-                    'dashicons dashicons-arrow-right ee-icon-size-22'
1544
-                )
1545
-                : '';
1546
-            $previous_reg                                  = $this->_registration->previous(
1547
-                null,
1548
-                array(),
1549
-                'REG_ID'
1550
-            );
1551
-            $this->_template_args['previous_registration'] = $previous_reg
1552
-                ? $this->_previous_link(
1553
-                    EE_Admin_Page::add_query_args_and_nonce(
1554
-                        array(
1555
-                            'action'  => 'view_registration',
1556
-                            '_REG_ID' => $previous_reg['REG_ID'],
1557
-                        ),
1558
-                        REG_ADMIN_URL
1559
-                    ),
1560
-                    'dashicons dashicons-arrow-left ee-icon-size-22'
1561
-                )
1562
-                : '';
1563
-            // grab header
1564
-            $template_path                             = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1565
-            $this->_template_args['REG_ID']            = $this->_registration->ID();
1566
-            $this->_template_args['admin_page_header'] = EEH_Template::display_template(
1567
-                $template_path,
1568
-                $this->_template_args,
1569
-                true
1570
-            );
1571
-        } else {
1572
-            $this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1573
-        }
1574
-        // the details template wrapper
1575
-        $this->display_admin_page_with_sidebar();
1576
-    }
1577
-
1578
-
1579
-    protected function _registration_details_metaboxes()
1580
-    {
1581
-        do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1582
-        $this->_set_registration_object();
1583
-        $attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1584
-        add_meta_box('edit-reg-status-mbox', esc_html__('Registration Status', 'event_espresso'),
1585
-            array($this, 'set_reg_status_buttons_metabox'), $this->wp_page_slug, 'normal', 'high');
1586
-        add_meta_box('edit-reg-details-mbox', esc_html__('Registration Details', 'event_espresso'),
1587
-            array($this, '_reg_details_meta_box'), $this->wp_page_slug, 'normal', 'high');
1588
-        if ($attendee instanceof EE_Attendee
1589
-            && EE_Registry::instance()->CAP->current_user_can(
1590
-                'ee_edit_registration',
1591
-                'edit-reg-questions-mbox',
1592
-                $this->_registration->ID()
1593
-            )
1594
-        ) {
1595
-            add_meta_box(
1596
-                'edit-reg-questions-mbox',
1597
-                esc_html__('Registration Form Answers', 'event_espresso'),
1598
-                array($this, '_reg_questions_meta_box'),
1599
-                $this->wp_page_slug,
1600
-                'normal',
1601
-                'high'
1602
-            );
1603
-        }
1604
-        add_meta_box(
1605
-            'edit-reg-registrant-mbox',
1606
-            esc_html__('Contact Details', 'event_espresso'),
1607
-            array($this, '_reg_registrant_side_meta_box'),
1608
-            $this->wp_page_slug,
1609
-            'side',
1610
-            'high'
1611
-        );
1612
-        if ($this->_registration->group_size() > 1) {
1613
-            add_meta_box(
1614
-                'edit-reg-attendees-mbox',
1615
-                esc_html__('Other Registrations in this Transaction', 'event_espresso'),
1616
-                array($this, '_reg_attendees_meta_box'),
1617
-                $this->wp_page_slug,
1618
-                'normal',
1619
-                'high'
1620
-            );
1621
-        }
1622
-    }
1623
-
1624
-
1625
-    /**
1626
-     * set_reg_status_buttons_metabox
1627
-     *
1628
-     * @access protected
1629
-     * @return string
1630
-     * @throws \EE_Error
1631
-     */
1632
-    public function set_reg_status_buttons_metabox()
1633
-    {
1634
-        $this->_set_registration_object();
1635
-        $change_reg_status_form = $this->_generate_reg_status_change_form();
1636
-        echo $change_reg_status_form->form_open(
1637
-            self::add_query_args_and_nonce(
1638
-                array(
1639
-                    'action' => 'change_reg_status',
1640
-                ),
1641
-                REG_ADMIN_URL
1642
-            )
1643
-        );
1644
-        echo $change_reg_status_form->get_html();
1645
-        echo $change_reg_status_form->form_close();
1646
-    }
1647
-
1648
-
1649
-
1650
-    /**
1651
-     * @return EE_Form_Section_Proper
1652
-     * @throws EE_Error
1653
-     */
1654
-    protected function _generate_reg_status_change_form()
1655
-    {
1656
-        return new EE_Form_Section_Proper(array(
1657
-            'name'            => 'reg_status_change_form',
1658
-            'html_id'         => 'reg-status-change-form',
1659
-            'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1660
-            'subsections'     => array(
1661
-                'return'             => new EE_Hidden_Input(array(
1662
-                    'name'    => 'return',
1663
-                    'default' => 'view_registration',
1664
-                )),
1665
-                'REG_ID'             => new EE_Hidden_Input(array(
1666
-                    'name'    => 'REG_ID',
1667
-                    'default' => $this->_registration->ID(),
1668
-                )),
1669
-                'current_status'     => new EE_Form_Section_HTML(
1670
-                    EEH_HTML::tr(
1671
-                        EEH_HTML::th(
1672
-                            EEH_HTML::label(
1673
-                                EEH_HTML::strong(esc_html__('Current Registration Status', 'event_espresso')
1674
-                                )
1675
-                            )
1676
-                        )
1677
-                        . EEH_HTML::td(
1678
-                            EEH_HTML::strong(
1679
-                                $this->_registration->pretty_status(),
1680
-                                '',
1681
-                                'status-' . $this->_registration->status_ID(),
1682
-                                'line-height: 1em; font-size: 1.5em; font-weight: bold;'
1683
-                            )
1684
-                        )
1685
-                    )
1686
-                ),
1687
-                'reg_status'         => new EE_Select_Input(
1688
-                    $this->_get_reg_statuses(),
1689
-                    array(
1690
-                        'html_label_text' => esc_html__('Change Registration Status to', 'event_espresso'),
1691
-                        'default'         => $this->_registration->status_ID(),
1692
-                    )
1693
-                ),
1694
-                'send_notifications' => new EE_Yes_No_Input(
1695
-                    array(
1696
-                        'html_label_text' => esc_html__('Send Related Messages', 'event_espresso'),
1697
-                        'default'         => false,
1698
-                        'html_help_text'  => esc_html__(
1699
-                            'If set to "Yes", then the related messages will be sent to the registrant.',
1700
-                            'event_espresso'
1701
-                        ),
1702
-                    )
1703
-                ),
1704
-                'submit'             => new EE_Submit_Input(
1705
-                    array(
1706
-                        'html_class'      => 'button-primary',
1707
-                        'html_label_text' => '&nbsp;',
1708
-                        'default'         => esc_html__('Update Registration Status', 'event_espresso'),
1709
-                    )
1710
-                ),
1711
-            ),
1712
-        ));
1713
-    }
1714
-
1715
-
1716
-    /**
1717
-     * Returns an array of all the buttons for the various statuses and switch status actions
1718
-     *
1719
-     * @return array
1720
-     * @throws EE_Error
1721
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1722
-     */
1723
-    protected function _get_reg_statuses()
1724
-    {
1725
-        $reg_status_array = EEM_Registration::instance()->reg_status_array();
1726
-        unset ($reg_status_array[EEM_Registration::status_id_incomplete]);
1727
-        // get current reg status
1728
-        $current_status = $this->_registration->status_ID();
1729
-        // is registration for free event? This will determine whether to display the pending payment option
1730
-        if (
1731
-            $current_status !== EEM_Registration::status_id_pending_payment
1732
-            && $this->_registration->transaction()->is_free()
1733
-        ) {
1734
-            unset($reg_status_array[EEM_Registration::status_id_pending_payment]);
1735
-        }
1736
-        return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1737
-    }
1738
-
1739
-
1740
-
1741
-    /**
1742
-     * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1743
-     *
1744
-     * @param bool $status REG status given for changing registrations to.
1745
-     * @param bool $notify Whether to send messages notifications or not.
1746
-     * @return array  (array with reg_id(s) updated and whether update was successful.
1747
-     * @throws \EE_Error
1748
-     */
1749
-    protected function _set_registration_status_from_request($status = false, $notify = false)
1750
-    {
1751
-        if (isset($this->_req_data['reg_status_change_form'])) {
1752
-            $REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1753
-                ? (array)$this->_req_data['reg_status_change_form']['REG_ID'] : array();
1754
-        } else {
1755
-            $REG_IDs = isset($this->_req_data['_REG_ID']) ? (array)$this->_req_data['_REG_ID'] : array();
1756
-        }
1757
-        $success = $this->_set_registration_status($REG_IDs, $status);
1758
-        //notify?
1759
-        if ($success
1760
-            && $notify
1761
-            && EE_Registry::instance()->CAP->current_user_can(
1762
-                'ee_send_message',
1763
-                'espresso_registrations_resend_registration'
1764
-            )
1765
-        ) {
1766
-            $this->_process_resend_registration();
1767
-        }
1768
-        return $success;
1769
-    }
1770
-
1771
-
1772
-
1773
-    /**
1774
-     * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1775
-     * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1776
-     *
1777
-     * @param array $REG_IDs
1778
-     * @param bool  $status
1779
-     * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1780
-     * @throws \RuntimeException
1781
-     * @throws \EE_Error
1782
-     *               the array of updated registrations).
1783
-     * @throws EE_Error
1784
-     * @throws RuntimeException
1785
-     */
1786
-    protected function _set_registration_status($REG_IDs = array(), $status = false)
1787
-    {
1788
-        $success = false;
1789
-        // typecast $REG_IDs
1790
-        $REG_IDs = (array)$REG_IDs;
1791
-        if ( ! empty($REG_IDs)) {
1792
-            $success = true;
1793
-            // set default status if none is passed
1794
-            $status = $status ? $status : EEM_Registration::status_id_pending_payment;
1795
-            // sanitize $REG_IDs
1796
-            $REG_IDs = array_filter($REG_IDs, 'absint');
1797
-            //loop through REG_ID's and change status
1798
-            foreach ($REG_IDs as $REG_ID) {
1799
-                $registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1800
-                if ($registration instanceof EE_Registration) {
1801
-                    $registration->set_status($status);
1802
-                    $result = $registration->save();
1803
-                    // verifying explicit fails because update *may* just return 0 for 0 rows affected
1804
-                    $success = $result !== false ? $success : false;
1805
-                }
1806
-            }
1807
-        }
1808
-        //reset _req_data['_REG_ID'] for any potential future messages notifications
1809
-        $this->_req_data['_REG_ID'] = $REG_IDs;
1810
-        //return $success and processed registrations
1811
-        return array('REG_ID' => $REG_IDs, 'success' => $success);
1812
-    }
1813
-
1814
-
1815
-    /**
1816
-     * Common logic for setting up success message and redirecting to appropriate route
1817
-     *
1818
-     * @param  string $STS_ID status id for the registration changed to
1819
-     * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1820
-     * @return void
1821
-     */
1822
-    protected function _reg_status_change_return($STS_ID, $notify = false)
1823
-    {
1824
-        $result  = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1825
-            : array('success' => false);
1826
-        $success = isset($result['success']) && $result['success'];
1827
-        //setup success message
1828
-        if ($success) {
1829
-            if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1830
-                $msg = sprintf(esc_html__('Registration status has been set to %s', 'event_espresso'),
1831
-                    EEH_Template::pretty_status($STS_ID, false, 'lower'));
1832
-            } else {
1833
-                $msg = sprintf(esc_html__('Registrations have been set to %s.', 'event_espresso'),
1834
-                    EEH_Template::pretty_status($STS_ID, false, 'lower'));
1835
-            }
1836
-            EE_Error::add_success($msg);
1837
-        } else {
1838
-            EE_Error::add_error(
1839
-                esc_html__(
1840
-                    'Something went wrong, and the status was not changed',
1841
-                    'event_espresso'
1842
-                ), __FILE__, __LINE__, __FUNCTION__
1843
-            );
1844
-        }
1845
-        if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
1846
-            $route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
1847
-        } else {
1848
-            $route = array('action' => 'default');
1849
-        }
1850
-        //unset nonces
1851
-        foreach ($this->_req_data as $ref => $value) {
1852
-            if (strpos($ref, 'nonce') !== false) {
1853
-                unset($this->_req_data[$ref]);
1854
-                continue;
1855
-            }
1856
-            $value                 = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
1857
-            $this->_req_data[$ref] = $value;
1858
-        }
1859
-        //merge request vars so that the reloaded list table contains any existing filter query params
1860
-        $route = array_merge($this->_req_data, $route);
1861
-        $this->_redirect_after_action($success, '', '', $route, true);
1862
-    }
1863
-
1864
-
1865
-    /**
1866
-     * incoming reg status change from reg details page.
1867
-     *
1868
-     * @return void
1869
-     */
1870
-    protected function _change_reg_status()
1871
-    {
1872
-        $this->_req_data['return'] = 'view_registration';
1873
-        //set notify based on whether the send notifications toggle is set or not
1874
-        $notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
1875
-        //$notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
1876
-        $this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
1877
-            ? $this->_req_data['reg_status_change_form']['reg_status'] : '';
1878
-        switch ($this->_req_data['reg_status_change_form']['reg_status']) {
1879
-            case EEM_Registration::status_id_approved :
1880
-            case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence') :
1881
-                $this->approve_registration($notify);
1882
-                break;
1883
-            case EEM_Registration::status_id_pending_payment :
1884
-            case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence') :
1885
-                $this->pending_registration($notify);
1886
-                break;
1887
-            case EEM_Registration::status_id_not_approved :
1888
-            case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence') :
1889
-                $this->not_approve_registration($notify);
1890
-                break;
1891
-            case EEM_Registration::status_id_declined :
1892
-            case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence') :
1893
-                $this->decline_registration($notify);
1894
-                break;
1895
-            case EEM_Registration::status_id_cancelled :
1896
-            case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence') :
1897
-                $this->cancel_registration($notify);
1898
-                break;
1899
-            case EEM_Registration::status_id_wait_list :
1900
-            case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence') :
1901
-                $this->wait_list_registration($notify);
1902
-                break;
1903
-            case EEM_Registration::status_id_incomplete :
1904
-            default :
1905
-                $result['success'] = false;
1906
-                unset($this->_req_data['return']);
1907
-                $this->_reg_status_change_return('', false);
1908
-                break;
1909
-        }
1910
-    }
1911
-
1912
-
1913
-    /**
1914
-     * Callback for bulk action routes.
1915
-     * Note: although we could just register the singular route callbacks for each bulk action route as well, this
1916
-     * method was chosen so there is one central place all the registration status bulk actions are going through.
1917
-     * Potentially, this provides an easier place to locate logic that is specific to these bulk actions (as opposed to
1918
-     * when an action is happening on just a single registration).
1919
-     * @param      $action
1920
-     * @param bool $notify
1921
-     */
1922
-    protected function bulk_action_on_registrations($action, $notify = false) {
1923
-        do_action(
1924
-            'AHEE__Registrations_Admin_Page__bulk_action_on_registrations__before_execution',
1925
-            $this,
1926
-            $action,
1927
-            $notify
1928
-        );
1929
-        $method = $action . '_registration';
1930
-        if (method_exists($this, $method)) {
1931
-            $this->$method($notify);
1932
-        }
1933
-    }
1934
-
1935
-
1936
-    /**
1937
-     * approve_registration
1938
-     *
1939
-     * @access protected
1940
-     * @param bool $notify whether or not to notify the registrant about their approval.
1941
-     * @return void
1942
-     */
1943
-    protected function approve_registration($notify = false)
1944
-    {
1945
-        $this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
1946
-    }
1947
-
1948
-
1949
-    /**
1950
-     *        decline_registration
1951
-     *
1952
-     * @access protected
1953
-     * @param bool $notify whether or not to notify the registrant about their status change.
1954
-     * @return void
1955
-     */
1956
-    protected function decline_registration($notify = false)
1957
-    {
1958
-        $this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
1959
-    }
1960
-
1961
-
1962
-    /**
1963
-     *        cancel_registration
1964
-     *
1965
-     * @access protected
1966
-     * @param bool $notify whether or not to notify the registrant about their status change.
1967
-     * @return void
1968
-     */
1969
-    protected function cancel_registration($notify = false)
1970
-    {
1971
-        $this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
1972
-    }
1973
-
1974
-
1975
-    /**
1976
-     *        not_approve_registration
1977
-     *
1978
-     * @access protected
1979
-     * @param bool $notify whether or not to notify the registrant about their status change.
1980
-     * @return void
1981
-     */
1982
-    protected function not_approve_registration($notify = false)
1983
-    {
1984
-        $this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
1985
-    }
1986
-
1987
-
1988
-    /**
1989
-     *        decline_registration
1990
-     *
1991
-     * @access protected
1992
-     * @param bool $notify whether or not to notify the registrant about their status change.
1993
-     * @return void
1994
-     */
1995
-    protected function pending_registration($notify = false)
1996
-    {
1997
-        $this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
1998
-    }
1999
-
2000
-
2001
-    /**
2002
-     * waitlist_registration
2003
-     *
2004
-     * @access protected
2005
-     * @param bool $notify whether or not to notify the registrant about their status change.
2006
-     * @return void
2007
-     */
2008
-    protected function wait_list_registration($notify = false)
2009
-    {
2010
-        $this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
2011
-    }
2012
-
2013
-
2014
-    /**
2015
-     *        generates HTML for the Registration main meta box
2016
-     *
2017
-     * @access public
2018
-     * @return void
2019
-     * @throws DomainException
2020
-     * @throws EE_Error
2021
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
2022
-     */
2023
-    public function _reg_details_meta_box()
2024
-    {
2025
-        EEH_Autoloader::register_line_item_display_autoloaders();
2026
-        EEH_Autoloader::register_line_item_filter_autoloaders();
2027
-        EE_Registry::instance()->load_helper('Line_Item');
2028
-        $transaction    = $this->_registration->transaction() ? $this->_registration->transaction()
2029
-            : EE_Transaction::new_instance();
2030
-        $this->_session = $transaction->session_data();
2031
-        $filters        = new EE_Line_Item_Filter_Collection();
2032
-        //$filters->add( new EE_Non_Zero_Line_Item_Filter() );
2033
-        $filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
2034
-        $line_item_filter_processor              = new EE_Line_Item_Filter_Processor($filters,
2035
-            $transaction->total_line_item());
2036
-        $filtered_line_item_tree                 = $line_item_filter_processor->process();
2037
-        $line_item_display                       = new EE_Line_Item_Display('reg_admin_table',
2038
-            'EE_Admin_Table_Registration_Line_Item_Display_Strategy');
2039
-        $this->_template_args['line_item_table'] = $line_item_display->display_line_item(
2040
-            $filtered_line_item_tree,
2041
-            array('EE_Registration' => $this->_registration)
2042
-        );
2043
-        $attendee                                = $this->_registration->attendee();
2044
-        if (EE_Registry::instance()->CAP->current_user_can(
2045
-            'ee_read_transaction',
2046
-            'espresso_transactions_view_transaction'
2047
-        )) {
2048
-            $this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(
2049
-                EE_Admin_Page::add_query_args_and_nonce(
2050
-                    array(
2051
-                        'action' => 'view_transaction',
2052
-                        'TXN_ID' => $transaction->ID(),
2053
-                    ),
2054
-                    TXN_ADMIN_URL
2055
-                ),
2056
-                esc_html__(' View Transaction', 'event_espresso'),
2057
-                'button secondary-button right',
2058
-                'dashicons dashicons-cart'
2059
-            );
2060
-        } else {
2061
-            $this->_template_args['view_transaction_button'] = '';
2062
-        }
2063
-        if ($attendee instanceof EE_Attendee
2064
-            && EE_Registry::instance()->CAP->current_user_can(
2065
-                'ee_send_message',
2066
-                'espresso_registrations_resend_registration'
2067
-            )
2068
-        ) {
2069
-            $this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(
2070
-                EE_Admin_Page::add_query_args_and_nonce(
2071
-                    array(
2072
-                        'action'      => 'resend_registration',
2073
-                        '_REG_ID'     => $this->_registration->ID(),
2074
-                        'redirect_to' => 'view_registration',
2075
-                    ),
2076
-                    REG_ADMIN_URL
2077
-                ),
2078
-                esc_html__(' Resend Registration', 'event_espresso'),
2079
-                'button secondary-button right',
2080
-                'dashicons dashicons-email-alt'
2081
-            );
2082
-        } else {
2083
-            $this->_template_args['resend_registration_button'] = '';
2084
-        }
2085
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2086
-        $payment                               = $transaction->get_first_related('Payment');
2087
-        $payment                               = ! $payment instanceof EE_Payment
2088
-            ? EE_Payment::new_instance()
2089
-            : $payment;
2090
-        $payment_method                        = $payment->get_first_related('Payment_Method');
2091
-        $payment_method                        = ! $payment_method instanceof EE_Payment_Method
2092
-            ? EE_Payment_Method::new_instance()
2093
-            : $payment_method;
2094
-        $reg_details                           = array(
2095
-            'payment_method'       => $payment_method->name(),
2096
-            'response_msg'         => $payment->gateway_response(),
2097
-            'registration_id'      => $this->_registration->get('REG_code'),
2098
-            'registration_session' => $this->_registration->session_ID(),
2099
-            'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
2100
-            'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
2101
-        );
2102
-        if (isset($reg_details['registration_id'])) {
2103
-            $this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
2104
-            $this->_template_args['reg_details']['registration_id']['label'] = esc_html__(
2105
-                'Registration ID',
2106
-                'event_espresso'
2107
-            );
2108
-            $this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
2109
-        }
2110
-        if (isset($reg_details['payment_method'])) {
2111
-            $this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
2112
-            $this->_template_args['reg_details']['payment_method']['label'] = esc_html__(
2113
-                'Most Recent Payment Method',
2114
-                'event_espresso'
2115
-            );
2116
-            $this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
2117
-            $this->_template_args['reg_details']['response_msg']['value']   = $reg_details['response_msg'];
2118
-            $this->_template_args['reg_details']['response_msg']['label']   = esc_html__(
2119
-                'Payment method response',
2120
-                'event_espresso'
2121
-            );
2122
-            $this->_template_args['reg_details']['response_msg']['class']   = 'regular-text';
2123
-        }
2124
-        $this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
2125
-        $this->_template_args['reg_details']['registration_session']['label'] = esc_html__(
2126
-            'Registration Session',
2127
-            'event_espresso'
2128
-        );
2129
-        $this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
2130
-        $this->_template_args['reg_details']['ip_address']['value']           = $reg_details['ip_address'];
2131
-        $this->_template_args['reg_details']['ip_address']['label']           = esc_html__(
2132
-            'Registration placed from IP',
2133
-            'event_espresso'
2134
-        );
2135
-        $this->_template_args['reg_details']['ip_address']['class']           = 'regular-text';
2136
-        $this->_template_args['reg_details']['user_agent']['value']           = $reg_details['user_agent'];
2137
-        $this->_template_args['reg_details']['user_agent']['label']           = esc_html__('Registrant User Agent',
2138
-            'event_espresso');
2139
-        $this->_template_args['reg_details']['user_agent']['class']           = 'large-text';
2140
-        $this->_template_args['event_link']                                   = EE_Admin_Page::add_query_args_and_nonce(
2141
-            array(
2142
-                'action'   => 'default',
2143
-                'event_id' => $this->_registration->event_ID(),
2144
-            ),
2145
-            REG_ADMIN_URL
2146
-        );
2147
-        $this->_template_args['REG_ID']                                       = $this->_registration->ID();
2148
-        $this->_template_args['event_id']                                     = $this->_registration->event_ID();
2149
-        $template_path                                                        =
2150
-            REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
2151
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2152
-    }
2153
-
2154
-
2155
-    /**
2156
-     * generates HTML for the Registration Questions meta box.
2157
-     * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
2158
-     * otherwise uses new forms system
2159
-     *
2160
-     * @access public
2161
-     * @return void
2162
-     * @throws DomainException
2163
-     * @throws EE_Error
2164
-     */
2165
-    public function _reg_questions_meta_box()
2166
-    {
2167
-        //allow someone to override this method entirely
2168
-        if (apply_filters('FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default', true, $this,
2169
-            $this->_registration)) {
2170
-            $form                                              = $this->_get_reg_custom_questions_form(
2171
-                $this->_registration->ID()
2172
-            );
2173
-            $this->_template_args['att_questions']             = count($form->subforms()) > 0
2174
-                ? $form->get_html_and_js()
2175
-                : '';
2176
-            $this->_template_args['reg_questions_form_action'] = 'edit_registration';
2177
-            $this->_template_args['REG_ID']                    = $this->_registration->ID();
2178
-            $template_path                                     =
2179
-                REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
2180
-            echo EEH_Template::display_template($template_path, $this->_template_args, true);
2181
-        }
2182
-    }
2183
-
2184
-
2185
-    /**
2186
-     * form_before_question_group
2187
-     *
2188
-     * @deprecated    as of 4.8.32.rc.000
2189
-     * @access        public
2190
-     * @param        string $output
2191
-     * @return        string
2192
-     */
2193
-    public function form_before_question_group($output)
2194
-    {
2195
-        EE_Error::doing_it_wrong(
2196
-            __CLASS__ . '::' . __FUNCTION__,
2197
-            esc_html__(
2198
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2199
-                'event_espresso'
2200
-            ),
2201
-            '4.8.32.rc.000'
2202
-        );
2203
-        return '
1236
+		if (! empty($registration_status)) {
1237
+			$where['STS_ID'] = $registration_status;
1238
+		} else {
1239
+			//make sure we exclude incomplete registrations, but only if not trashed.
1240
+			if ($view === 'trash') {
1241
+				$where['REG_deleted'] = true;
1242
+			} elseif ($view === 'incomplete') {
1243
+				$where['STS_ID'] = EEM_Registration::status_id_incomplete;
1244
+			} else {
1245
+				$where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1246
+			}
1247
+		}
1248
+		return $where;
1249
+	}
1250
+
1251
+
1252
+	/**
1253
+	 * Adds any provided date restraints to the where conditions for the registrations query.
1254
+	 *
1255
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1256
+	 * @return array
1257
+	 * @throws EE_Error
1258
+	 */
1259
+	protected function _add_date_to_where_conditions(array $request)
1260
+	{
1261
+		$where = array();
1262
+		$view = EEH_Array::is_set($request, 'status', '');
1263
+		$month_range             = ! empty($request['month_range'])
1264
+			? sanitize_text_field($request['month_range'])
1265
+			: '';
1266
+		$retrieve_for_today      = $view === 'today';
1267
+		$retrieve_for_this_month = $view === 'month';
1268
+
1269
+		if ($retrieve_for_today) {
1270
+			$now               = date('Y-m-d', current_time('timestamp'));
1271
+			$where['REG_date'] = array(
1272
+				'BETWEEN',
1273
+				array(
1274
+					EEM_Registration::instance()->convert_datetime_for_query(
1275
+						'REG_date',
1276
+						$now . ' 00:00:00',
1277
+						'Y-m-d H:i:s'
1278
+					),
1279
+					EEM_Registration::instance()->convert_datetime_for_query(
1280
+						'REG_date',
1281
+						$now . ' 23:59:59',
1282
+						'Y-m-d H:i:s'
1283
+					),
1284
+				),
1285
+			);
1286
+		} elseif ($retrieve_for_this_month) {
1287
+			$current_year_and_month = date('Y-m', current_time('timestamp'));
1288
+			$days_this_month        = date('t', current_time('timestamp'));
1289
+			$where['REG_date']      = array(
1290
+				'BETWEEN',
1291
+				array(
1292
+					EEM_Registration::instance()->convert_datetime_for_query(
1293
+						'REG_date',
1294
+						$current_year_and_month . '-01 00:00:00',
1295
+						'Y-m-d H:i:s'
1296
+					),
1297
+					EEM_Registration::instance()->convert_datetime_for_query(
1298
+						'REG_date',
1299
+						$current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1300
+						'Y-m-d H:i:s'
1301
+					),
1302
+				),
1303
+			);
1304
+		} elseif ($month_range) {
1305
+			$pieces          = explode(' ', $month_range, 3);
1306
+			$month_requested = ! empty($pieces[0])
1307
+				? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0]))
1308
+				: '';
1309
+			$year_requested  = ! empty($pieces[1])
1310
+				? $pieces[1]
1311
+				: '';
1312
+			//if there is not a month or year then we can't go further
1313
+			if ($month_requested && $year_requested) {
1314
+				$days_in_month     = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1315
+				$where['REG_date'] = array(
1316
+					'BETWEEN',
1317
+					array(
1318
+						EEM_Registration::instance()->convert_datetime_for_query(
1319
+							'REG_date',
1320
+							$year_requested . '-' . $month_requested . '-01 00:00:00',
1321
+							'Y-m-d H:i:s'
1322
+						),
1323
+						EEM_Registration::instance()->convert_datetime_for_query(
1324
+							'REG_date',
1325
+							$year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1326
+							'Y-m-d H:i:s'
1327
+						),
1328
+					),
1329
+				);
1330
+			}
1331
+		}
1332
+		return $where;
1333
+	}
1334
+
1335
+
1336
+	/**
1337
+	 * Adds any provided search restraints to the where conditions for the registrations query
1338
+	 *
1339
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1340
+	 * @return array
1341
+	 */
1342
+	protected function _add_search_to_where_conditions(array $request)
1343
+	{
1344
+		$where = array();
1345
+		if (! empty($request['s'])) {
1346
+			$search_string = '%' . sanitize_text_field($request['s']) . '%';
1347
+			$where['OR*search_conditions'] = array(
1348
+				'Event.EVT_name'                          => array('LIKE', $search_string),
1349
+				'Event.EVT_desc'                          => array('LIKE', $search_string),
1350
+				'Event.EVT_short_desc'                    => array('LIKE', $search_string),
1351
+				'Attendee.ATT_full_name'                  => array('LIKE', $search_string),
1352
+				'Attendee.ATT_fname'                      => array('LIKE', $search_string),
1353
+				'Attendee.ATT_lname'                      => array('LIKE', $search_string),
1354
+				'Attendee.ATT_short_bio'                  => array('LIKE', $search_string),
1355
+				'Attendee.ATT_email'                      => array('LIKE', $search_string),
1356
+				'Attendee.ATT_address'                    => array('LIKE', $search_string),
1357
+				'Attendee.ATT_address2'                   => array('LIKE', $search_string),
1358
+				'Attendee.ATT_city'                       => array('LIKE', $search_string),
1359
+				'REG_final_price'                         => array('LIKE', $search_string),
1360
+				'REG_code'                                => array('LIKE', $search_string),
1361
+				'REG_count'                               => array('LIKE', $search_string),
1362
+				'REG_group_size'                          => array('LIKE', $search_string),
1363
+				'Ticket.TKT_name'                         => array('LIKE', $search_string),
1364
+				'Ticket.TKT_description'                  => array('LIKE', $search_string),
1365
+				'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $search_string),
1366
+			);
1367
+		}
1368
+		return $where;
1369
+	}
1370
+
1371
+
1372
+	/**
1373
+	 * Sets up the where conditions for the registrations query.
1374
+	 *
1375
+	 * @param array $request
1376
+	 * @return array
1377
+	 * @throws EE_Error
1378
+	 */
1379
+	protected function _get_where_conditions_for_registrations_query($request)
1380
+	{
1381
+		return apply_filters(
1382
+			'FHEE__Registrations_Admin_Page___get_where_conditions_for_registrations_query',
1383
+			array_merge(
1384
+				$this->_add_event_id_to_where_conditions($request),
1385
+				$this->_add_category_id_to_where_conditions($request),
1386
+				$this->_add_datetime_id_to_where_conditions($request),
1387
+				$this->_add_registration_status_to_where_conditions($request),
1388
+				$this->_add_date_to_where_conditions($request),
1389
+				$this->_add_search_to_where_conditions($request)
1390
+			),
1391
+			$request
1392
+		);
1393
+	}
1394
+
1395
+
1396
+	/**
1397
+	 * Sets up the orderby for the registrations query.
1398
+	 *
1399
+	 * @return array
1400
+	 */
1401
+	protected function _get_orderby_for_registrations_query()
1402
+	{
1403
+		$orderby_field = ! empty($this->_req_data['orderby'])
1404
+			? sanitize_text_field($this->_req_data['orderby'])
1405
+			: '';
1406
+		switch ($orderby_field) {
1407
+			case '_REG_ID':
1408
+				$orderby_field = 'REG_ID';
1409
+				break;
1410
+			case '_Reg_status':
1411
+				$orderby_field = 'STS_ID';
1412
+				break;
1413
+			case 'ATT_fname':
1414
+				$orderby_field = array('Attendee.ATT_fname', 'Attendee.ATT_lname');
1415
+				break;
1416
+			case 'ATT_lname':
1417
+				$orderby_field = array('Attendee.ATT_lname', 'Attendee.ATT_fname');
1418
+				break;
1419
+			case 'event_name':
1420
+				$orderby_field = 'Event.EVT_name';
1421
+				break;
1422
+			case 'DTT_EVT_start':
1423
+				$orderby_field = 'Event.Datetime.DTT_EVT_start';
1424
+				break;
1425
+			default: //'REG_date'
1426
+				$orderby_field = 'REG_date';
1427
+		}
1428
+
1429
+		//order
1430
+		$order = ! empty($this->_req_data['order'])
1431
+			? sanitize_text_field($this->_req_data['order'])
1432
+			: 'DESC';
1433
+
1434
+		//mutate orderby_field
1435
+		$orderby_field = array_combine(
1436
+			(array) $orderby_field,
1437
+			array_fill(0, count($orderby_field), $order)
1438
+		);
1439
+		return array('order_by' => $orderby_field);
1440
+	}
1441
+
1442
+
1443
+	/**
1444
+	 * Sets up the limit for the registrations query.
1445
+	 *
1446
+	 * @param $per_page
1447
+	 * @return array
1448
+	 */
1449
+	protected function _get_limit($per_page)
1450
+	{
1451
+		$current_page = ! empty($this->_req_data['paged'])
1452
+			? absint($this->_req_data['paged'])
1453
+			: 1;
1454
+		$per_page     = ! empty($this->_req_data['perpage'])
1455
+			? $this->_req_data['perpage']
1456
+			: $per_page;
1457
+
1458
+		//-1 means return all results so get out if that's set.
1459
+		if ((int)$per_page === -1) {
1460
+			return array();
1461
+		}
1462
+		$per_page = absint($per_page);
1463
+		$offset   = ($current_page - 1) * $per_page;
1464
+		return array('limit' => array($offset, $per_page));
1465
+	}
1466
+
1467
+
1468
+	public function get_registration_status_array()
1469
+	{
1470
+		return self::$_reg_status;
1471
+	}
1472
+
1473
+
1474
+
1475
+
1476
+	/***************************************        REGISTRATION DETAILS        ***************************************/
1477
+	/**
1478
+	 *        generates HTML for the View Registration Details Admin page
1479
+	 *
1480
+	 * @access protected
1481
+	 * @return void
1482
+	 * @throws DomainException
1483
+	 * @throws EE_Error
1484
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1485
+	 */
1486
+	protected function _registration_details()
1487
+	{
1488
+		$this->_template_args = array();
1489
+		$this->_set_registration_object();
1490
+		if (is_object($this->_registration)) {
1491
+			$transaction                                   = $this->_registration->transaction()
1492
+				? $this->_registration->transaction()
1493
+				: EE_Transaction::new_instance();
1494
+			$this->_session                                = $transaction->session_data();
1495
+			$event_id                                      = $this->_registration->event_ID();
1496
+			$this->_template_args['reg_nmbr']['value']     = $this->_registration->ID();
1497
+			$this->_template_args['reg_nmbr']['label']     = esc_html__('Registration Number', 'event_espresso');
1498
+			$this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1499
+			$this->_template_args['reg_datetime']['label'] = esc_html__('Date', 'event_espresso');
1500
+			$this->_template_args['grand_total']           = $transaction->total();
1501
+			$this->_template_args['currency_sign']         = EE_Registry::instance()->CFG->currency->sign;
1502
+			// link back to overview
1503
+			$this->_template_args['reg_overview_url']            = REG_ADMIN_URL;
1504
+			$this->_template_args['registration']                = $this->_registration;
1505
+			$this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(
1506
+				array(
1507
+					'action'   => 'default',
1508
+					'event_id' => $event_id,
1509
+				),
1510
+				REG_ADMIN_URL
1511
+			);
1512
+			$this->_template_args['filtered_transactions_link']  = EE_Admin_Page::add_query_args_and_nonce(
1513
+				array(
1514
+					'action' => 'default',
1515
+					'EVT_ID' => $event_id,
1516
+					'page'   => 'espresso_transactions',
1517
+				),
1518
+				admin_url('admin.php')
1519
+			);
1520
+			$this->_template_args['event_link']                  = EE_Admin_Page::add_query_args_and_nonce(
1521
+				array(
1522
+					'page'   => 'espresso_events',
1523
+					'action' => 'edit',
1524
+					'post'   => $event_id,
1525
+				),
1526
+				admin_url('admin.php')
1527
+			);
1528
+			//next and previous links
1529
+			$next_reg                                      = $this->_registration->next(
1530
+				null,
1531
+				array(),
1532
+				'REG_ID'
1533
+			);
1534
+			$this->_template_args['next_registration']     = $next_reg
1535
+				? $this->_next_link(
1536
+					EE_Admin_Page::add_query_args_and_nonce(
1537
+						array(
1538
+							'action'  => 'view_registration',
1539
+							'_REG_ID' => $next_reg['REG_ID'],
1540
+						),
1541
+						REG_ADMIN_URL
1542
+					),
1543
+					'dashicons dashicons-arrow-right ee-icon-size-22'
1544
+				)
1545
+				: '';
1546
+			$previous_reg                                  = $this->_registration->previous(
1547
+				null,
1548
+				array(),
1549
+				'REG_ID'
1550
+			);
1551
+			$this->_template_args['previous_registration'] = $previous_reg
1552
+				? $this->_previous_link(
1553
+					EE_Admin_Page::add_query_args_and_nonce(
1554
+						array(
1555
+							'action'  => 'view_registration',
1556
+							'_REG_ID' => $previous_reg['REG_ID'],
1557
+						),
1558
+						REG_ADMIN_URL
1559
+					),
1560
+					'dashicons dashicons-arrow-left ee-icon-size-22'
1561
+				)
1562
+				: '';
1563
+			// grab header
1564
+			$template_path                             = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1565
+			$this->_template_args['REG_ID']            = $this->_registration->ID();
1566
+			$this->_template_args['admin_page_header'] = EEH_Template::display_template(
1567
+				$template_path,
1568
+				$this->_template_args,
1569
+				true
1570
+			);
1571
+		} else {
1572
+			$this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1573
+		}
1574
+		// the details template wrapper
1575
+		$this->display_admin_page_with_sidebar();
1576
+	}
1577
+
1578
+
1579
+	protected function _registration_details_metaboxes()
1580
+	{
1581
+		do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1582
+		$this->_set_registration_object();
1583
+		$attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1584
+		add_meta_box('edit-reg-status-mbox', esc_html__('Registration Status', 'event_espresso'),
1585
+			array($this, 'set_reg_status_buttons_metabox'), $this->wp_page_slug, 'normal', 'high');
1586
+		add_meta_box('edit-reg-details-mbox', esc_html__('Registration Details', 'event_espresso'),
1587
+			array($this, '_reg_details_meta_box'), $this->wp_page_slug, 'normal', 'high');
1588
+		if ($attendee instanceof EE_Attendee
1589
+			&& EE_Registry::instance()->CAP->current_user_can(
1590
+				'ee_edit_registration',
1591
+				'edit-reg-questions-mbox',
1592
+				$this->_registration->ID()
1593
+			)
1594
+		) {
1595
+			add_meta_box(
1596
+				'edit-reg-questions-mbox',
1597
+				esc_html__('Registration Form Answers', 'event_espresso'),
1598
+				array($this, '_reg_questions_meta_box'),
1599
+				$this->wp_page_slug,
1600
+				'normal',
1601
+				'high'
1602
+			);
1603
+		}
1604
+		add_meta_box(
1605
+			'edit-reg-registrant-mbox',
1606
+			esc_html__('Contact Details', 'event_espresso'),
1607
+			array($this, '_reg_registrant_side_meta_box'),
1608
+			$this->wp_page_slug,
1609
+			'side',
1610
+			'high'
1611
+		);
1612
+		if ($this->_registration->group_size() > 1) {
1613
+			add_meta_box(
1614
+				'edit-reg-attendees-mbox',
1615
+				esc_html__('Other Registrations in this Transaction', 'event_espresso'),
1616
+				array($this, '_reg_attendees_meta_box'),
1617
+				$this->wp_page_slug,
1618
+				'normal',
1619
+				'high'
1620
+			);
1621
+		}
1622
+	}
1623
+
1624
+
1625
+	/**
1626
+	 * set_reg_status_buttons_metabox
1627
+	 *
1628
+	 * @access protected
1629
+	 * @return string
1630
+	 * @throws \EE_Error
1631
+	 */
1632
+	public function set_reg_status_buttons_metabox()
1633
+	{
1634
+		$this->_set_registration_object();
1635
+		$change_reg_status_form = $this->_generate_reg_status_change_form();
1636
+		echo $change_reg_status_form->form_open(
1637
+			self::add_query_args_and_nonce(
1638
+				array(
1639
+					'action' => 'change_reg_status',
1640
+				),
1641
+				REG_ADMIN_URL
1642
+			)
1643
+		);
1644
+		echo $change_reg_status_form->get_html();
1645
+		echo $change_reg_status_form->form_close();
1646
+	}
1647
+
1648
+
1649
+
1650
+	/**
1651
+	 * @return EE_Form_Section_Proper
1652
+	 * @throws EE_Error
1653
+	 */
1654
+	protected function _generate_reg_status_change_form()
1655
+	{
1656
+		return new EE_Form_Section_Proper(array(
1657
+			'name'            => 'reg_status_change_form',
1658
+			'html_id'         => 'reg-status-change-form',
1659
+			'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1660
+			'subsections'     => array(
1661
+				'return'             => new EE_Hidden_Input(array(
1662
+					'name'    => 'return',
1663
+					'default' => 'view_registration',
1664
+				)),
1665
+				'REG_ID'             => new EE_Hidden_Input(array(
1666
+					'name'    => 'REG_ID',
1667
+					'default' => $this->_registration->ID(),
1668
+				)),
1669
+				'current_status'     => new EE_Form_Section_HTML(
1670
+					EEH_HTML::tr(
1671
+						EEH_HTML::th(
1672
+							EEH_HTML::label(
1673
+								EEH_HTML::strong(esc_html__('Current Registration Status', 'event_espresso')
1674
+								)
1675
+							)
1676
+						)
1677
+						. EEH_HTML::td(
1678
+							EEH_HTML::strong(
1679
+								$this->_registration->pretty_status(),
1680
+								'',
1681
+								'status-' . $this->_registration->status_ID(),
1682
+								'line-height: 1em; font-size: 1.5em; font-weight: bold;'
1683
+							)
1684
+						)
1685
+					)
1686
+				),
1687
+				'reg_status'         => new EE_Select_Input(
1688
+					$this->_get_reg_statuses(),
1689
+					array(
1690
+						'html_label_text' => esc_html__('Change Registration Status to', 'event_espresso'),
1691
+						'default'         => $this->_registration->status_ID(),
1692
+					)
1693
+				),
1694
+				'send_notifications' => new EE_Yes_No_Input(
1695
+					array(
1696
+						'html_label_text' => esc_html__('Send Related Messages', 'event_espresso'),
1697
+						'default'         => false,
1698
+						'html_help_text'  => esc_html__(
1699
+							'If set to "Yes", then the related messages will be sent to the registrant.',
1700
+							'event_espresso'
1701
+						),
1702
+					)
1703
+				),
1704
+				'submit'             => new EE_Submit_Input(
1705
+					array(
1706
+						'html_class'      => 'button-primary',
1707
+						'html_label_text' => '&nbsp;',
1708
+						'default'         => esc_html__('Update Registration Status', 'event_espresso'),
1709
+					)
1710
+				),
1711
+			),
1712
+		));
1713
+	}
1714
+
1715
+
1716
+	/**
1717
+	 * Returns an array of all the buttons for the various statuses and switch status actions
1718
+	 *
1719
+	 * @return array
1720
+	 * @throws EE_Error
1721
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1722
+	 */
1723
+	protected function _get_reg_statuses()
1724
+	{
1725
+		$reg_status_array = EEM_Registration::instance()->reg_status_array();
1726
+		unset ($reg_status_array[EEM_Registration::status_id_incomplete]);
1727
+		// get current reg status
1728
+		$current_status = $this->_registration->status_ID();
1729
+		// is registration for free event? This will determine whether to display the pending payment option
1730
+		if (
1731
+			$current_status !== EEM_Registration::status_id_pending_payment
1732
+			&& $this->_registration->transaction()->is_free()
1733
+		) {
1734
+			unset($reg_status_array[EEM_Registration::status_id_pending_payment]);
1735
+		}
1736
+		return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1737
+	}
1738
+
1739
+
1740
+
1741
+	/**
1742
+	 * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1743
+	 *
1744
+	 * @param bool $status REG status given for changing registrations to.
1745
+	 * @param bool $notify Whether to send messages notifications or not.
1746
+	 * @return array  (array with reg_id(s) updated and whether update was successful.
1747
+	 * @throws \EE_Error
1748
+	 */
1749
+	protected function _set_registration_status_from_request($status = false, $notify = false)
1750
+	{
1751
+		if (isset($this->_req_data['reg_status_change_form'])) {
1752
+			$REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1753
+				? (array)$this->_req_data['reg_status_change_form']['REG_ID'] : array();
1754
+		} else {
1755
+			$REG_IDs = isset($this->_req_data['_REG_ID']) ? (array)$this->_req_data['_REG_ID'] : array();
1756
+		}
1757
+		$success = $this->_set_registration_status($REG_IDs, $status);
1758
+		//notify?
1759
+		if ($success
1760
+			&& $notify
1761
+			&& EE_Registry::instance()->CAP->current_user_can(
1762
+				'ee_send_message',
1763
+				'espresso_registrations_resend_registration'
1764
+			)
1765
+		) {
1766
+			$this->_process_resend_registration();
1767
+		}
1768
+		return $success;
1769
+	}
1770
+
1771
+
1772
+
1773
+	/**
1774
+	 * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1775
+	 * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1776
+	 *
1777
+	 * @param array $REG_IDs
1778
+	 * @param bool  $status
1779
+	 * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1780
+	 * @throws \RuntimeException
1781
+	 * @throws \EE_Error
1782
+	 *               the array of updated registrations).
1783
+	 * @throws EE_Error
1784
+	 * @throws RuntimeException
1785
+	 */
1786
+	protected function _set_registration_status($REG_IDs = array(), $status = false)
1787
+	{
1788
+		$success = false;
1789
+		// typecast $REG_IDs
1790
+		$REG_IDs = (array)$REG_IDs;
1791
+		if ( ! empty($REG_IDs)) {
1792
+			$success = true;
1793
+			// set default status if none is passed
1794
+			$status = $status ? $status : EEM_Registration::status_id_pending_payment;
1795
+			// sanitize $REG_IDs
1796
+			$REG_IDs = array_filter($REG_IDs, 'absint');
1797
+			//loop through REG_ID's and change status
1798
+			foreach ($REG_IDs as $REG_ID) {
1799
+				$registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1800
+				if ($registration instanceof EE_Registration) {
1801
+					$registration->set_status($status);
1802
+					$result = $registration->save();
1803
+					// verifying explicit fails because update *may* just return 0 for 0 rows affected
1804
+					$success = $result !== false ? $success : false;
1805
+				}
1806
+			}
1807
+		}
1808
+		//reset _req_data['_REG_ID'] for any potential future messages notifications
1809
+		$this->_req_data['_REG_ID'] = $REG_IDs;
1810
+		//return $success and processed registrations
1811
+		return array('REG_ID' => $REG_IDs, 'success' => $success);
1812
+	}
1813
+
1814
+
1815
+	/**
1816
+	 * Common logic for setting up success message and redirecting to appropriate route
1817
+	 *
1818
+	 * @param  string $STS_ID status id for the registration changed to
1819
+	 * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1820
+	 * @return void
1821
+	 */
1822
+	protected function _reg_status_change_return($STS_ID, $notify = false)
1823
+	{
1824
+		$result  = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1825
+			: array('success' => false);
1826
+		$success = isset($result['success']) && $result['success'];
1827
+		//setup success message
1828
+		if ($success) {
1829
+			if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1830
+				$msg = sprintf(esc_html__('Registration status has been set to %s', 'event_espresso'),
1831
+					EEH_Template::pretty_status($STS_ID, false, 'lower'));
1832
+			} else {
1833
+				$msg = sprintf(esc_html__('Registrations have been set to %s.', 'event_espresso'),
1834
+					EEH_Template::pretty_status($STS_ID, false, 'lower'));
1835
+			}
1836
+			EE_Error::add_success($msg);
1837
+		} else {
1838
+			EE_Error::add_error(
1839
+				esc_html__(
1840
+					'Something went wrong, and the status was not changed',
1841
+					'event_espresso'
1842
+				), __FILE__, __LINE__, __FUNCTION__
1843
+			);
1844
+		}
1845
+		if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
1846
+			$route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
1847
+		} else {
1848
+			$route = array('action' => 'default');
1849
+		}
1850
+		//unset nonces
1851
+		foreach ($this->_req_data as $ref => $value) {
1852
+			if (strpos($ref, 'nonce') !== false) {
1853
+				unset($this->_req_data[$ref]);
1854
+				continue;
1855
+			}
1856
+			$value                 = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
1857
+			$this->_req_data[$ref] = $value;
1858
+		}
1859
+		//merge request vars so that the reloaded list table contains any existing filter query params
1860
+		$route = array_merge($this->_req_data, $route);
1861
+		$this->_redirect_after_action($success, '', '', $route, true);
1862
+	}
1863
+
1864
+
1865
+	/**
1866
+	 * incoming reg status change from reg details page.
1867
+	 *
1868
+	 * @return void
1869
+	 */
1870
+	protected function _change_reg_status()
1871
+	{
1872
+		$this->_req_data['return'] = 'view_registration';
1873
+		//set notify based on whether the send notifications toggle is set or not
1874
+		$notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
1875
+		//$notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
1876
+		$this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
1877
+			? $this->_req_data['reg_status_change_form']['reg_status'] : '';
1878
+		switch ($this->_req_data['reg_status_change_form']['reg_status']) {
1879
+			case EEM_Registration::status_id_approved :
1880
+			case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence') :
1881
+				$this->approve_registration($notify);
1882
+				break;
1883
+			case EEM_Registration::status_id_pending_payment :
1884
+			case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence') :
1885
+				$this->pending_registration($notify);
1886
+				break;
1887
+			case EEM_Registration::status_id_not_approved :
1888
+			case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence') :
1889
+				$this->not_approve_registration($notify);
1890
+				break;
1891
+			case EEM_Registration::status_id_declined :
1892
+			case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence') :
1893
+				$this->decline_registration($notify);
1894
+				break;
1895
+			case EEM_Registration::status_id_cancelled :
1896
+			case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence') :
1897
+				$this->cancel_registration($notify);
1898
+				break;
1899
+			case EEM_Registration::status_id_wait_list :
1900
+			case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence') :
1901
+				$this->wait_list_registration($notify);
1902
+				break;
1903
+			case EEM_Registration::status_id_incomplete :
1904
+			default :
1905
+				$result['success'] = false;
1906
+				unset($this->_req_data['return']);
1907
+				$this->_reg_status_change_return('', false);
1908
+				break;
1909
+		}
1910
+	}
1911
+
1912
+
1913
+	/**
1914
+	 * Callback for bulk action routes.
1915
+	 * Note: although we could just register the singular route callbacks for each bulk action route as well, this
1916
+	 * method was chosen so there is one central place all the registration status bulk actions are going through.
1917
+	 * Potentially, this provides an easier place to locate logic that is specific to these bulk actions (as opposed to
1918
+	 * when an action is happening on just a single registration).
1919
+	 * @param      $action
1920
+	 * @param bool $notify
1921
+	 */
1922
+	protected function bulk_action_on_registrations($action, $notify = false) {
1923
+		do_action(
1924
+			'AHEE__Registrations_Admin_Page__bulk_action_on_registrations__before_execution',
1925
+			$this,
1926
+			$action,
1927
+			$notify
1928
+		);
1929
+		$method = $action . '_registration';
1930
+		if (method_exists($this, $method)) {
1931
+			$this->$method($notify);
1932
+		}
1933
+	}
1934
+
1935
+
1936
+	/**
1937
+	 * approve_registration
1938
+	 *
1939
+	 * @access protected
1940
+	 * @param bool $notify whether or not to notify the registrant about their approval.
1941
+	 * @return void
1942
+	 */
1943
+	protected function approve_registration($notify = false)
1944
+	{
1945
+		$this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
1946
+	}
1947
+
1948
+
1949
+	/**
1950
+	 *        decline_registration
1951
+	 *
1952
+	 * @access protected
1953
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1954
+	 * @return void
1955
+	 */
1956
+	protected function decline_registration($notify = false)
1957
+	{
1958
+		$this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
1959
+	}
1960
+
1961
+
1962
+	/**
1963
+	 *        cancel_registration
1964
+	 *
1965
+	 * @access protected
1966
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1967
+	 * @return void
1968
+	 */
1969
+	protected function cancel_registration($notify = false)
1970
+	{
1971
+		$this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
1972
+	}
1973
+
1974
+
1975
+	/**
1976
+	 *        not_approve_registration
1977
+	 *
1978
+	 * @access protected
1979
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1980
+	 * @return void
1981
+	 */
1982
+	protected function not_approve_registration($notify = false)
1983
+	{
1984
+		$this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
1985
+	}
1986
+
1987
+
1988
+	/**
1989
+	 *        decline_registration
1990
+	 *
1991
+	 * @access protected
1992
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1993
+	 * @return void
1994
+	 */
1995
+	protected function pending_registration($notify = false)
1996
+	{
1997
+		$this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
1998
+	}
1999
+
2000
+
2001
+	/**
2002
+	 * waitlist_registration
2003
+	 *
2004
+	 * @access protected
2005
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2006
+	 * @return void
2007
+	 */
2008
+	protected function wait_list_registration($notify = false)
2009
+	{
2010
+		$this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
2011
+	}
2012
+
2013
+
2014
+	/**
2015
+	 *        generates HTML for the Registration main meta box
2016
+	 *
2017
+	 * @access public
2018
+	 * @return void
2019
+	 * @throws DomainException
2020
+	 * @throws EE_Error
2021
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
2022
+	 */
2023
+	public function _reg_details_meta_box()
2024
+	{
2025
+		EEH_Autoloader::register_line_item_display_autoloaders();
2026
+		EEH_Autoloader::register_line_item_filter_autoloaders();
2027
+		EE_Registry::instance()->load_helper('Line_Item');
2028
+		$transaction    = $this->_registration->transaction() ? $this->_registration->transaction()
2029
+			: EE_Transaction::new_instance();
2030
+		$this->_session = $transaction->session_data();
2031
+		$filters        = new EE_Line_Item_Filter_Collection();
2032
+		//$filters->add( new EE_Non_Zero_Line_Item_Filter() );
2033
+		$filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
2034
+		$line_item_filter_processor              = new EE_Line_Item_Filter_Processor($filters,
2035
+			$transaction->total_line_item());
2036
+		$filtered_line_item_tree                 = $line_item_filter_processor->process();
2037
+		$line_item_display                       = new EE_Line_Item_Display('reg_admin_table',
2038
+			'EE_Admin_Table_Registration_Line_Item_Display_Strategy');
2039
+		$this->_template_args['line_item_table'] = $line_item_display->display_line_item(
2040
+			$filtered_line_item_tree,
2041
+			array('EE_Registration' => $this->_registration)
2042
+		);
2043
+		$attendee                                = $this->_registration->attendee();
2044
+		if (EE_Registry::instance()->CAP->current_user_can(
2045
+			'ee_read_transaction',
2046
+			'espresso_transactions_view_transaction'
2047
+		)) {
2048
+			$this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(
2049
+				EE_Admin_Page::add_query_args_and_nonce(
2050
+					array(
2051
+						'action' => 'view_transaction',
2052
+						'TXN_ID' => $transaction->ID(),
2053
+					),
2054
+					TXN_ADMIN_URL
2055
+				),
2056
+				esc_html__(' View Transaction', 'event_espresso'),
2057
+				'button secondary-button right',
2058
+				'dashicons dashicons-cart'
2059
+			);
2060
+		} else {
2061
+			$this->_template_args['view_transaction_button'] = '';
2062
+		}
2063
+		if ($attendee instanceof EE_Attendee
2064
+			&& EE_Registry::instance()->CAP->current_user_can(
2065
+				'ee_send_message',
2066
+				'espresso_registrations_resend_registration'
2067
+			)
2068
+		) {
2069
+			$this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(
2070
+				EE_Admin_Page::add_query_args_and_nonce(
2071
+					array(
2072
+						'action'      => 'resend_registration',
2073
+						'_REG_ID'     => $this->_registration->ID(),
2074
+						'redirect_to' => 'view_registration',
2075
+					),
2076
+					REG_ADMIN_URL
2077
+				),
2078
+				esc_html__(' Resend Registration', 'event_espresso'),
2079
+				'button secondary-button right',
2080
+				'dashicons dashicons-email-alt'
2081
+			);
2082
+		} else {
2083
+			$this->_template_args['resend_registration_button'] = '';
2084
+		}
2085
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2086
+		$payment                               = $transaction->get_first_related('Payment');
2087
+		$payment                               = ! $payment instanceof EE_Payment
2088
+			? EE_Payment::new_instance()
2089
+			: $payment;
2090
+		$payment_method                        = $payment->get_first_related('Payment_Method');
2091
+		$payment_method                        = ! $payment_method instanceof EE_Payment_Method
2092
+			? EE_Payment_Method::new_instance()
2093
+			: $payment_method;
2094
+		$reg_details                           = array(
2095
+			'payment_method'       => $payment_method->name(),
2096
+			'response_msg'         => $payment->gateway_response(),
2097
+			'registration_id'      => $this->_registration->get('REG_code'),
2098
+			'registration_session' => $this->_registration->session_ID(),
2099
+			'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
2100
+			'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
2101
+		);
2102
+		if (isset($reg_details['registration_id'])) {
2103
+			$this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
2104
+			$this->_template_args['reg_details']['registration_id']['label'] = esc_html__(
2105
+				'Registration ID',
2106
+				'event_espresso'
2107
+			);
2108
+			$this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
2109
+		}
2110
+		if (isset($reg_details['payment_method'])) {
2111
+			$this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
2112
+			$this->_template_args['reg_details']['payment_method']['label'] = esc_html__(
2113
+				'Most Recent Payment Method',
2114
+				'event_espresso'
2115
+			);
2116
+			$this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
2117
+			$this->_template_args['reg_details']['response_msg']['value']   = $reg_details['response_msg'];
2118
+			$this->_template_args['reg_details']['response_msg']['label']   = esc_html__(
2119
+				'Payment method response',
2120
+				'event_espresso'
2121
+			);
2122
+			$this->_template_args['reg_details']['response_msg']['class']   = 'regular-text';
2123
+		}
2124
+		$this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
2125
+		$this->_template_args['reg_details']['registration_session']['label'] = esc_html__(
2126
+			'Registration Session',
2127
+			'event_espresso'
2128
+		);
2129
+		$this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
2130
+		$this->_template_args['reg_details']['ip_address']['value']           = $reg_details['ip_address'];
2131
+		$this->_template_args['reg_details']['ip_address']['label']           = esc_html__(
2132
+			'Registration placed from IP',
2133
+			'event_espresso'
2134
+		);
2135
+		$this->_template_args['reg_details']['ip_address']['class']           = 'regular-text';
2136
+		$this->_template_args['reg_details']['user_agent']['value']           = $reg_details['user_agent'];
2137
+		$this->_template_args['reg_details']['user_agent']['label']           = esc_html__('Registrant User Agent',
2138
+			'event_espresso');
2139
+		$this->_template_args['reg_details']['user_agent']['class']           = 'large-text';
2140
+		$this->_template_args['event_link']                                   = EE_Admin_Page::add_query_args_and_nonce(
2141
+			array(
2142
+				'action'   => 'default',
2143
+				'event_id' => $this->_registration->event_ID(),
2144
+			),
2145
+			REG_ADMIN_URL
2146
+		);
2147
+		$this->_template_args['REG_ID']                                       = $this->_registration->ID();
2148
+		$this->_template_args['event_id']                                     = $this->_registration->event_ID();
2149
+		$template_path                                                        =
2150
+			REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
2151
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2152
+	}
2153
+
2154
+
2155
+	/**
2156
+	 * generates HTML for the Registration Questions meta box.
2157
+	 * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
2158
+	 * otherwise uses new forms system
2159
+	 *
2160
+	 * @access public
2161
+	 * @return void
2162
+	 * @throws DomainException
2163
+	 * @throws EE_Error
2164
+	 */
2165
+	public function _reg_questions_meta_box()
2166
+	{
2167
+		//allow someone to override this method entirely
2168
+		if (apply_filters('FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default', true, $this,
2169
+			$this->_registration)) {
2170
+			$form                                              = $this->_get_reg_custom_questions_form(
2171
+				$this->_registration->ID()
2172
+			);
2173
+			$this->_template_args['att_questions']             = count($form->subforms()) > 0
2174
+				? $form->get_html_and_js()
2175
+				: '';
2176
+			$this->_template_args['reg_questions_form_action'] = 'edit_registration';
2177
+			$this->_template_args['REG_ID']                    = $this->_registration->ID();
2178
+			$template_path                                     =
2179
+				REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
2180
+			echo EEH_Template::display_template($template_path, $this->_template_args, true);
2181
+		}
2182
+	}
2183
+
2184
+
2185
+	/**
2186
+	 * form_before_question_group
2187
+	 *
2188
+	 * @deprecated    as of 4.8.32.rc.000
2189
+	 * @access        public
2190
+	 * @param        string $output
2191
+	 * @return        string
2192
+	 */
2193
+	public function form_before_question_group($output)
2194
+	{
2195
+		EE_Error::doing_it_wrong(
2196
+			__CLASS__ . '::' . __FUNCTION__,
2197
+			esc_html__(
2198
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2199
+				'event_espresso'
2200
+			),
2201
+			'4.8.32.rc.000'
2202
+		);
2203
+		return '
2204 2204
 	<table class="form-table ee-width-100">
2205 2205
 		<tbody>
2206 2206
 			';
2207
-    }
2208
-
2209
-
2210
-    /**
2211
-     * form_after_question_group
2212
-     *
2213
-     * @deprecated    as of 4.8.32.rc.000
2214
-     * @access        public
2215
-     * @param        string $output
2216
-     * @return        string
2217
-     */
2218
-    public function form_after_question_group($output)
2219
-    {
2220
-        EE_Error::doing_it_wrong(
2221
-            __CLASS__ . '::' . __FUNCTION__,
2222
-            esc_html__(
2223
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2224
-                'event_espresso'
2225
-            ),
2226
-            '4.8.32.rc.000'
2227
-        );
2228
-        return '
2207
+	}
2208
+
2209
+
2210
+	/**
2211
+	 * form_after_question_group
2212
+	 *
2213
+	 * @deprecated    as of 4.8.32.rc.000
2214
+	 * @access        public
2215
+	 * @param        string $output
2216
+	 * @return        string
2217
+	 */
2218
+	public function form_after_question_group($output)
2219
+	{
2220
+		EE_Error::doing_it_wrong(
2221
+			__CLASS__ . '::' . __FUNCTION__,
2222
+			esc_html__(
2223
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2224
+				'event_espresso'
2225
+			),
2226
+			'4.8.32.rc.000'
2227
+		);
2228
+		return '
2229 2229
 			<tr class="hide-if-no-js">
2230 2230
 				<th> </th>
2231 2231
 				<td class="reg-admin-edit-attendee-question-td">
2232 2232
 					<a class="reg-admin-edit-attendee-question-lnk" href="#" title="'
2233
-               . esc_attr__('click to edit question', 'event_espresso')
2234
-               . '">
2233
+			   . esc_attr__('click to edit question', 'event_espresso')
2234
+			   . '">
2235 2235
 						<span class="reg-admin-edit-question-group-spn lt-grey-txt">'
2236
-               . esc_html__('edit the above question group', 'event_espresso')
2237
-               . '</span>
2236
+			   . esc_html__('edit the above question group', 'event_espresso')
2237
+			   . '</span>
2238 2238
 						<div class="dashicons dashicons-edit"></div>
2239 2239
 					</a>
2240 2240
 				</td>
@@ -2242,558 +2242,558 @@  discard block
 block discarded – undo
2242 2242
 		</tbody>
2243 2243
 	</table>
2244 2244
 ';
2245
-    }
2246
-
2247
-
2248
-    /**
2249
-     * form_form_field_label_wrap
2250
-     *
2251
-     * @deprecated    as of 4.8.32.rc.000
2252
-     * @access        public
2253
-     * @param        string $label
2254
-     * @return        string
2255
-     */
2256
-    public function form_form_field_label_wrap($label)
2257
-    {
2258
-        EE_Error::doing_it_wrong(
2259
-            __CLASS__ . '::' . __FUNCTION__,
2260
-            esc_html__(
2261
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2262
-                'event_espresso'
2263
-            ),
2264
-            '4.8.32.rc.000'
2265
-        );
2266
-        return '
2245
+	}
2246
+
2247
+
2248
+	/**
2249
+	 * form_form_field_label_wrap
2250
+	 *
2251
+	 * @deprecated    as of 4.8.32.rc.000
2252
+	 * @access        public
2253
+	 * @param        string $label
2254
+	 * @return        string
2255
+	 */
2256
+	public function form_form_field_label_wrap($label)
2257
+	{
2258
+		EE_Error::doing_it_wrong(
2259
+			__CLASS__ . '::' . __FUNCTION__,
2260
+			esc_html__(
2261
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2262
+				'event_espresso'
2263
+			),
2264
+			'4.8.32.rc.000'
2265
+		);
2266
+		return '
2267 2267
 			<tr>
2268 2268
 				<th>
2269 2269
 					' . $label . '
2270 2270
 				</th>';
2271
-    }
2272
-
2273
-
2274
-    /**
2275
-     * form_form_field_input__wrap
2276
-     *
2277
-     * @deprecated    as of 4.8.32.rc.000
2278
-     * @access        public
2279
-     * @param        string $input
2280
-     * @return        string
2281
-     */
2282
-    public function form_form_field_input__wrap($input)
2283
-    {
2284
-        EE_Error::doing_it_wrong(
2285
-            __CLASS__ . '::' . __FUNCTION__,
2286
-            esc_html__(
2287
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2288
-                'event_espresso'
2289
-            ),
2290
-            '4.8.32.rc.000'
2291
-        );
2292
-        return '
2271
+	}
2272
+
2273
+
2274
+	/**
2275
+	 * form_form_field_input__wrap
2276
+	 *
2277
+	 * @deprecated    as of 4.8.32.rc.000
2278
+	 * @access        public
2279
+	 * @param        string $input
2280
+	 * @return        string
2281
+	 */
2282
+	public function form_form_field_input__wrap($input)
2283
+	{
2284
+		EE_Error::doing_it_wrong(
2285
+			__CLASS__ . '::' . __FUNCTION__,
2286
+			esc_html__(
2287
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2288
+				'event_espresso'
2289
+			),
2290
+			'4.8.32.rc.000'
2291
+		);
2292
+		return '
2293 2293
 				<td class="reg-admin-attendee-questions-input-td disabled-input">
2294 2294
 					' . $input . '
2295 2295
 				</td>
2296 2296
 			</tr>';
2297
-    }
2298
-
2299
-
2300
-    /**
2301
-     * Updates the registration's custom questions according to the form info, if the form is submitted.
2302
-     * If it's not a post, the "view_registrations" route will be called next on the SAME request
2303
-     * to display the page
2304
-     *
2305
-     * @access protected
2306
-     * @return void
2307
-     * @throws EE_Error
2308
-     */
2309
-    protected function _update_attendee_registration_form()
2310
-    {
2311
-        do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
2312
-        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
2313
-            $REG_ID  = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
2314
-            $success = $this->_save_reg_custom_questions_form($REG_ID);
2315
-            if ($success) {
2316
-                $what  = esc_html__('Registration Form', 'event_espresso');
2317
-                $route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
2318
-                    : array('action' => 'default');
2319
-                $this->_redirect_after_action($success, $what, esc_html__('updated', 'event_espresso'), $route);
2320
-            }
2321
-        }
2322
-    }
2323
-
2324
-
2325
-    /**
2326
-     * Gets the form for saving registrations custom questions (if done
2327
-     * previously retrieves the cached form object, which may have validation errors in it)
2328
-     *
2329
-     * @param int $REG_ID
2330
-     * @return EE_Registration_Custom_Questions_Form
2331
-     * @throws EE_Error
2332
-     */
2333
-    protected function _get_reg_custom_questions_form($REG_ID)
2334
-    {
2335
-        if ( ! $this->_reg_custom_questions_form) {
2336
-            require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
2337
-            $this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(
2338
-                EEM_Registration::instance()->get_one_by_ID($REG_ID)
2339
-            );
2340
-            $this->_reg_custom_questions_form->_construct_finalize(null, null);
2341
-        }
2342
-        return $this->_reg_custom_questions_form;
2343
-    }
2344
-
2345
-
2346
-    /**
2347
-     * Saves
2348
-     *
2349
-     * @access private
2350
-     * @param bool $REG_ID
2351
-     * @return bool
2352
-     * @throws EE_Error
2353
-     */
2354
-    private function _save_reg_custom_questions_form($REG_ID = false)
2355
-    {
2356
-        if ( ! $REG_ID) {
2357
-            EE_Error::add_error(
2358
-                esc_html__(
2359
-                    'An error occurred. No registration ID was received.', 'event_espresso'),
2360
-                __FILE__, __FUNCTION__, __LINE__
2361
-            );
2362
-        }
2363
-        $form = $this->_get_reg_custom_questions_form($REG_ID);
2364
-        $form->receive_form_submission($this->_req_data);
2365
-        $success = false;
2366
-        if ($form->is_valid()) {
2367
-            foreach ($form->subforms() as $question_group_id => $question_group_form) {
2368
-                foreach ($question_group_form->inputs() as $question_id => $input) {
2369
-                    $where_conditions    = array(
2370
-                        'QST_ID' => $question_id,
2371
-                        'REG_ID' => $REG_ID,
2372
-                    );
2373
-                    $possibly_new_values = array(
2374
-                        'ANS_value' => $input->normalized_value(),
2375
-                    );
2376
-                    $answer              = EEM_Answer::instance()->get_one(array($where_conditions));
2377
-                    if ($answer instanceof EE_Answer) {
2378
-                        $success = $answer->save($possibly_new_values);
2379
-                    } else {
2380
-                        //insert it then
2381
-                        $cols_n_vals = array_merge($where_conditions, $possibly_new_values);
2382
-                        $answer      = EE_Answer::new_instance($cols_n_vals);
2383
-                        $success     = $answer->save();
2384
-                    }
2385
-                }
2386
-            }
2387
-        } else {
2388
-            EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
2389
-        }
2390
-        return $success;
2391
-    }
2392
-
2393
-
2394
-    /**
2395
-     *        generates HTML for the Registration main meta box
2396
-     *
2397
-     * @access public
2398
-     * @return void
2399
-     * @throws DomainException
2400
-     * @throws EE_Error
2401
-     */
2402
-    public function _reg_attendees_meta_box()
2403
-    {
2404
-        $REG = EEM_Registration::instance();
2405
-        //get all other registrations on this transaction, and cache
2406
-        //the attendees for them so we don't have to run another query using force_join
2407
-        $registrations                           = $REG->get_all(array(
2408
-            array(
2409
-                'TXN_ID' => $this->_registration->transaction_ID(),
2410
-                'REG_ID' => array('!=', $this->_registration->ID()),
2411
-            ),
2412
-            'force_join' => array('Attendee'),
2413
-        ));
2414
-        $this->_template_args['attendees']       = array();
2415
-        $this->_template_args['attendee_notice'] = '';
2416
-        if (empty($registrations)
2417
-            || (is_array($registrations)
2418
-                && ! EEH_Array::get_one_item_from_array($registrations))
2419
-        ) {
2420
-            EE_Error::add_error(
2421
-                esc_html__(
2422
-                    'There are no records attached to this registration. Something may have gone wrong with the registration',
2423
-                    'event_espresso'
2424
-                ), __FILE__, __FUNCTION__, __LINE__
2425
-            );
2426
-            $this->_template_args['attendee_notice'] = EE_Error::get_notices();
2427
-        } else {
2428
-            $att_nmbr = 1;
2429
-            foreach ($registrations as $registration) {
2430
-                /* @var $registration EE_Registration */
2431
-                $attendee                                                    = $registration->attendee()
2432
-                    ? $registration->attendee()
2433
-                    : EEM_Attendee::instance()
2434
-                                  ->create_default_object();
2435
-                $this->_template_args['attendees'][$att_nmbr]['STS_ID']      = $registration->status_ID();
2436
-                $this->_template_args['attendees'][$att_nmbr]['fname']       = $attendee->fname();
2437
-                $this->_template_args['attendees'][$att_nmbr]['lname']       = $attendee->lname();
2438
-                $this->_template_args['attendees'][$att_nmbr]['email']       = $attendee->email();
2439
-                $this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price();
2440
-                $this->_template_args['attendees'][$att_nmbr]['address']     = implode(
2441
-                    ', ',
2442
-                    $attendee->full_address_as_array()
2443
-                );
2444
-                $this->_template_args['attendees'][$att_nmbr]['att_link']    = self::add_query_args_and_nonce(
2445
-                    array(
2446
-                        'action' => 'edit_attendee',
2447
-                        'post'   => $attendee->ID(),
2448
-                    ),
2449
-                    REG_ADMIN_URL
2450
-                );
2451
-                $this->_template_args['attendees'][$att_nmbr]['event_name']  = $registration->event_obj()->name();
2452
-                $att_nmbr++;
2453
-            }
2454
-            $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2455
-        }
2456
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2457
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2458
-    }
2459
-
2460
-
2461
-    /**
2462
-     *        generates HTML for the Edit Registration side meta box
2463
-     *
2464
-     * @access public
2465
-     * @return void
2466
-     * @throws DomainException
2467
-     * @throws EE_Error
2468
-     */
2469
-    public function _reg_registrant_side_meta_box()
2470
-    {
2471
-        /*@var $attendee EE_Attendee */
2472
-        $att_check = $this->_registration->attendee();
2473
-        $attendee  = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2474
-        //now let's determine if this is not the primary registration.  If it isn't then we set the
2475
-        //primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the
2476
-        //primary registration object (that way we know if we need to show create button or not)
2477
-        if ( ! $this->_registration->is_primary_registrant()) {
2478
-            $primary_registration = $this->_registration->get_primary_registration();
2479
-            $primary_attendee     = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2480
-                : null;
2481
-            if ( ! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2482
-                //in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own
2483
-                //custom attendee object so let's not worry about the primary reg.
2484
-                $primary_registration = null;
2485
-            }
2486
-        } else {
2487
-            $primary_registration = null;
2488
-        }
2489
-        $this->_template_args['ATT_ID']            = $attendee->ID();
2490
-        $this->_template_args['fname']             = $attendee->fname();
2491
-        $this->_template_args['lname']             = $attendee->lname();
2492
-        $this->_template_args['email']             = $attendee->email();
2493
-        $this->_template_args['phone']             = $attendee->phone();
2494
-        $this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2495
-        //edit link
2496
-        $this->_template_args['att_edit_link']  = EE_Admin_Page::add_query_args_and_nonce(array(
2497
-            'action' => 'edit_attendee',
2498
-            'post'   => $attendee->ID(),
2499
-        ), REG_ADMIN_URL);
2500
-        $this->_template_args['att_edit_label'] = esc_html__('View/Edit Contact', 'event_espresso');
2501
-        //create link
2502
-        $this->_template_args['create_link']  = $primary_registration instanceof EE_Registration
2503
-            ? EE_Admin_Page::add_query_args_and_nonce(array(
2504
-                'action'  => 'duplicate_attendee',
2505
-                '_REG_ID' => $this->_registration->ID(),
2506
-            ), REG_ADMIN_URL) : '';
2507
-        $this->_template_args['create_label'] = esc_html__('Create Contact', 'event_espresso');
2508
-        $this->_template_args['att_check']    = $att_check;
2509
-        $template_path                        = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2510
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2511
-    }
2512
-
2513
-
2514
-    /**
2515
-     * trash or restore registrations
2516
-     *
2517
-     * @param  boolean $trash whether to archive or restore
2518
-     * @return void
2519
-     * @throws EE_Error
2520
-     * @throws RuntimeException
2521
-     * @access protected
2522
-     */
2523
-    protected function _trash_or_restore_registrations($trash = true)
2524
-    {
2525
-        //if empty _REG_ID then get out because there's nothing to do
2526
-        if (empty($this->_req_data['_REG_ID'])) {
2527
-            EE_Error::add_error(
2528
-                sprintf(
2529
-                    esc_html__(
2530
-                        'In order to %1$s registrations you must select which ones you wish to %1$s by clicking the checkboxes.',
2531
-                        'event_espresso'
2532
-                    ),
2533
-                    $trash ? 'trash' : 'restore'
2534
-                ),
2535
-                __FILE__, __LINE__, __FUNCTION__
2536
-            );
2537
-            $this->_redirect_after_action(false, '', '', array(), true);
2538
-        }
2539
-        $success = 0;
2540
-        $overwrite_msgs = false;
2541
-        //Checkboxes
2542
-        if ( ! is_array($this->_req_data['_REG_ID'])) {
2543
-            $this->_req_data['_REG_ID'] = array($this->_req_data['_REG_ID']);
2544
-        }
2545
-        $reg_count = count($this->_req_data['_REG_ID']);
2546
-        // cycle thru checkboxes
2547
-        foreach ($this->_req_data['_REG_ID'] as $REG_ID) {
2548
-            /** @var EE_Registration $REG */
2549
-            $REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
2550
-            $payments = $REG->registration_payments();
2551
-            if (! empty($payments)) {
2552
-                $name = $REG->attendee() instanceof EE_Attendee
2553
-                    ? $REG->attendee()->full_name()
2554
-                    : esc_html__('Unknown Attendee', 'event_espresso');
2555
-                $overwrite_msgs = true;
2556
-                EE_Error::add_error(
2557
-                    sprintf(
2558
-                        esc_html__(
2559
-                            'The registration for %s could not be trashed because it has payments attached to the related transaction.  If you wish to trash this registration you must first delete the payments on the related transaction.',
2560
-                            'event_espresso'
2561
-                        ),
2562
-                        $name
2563
-                    ),
2564
-                    __FILE__, __FUNCTION__, __LINE__
2565
-                );
2566
-                //can't trash this registration because it has payments.
2567
-                continue;
2568
-            }
2569
-            $updated = $trash ? $REG->delete() : $REG->restore();
2570
-            if ($updated) {
2571
-                $success++;
2572
-            }
2573
-        }
2574
-        $this->_redirect_after_action(
2575
-            $success === $reg_count, // were ALL registrations affected?
2576
-            $success > 1
2577
-                ? esc_html__('Registrations', 'event_espresso')
2578
-                : esc_html__('Registration', 'event_espresso'),
2579
-            $trash
2580
-                ? esc_html__('moved to the trash', 'event_espresso')
2581
-                : esc_html__('restored', 'event_espresso'),
2582
-            array('action' => 'default'),
2583
-            $overwrite_msgs
2584
-        );
2585
-    }
2586
-
2587
-
2588
-    /**
2589
-     * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2590
-     * registration but also.
2591
-     * 1. Removing relations to EE_Attendee
2592
-     * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2593
-     * ALSO trashed.
2594
-     * 3. Deleting permanently any related Line items but only if the above conditions are met.
2595
-     * 4. Removing relationships between all tickets and the related registrations
2596
-     * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2597
-     * 6. Deleting permanently any related Checkins.
2598
-     *
2599
-     * @return void
2600
-     * @throws EE_Error
2601
-     */
2602
-    protected function _delete_registrations()
2603
-    {
2604
-        $REG_MDL = EEM_Registration::instance();
2605
-        $success = 1;
2606
-        //Checkboxes
2607
-        if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2608
-            // if array has more than one element than success message should be plural
2609
-            $success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2610
-            // cycle thru checkboxes
2611
-            while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2612
-                $REG = $REG_MDL->get_one_by_ID($REG_ID);
2613
-                if ( ! $REG instanceof EE_Registration) {
2614
-                    continue;
2615
-                }
2616
-                $deleted = $this->_delete_registration($REG);
2617
-                if ( ! $deleted) {
2618
-                    $success = 0;
2619
-                }
2620
-            }
2621
-        } else {
2622
-            // grab single id and delete
2623
-            $REG_ID  = $this->_req_data['_REG_ID'];
2624
-            $REG     = $REG_MDL->get_one_by_ID($REG_ID);
2625
-            $deleted = $this->_delete_registration($REG);
2626
-            if ( ! $deleted) {
2627
-                $success = 0;
2628
-            }
2629
-        }
2630
-        $what        = $success > 1
2631
-            ? esc_html__('Registrations', 'event_espresso')
2632
-            : esc_html__('Registration', 'event_espresso');
2633
-        $action_desc = esc_html__('permanently deleted.', 'event_espresso');
2634
-        $this->_redirect_after_action(
2635
-            $success,
2636
-            $what,
2637
-            $action_desc,
2638
-            array('action' => 'default'),
2639
-            true
2640
-        );
2641
-    }
2642
-
2643
-
2644
-    /**
2645
-     * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2646
-     * models get affected.
2647
-     *
2648
-     * @param  EE_Registration $REG registration to be deleted permenantly
2649
-     * @return bool true = successful deletion, false = fail.
2650
-     * @throws EE_Error
2651
-     */
2652
-    protected function _delete_registration(EE_Registration $REG)
2653
-    {
2654
-        //first we start with the transaction... ultimately, we WILL not delete permanently if there are any related
2655
-        //registrations on the transaction that are NOT trashed.
2656
-        $TXN         = $REG->get_first_related('Transaction');
2657
-        $REGS        = $TXN->get_many_related('Registration');
2658
-        $all_trashed = true;
2659
-        foreach ($REGS as $registration) {
2660
-            if ( ! $registration->get('REG_deleted')) {
2661
-                $all_trashed = false;
2662
-            }
2663
-        }
2664
-        if ( ! $all_trashed) {
2665
-            EE_Error::add_error(
2666
-                esc_html__(
2667
-                    'Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
2668
-                    'event_espresso'
2669
-                ),
2670
-                __FILE__, __FUNCTION__, __LINE__
2671
-            );
2672
-            return false;
2673
-        }
2674
-        //k made it here so that means we can delete all the related transactions and their answers (but let's do them
2675
-        //separately from THIS one).
2676
-        foreach ($REGS as $registration) {
2677
-            //delete related answers
2678
-            $registration->delete_related_permanently('Answer');
2679
-            //remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2680
-            $attendee = $registration->get_first_related('Attendee');
2681
-            if ($attendee instanceof EE_Attendee) {
2682
-                $registration->_remove_relation_to($attendee, 'Attendee');
2683
-            }
2684
-            //now remove relationships to tickets on this registration.
2685
-            $registration->_remove_relations('Ticket');
2686
-            //now delete permanently the checkins related to this registration.
2687
-            $registration->delete_related_permanently('Checkin');
2688
-            if ($registration->ID() === $REG->ID()) {
2689
-                continue;
2690
-            } //we don't want to delete permanently the existing registration just yet.
2691
-            //remove relation to transaction for these registrations if NOT the existing registrations
2692
-            $registration->_remove_relations('Transaction');
2693
-            //delete permanently any related messages.
2694
-            $registration->delete_related_permanently('Message');
2695
-            //now delete this registration permanently
2696
-            $registration->delete_permanently();
2697
-        }
2698
-        //now all related registrations on the transaction are handled.  So let's just handle this registration itself
2699
-        // (the transaction and line items should be all that's left).
2700
-        // delete the line items related to the transaction for this registration.
2701
-        $TXN->delete_related_permanently('Line_Item');
2702
-        //we need to remove all the relationships on the transaction
2703
-        $TXN->delete_related_permanently('Payment');
2704
-        $TXN->delete_related_permanently('Extra_Meta');
2705
-        $TXN->delete_related_permanently('Message');
2706
-        //now we can delete this REG permanently (and the transaction of course)
2707
-        $REG->delete_related_permanently('Transaction');
2708
-        return $REG->delete_permanently();
2709
-    }
2710
-
2711
-
2712
-    /**
2713
-     *    generates HTML for the Register New Attendee Admin page
2714
-     *
2715
-     * @access private
2716
-     * @throws DomainException
2717
-     * @throws EE_Error
2718
-     */
2719
-    public function new_registration()
2720
-    {
2721
-        if ( ! $this->_set_reg_event()) {
2722
-            throw new EE_Error(
2723
-                esc_html__(
2724
-                    'Unable to continue with registering because there is no Event ID in the request',
2725
-                    'event_espresso'
2726
-                )
2727
-            );
2728
-        }
2729
-        EE_Registry::instance()->REQ->set_espresso_page(true);
2730
-        // gotta start with a clean slate if we're not coming here via ajax
2731
-        if ( ! defined('DOING_AJAX')
2732
-             && ( ! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2733
-        ) {
2734
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2735
-        }
2736
-        $this->_template_args['event_name'] = '';
2737
-        // event name
2738
-        if ($this->_reg_event) {
2739
-            $this->_template_args['event_name'] = $this->_reg_event->name();
2740
-            $edit_event_url                     = self::add_query_args_and_nonce(array(
2741
-                'action' => 'edit',
2742
-                'post'   => $this->_reg_event->ID(),
2743
-            ), EVENTS_ADMIN_URL);
2744
-            $edit_event_lnk                     = '<a href="'
2745
-                                                  . $edit_event_url
2746
-                                                  . '" title="'
2747
-                                                  . esc_attr__('Edit ', 'event_espresso')
2748
-                                                  . $this->_reg_event->name()
2749
-                                                  . '">'
2750
-                                                  . esc_html__('Edit Event', 'event_espresso')
2751
-                                                  . '</a>';
2752
-            $this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2753
-                                                   . $edit_event_lnk
2754
-                                                   . '</span>';
2755
-        }
2756
-        $this->_template_args['step_content'] = $this->_get_registration_step_content();
2757
-        if (defined('DOING_AJAX')) {
2758
-            $this->_return_json();
2759
-        }
2760
-        // grab header
2761
-        $template_path                              =
2762
-            REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2763
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path,
2764
-            $this->_template_args, true);
2765
-        //$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2766
-        // the details template wrapper
2767
-        $this->display_admin_page_with_sidebar();
2768
-    }
2769
-
2770
-
2771
-    /**
2772
-     * This returns the content for a registration step
2773
-     *
2774
-     * @access protected
2775
-     * @return string html
2776
-     * @throws DomainException
2777
-     * @throws EE_Error
2778
-     */
2779
-    protected function _get_registration_step_content()
2780
-    {
2781
-        if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
2782
-            $warning_msg = sprintf(
2783
-                esc_html__(
2784
-                    '%2$sWARNING!!!%3$s%1$sPlease do not use the back button to return to this page for the purpose of adding another registration.%1$sThis can result in lost and/or corrupted data.%1$sIf you wish to add another registration, then please click the%1$s%7$s"Add Another New Registration to Event"%8$s button%1$son the Transaction details page, after you are redirected.%1$s%1$s%4$s redirecting in %5$s seconds %6$s',
2785
-                    'event_espresso'
2786
-                ),
2787
-                '<br />',
2788
-                '<h3 class="important-notice">',
2789
-                '</h3>',
2790
-                '<div class="float-right">',
2791
-                '<span id="redirect_timer" class="important-notice">30</span>',
2792
-                '</div>',
2793
-                '<b>',
2794
-                '</b>'
2795
-            );
2796
-            return '
2297
+	}
2298
+
2299
+
2300
+	/**
2301
+	 * Updates the registration's custom questions according to the form info, if the form is submitted.
2302
+	 * If it's not a post, the "view_registrations" route will be called next on the SAME request
2303
+	 * to display the page
2304
+	 *
2305
+	 * @access protected
2306
+	 * @return void
2307
+	 * @throws EE_Error
2308
+	 */
2309
+	protected function _update_attendee_registration_form()
2310
+	{
2311
+		do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
2312
+		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
2313
+			$REG_ID  = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
2314
+			$success = $this->_save_reg_custom_questions_form($REG_ID);
2315
+			if ($success) {
2316
+				$what  = esc_html__('Registration Form', 'event_espresso');
2317
+				$route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
2318
+					: array('action' => 'default');
2319
+				$this->_redirect_after_action($success, $what, esc_html__('updated', 'event_espresso'), $route);
2320
+			}
2321
+		}
2322
+	}
2323
+
2324
+
2325
+	/**
2326
+	 * Gets the form for saving registrations custom questions (if done
2327
+	 * previously retrieves the cached form object, which may have validation errors in it)
2328
+	 *
2329
+	 * @param int $REG_ID
2330
+	 * @return EE_Registration_Custom_Questions_Form
2331
+	 * @throws EE_Error
2332
+	 */
2333
+	protected function _get_reg_custom_questions_form($REG_ID)
2334
+	{
2335
+		if ( ! $this->_reg_custom_questions_form) {
2336
+			require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
2337
+			$this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(
2338
+				EEM_Registration::instance()->get_one_by_ID($REG_ID)
2339
+			);
2340
+			$this->_reg_custom_questions_form->_construct_finalize(null, null);
2341
+		}
2342
+		return $this->_reg_custom_questions_form;
2343
+	}
2344
+
2345
+
2346
+	/**
2347
+	 * Saves
2348
+	 *
2349
+	 * @access private
2350
+	 * @param bool $REG_ID
2351
+	 * @return bool
2352
+	 * @throws EE_Error
2353
+	 */
2354
+	private function _save_reg_custom_questions_form($REG_ID = false)
2355
+	{
2356
+		if ( ! $REG_ID) {
2357
+			EE_Error::add_error(
2358
+				esc_html__(
2359
+					'An error occurred. No registration ID was received.', 'event_espresso'),
2360
+				__FILE__, __FUNCTION__, __LINE__
2361
+			);
2362
+		}
2363
+		$form = $this->_get_reg_custom_questions_form($REG_ID);
2364
+		$form->receive_form_submission($this->_req_data);
2365
+		$success = false;
2366
+		if ($form->is_valid()) {
2367
+			foreach ($form->subforms() as $question_group_id => $question_group_form) {
2368
+				foreach ($question_group_form->inputs() as $question_id => $input) {
2369
+					$where_conditions    = array(
2370
+						'QST_ID' => $question_id,
2371
+						'REG_ID' => $REG_ID,
2372
+					);
2373
+					$possibly_new_values = array(
2374
+						'ANS_value' => $input->normalized_value(),
2375
+					);
2376
+					$answer              = EEM_Answer::instance()->get_one(array($where_conditions));
2377
+					if ($answer instanceof EE_Answer) {
2378
+						$success = $answer->save($possibly_new_values);
2379
+					} else {
2380
+						//insert it then
2381
+						$cols_n_vals = array_merge($where_conditions, $possibly_new_values);
2382
+						$answer      = EE_Answer::new_instance($cols_n_vals);
2383
+						$success     = $answer->save();
2384
+					}
2385
+				}
2386
+			}
2387
+		} else {
2388
+			EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
2389
+		}
2390
+		return $success;
2391
+	}
2392
+
2393
+
2394
+	/**
2395
+	 *        generates HTML for the Registration main meta box
2396
+	 *
2397
+	 * @access public
2398
+	 * @return void
2399
+	 * @throws DomainException
2400
+	 * @throws EE_Error
2401
+	 */
2402
+	public function _reg_attendees_meta_box()
2403
+	{
2404
+		$REG = EEM_Registration::instance();
2405
+		//get all other registrations on this transaction, and cache
2406
+		//the attendees for them so we don't have to run another query using force_join
2407
+		$registrations                           = $REG->get_all(array(
2408
+			array(
2409
+				'TXN_ID' => $this->_registration->transaction_ID(),
2410
+				'REG_ID' => array('!=', $this->_registration->ID()),
2411
+			),
2412
+			'force_join' => array('Attendee'),
2413
+		));
2414
+		$this->_template_args['attendees']       = array();
2415
+		$this->_template_args['attendee_notice'] = '';
2416
+		if (empty($registrations)
2417
+			|| (is_array($registrations)
2418
+				&& ! EEH_Array::get_one_item_from_array($registrations))
2419
+		) {
2420
+			EE_Error::add_error(
2421
+				esc_html__(
2422
+					'There are no records attached to this registration. Something may have gone wrong with the registration',
2423
+					'event_espresso'
2424
+				), __FILE__, __FUNCTION__, __LINE__
2425
+			);
2426
+			$this->_template_args['attendee_notice'] = EE_Error::get_notices();
2427
+		} else {
2428
+			$att_nmbr = 1;
2429
+			foreach ($registrations as $registration) {
2430
+				/* @var $registration EE_Registration */
2431
+				$attendee                                                    = $registration->attendee()
2432
+					? $registration->attendee()
2433
+					: EEM_Attendee::instance()
2434
+								  ->create_default_object();
2435
+				$this->_template_args['attendees'][$att_nmbr]['STS_ID']      = $registration->status_ID();
2436
+				$this->_template_args['attendees'][$att_nmbr]['fname']       = $attendee->fname();
2437
+				$this->_template_args['attendees'][$att_nmbr]['lname']       = $attendee->lname();
2438
+				$this->_template_args['attendees'][$att_nmbr]['email']       = $attendee->email();
2439
+				$this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price();
2440
+				$this->_template_args['attendees'][$att_nmbr]['address']     = implode(
2441
+					', ',
2442
+					$attendee->full_address_as_array()
2443
+				);
2444
+				$this->_template_args['attendees'][$att_nmbr]['att_link']    = self::add_query_args_and_nonce(
2445
+					array(
2446
+						'action' => 'edit_attendee',
2447
+						'post'   => $attendee->ID(),
2448
+					),
2449
+					REG_ADMIN_URL
2450
+				);
2451
+				$this->_template_args['attendees'][$att_nmbr]['event_name']  = $registration->event_obj()->name();
2452
+				$att_nmbr++;
2453
+			}
2454
+			$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2455
+		}
2456
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2457
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2458
+	}
2459
+
2460
+
2461
+	/**
2462
+	 *        generates HTML for the Edit Registration side meta box
2463
+	 *
2464
+	 * @access public
2465
+	 * @return void
2466
+	 * @throws DomainException
2467
+	 * @throws EE_Error
2468
+	 */
2469
+	public function _reg_registrant_side_meta_box()
2470
+	{
2471
+		/*@var $attendee EE_Attendee */
2472
+		$att_check = $this->_registration->attendee();
2473
+		$attendee  = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2474
+		//now let's determine if this is not the primary registration.  If it isn't then we set the
2475
+		//primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the
2476
+		//primary registration object (that way we know if we need to show create button or not)
2477
+		if ( ! $this->_registration->is_primary_registrant()) {
2478
+			$primary_registration = $this->_registration->get_primary_registration();
2479
+			$primary_attendee     = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2480
+				: null;
2481
+			if ( ! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2482
+				//in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own
2483
+				//custom attendee object so let's not worry about the primary reg.
2484
+				$primary_registration = null;
2485
+			}
2486
+		} else {
2487
+			$primary_registration = null;
2488
+		}
2489
+		$this->_template_args['ATT_ID']            = $attendee->ID();
2490
+		$this->_template_args['fname']             = $attendee->fname();
2491
+		$this->_template_args['lname']             = $attendee->lname();
2492
+		$this->_template_args['email']             = $attendee->email();
2493
+		$this->_template_args['phone']             = $attendee->phone();
2494
+		$this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2495
+		//edit link
2496
+		$this->_template_args['att_edit_link']  = EE_Admin_Page::add_query_args_and_nonce(array(
2497
+			'action' => 'edit_attendee',
2498
+			'post'   => $attendee->ID(),
2499
+		), REG_ADMIN_URL);
2500
+		$this->_template_args['att_edit_label'] = esc_html__('View/Edit Contact', 'event_espresso');
2501
+		//create link
2502
+		$this->_template_args['create_link']  = $primary_registration instanceof EE_Registration
2503
+			? EE_Admin_Page::add_query_args_and_nonce(array(
2504
+				'action'  => 'duplicate_attendee',
2505
+				'_REG_ID' => $this->_registration->ID(),
2506
+			), REG_ADMIN_URL) : '';
2507
+		$this->_template_args['create_label'] = esc_html__('Create Contact', 'event_espresso');
2508
+		$this->_template_args['att_check']    = $att_check;
2509
+		$template_path                        = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2510
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2511
+	}
2512
+
2513
+
2514
+	/**
2515
+	 * trash or restore registrations
2516
+	 *
2517
+	 * @param  boolean $trash whether to archive or restore
2518
+	 * @return void
2519
+	 * @throws EE_Error
2520
+	 * @throws RuntimeException
2521
+	 * @access protected
2522
+	 */
2523
+	protected function _trash_or_restore_registrations($trash = true)
2524
+	{
2525
+		//if empty _REG_ID then get out because there's nothing to do
2526
+		if (empty($this->_req_data['_REG_ID'])) {
2527
+			EE_Error::add_error(
2528
+				sprintf(
2529
+					esc_html__(
2530
+						'In order to %1$s registrations you must select which ones you wish to %1$s by clicking the checkboxes.',
2531
+						'event_espresso'
2532
+					),
2533
+					$trash ? 'trash' : 'restore'
2534
+				),
2535
+				__FILE__, __LINE__, __FUNCTION__
2536
+			);
2537
+			$this->_redirect_after_action(false, '', '', array(), true);
2538
+		}
2539
+		$success = 0;
2540
+		$overwrite_msgs = false;
2541
+		//Checkboxes
2542
+		if ( ! is_array($this->_req_data['_REG_ID'])) {
2543
+			$this->_req_data['_REG_ID'] = array($this->_req_data['_REG_ID']);
2544
+		}
2545
+		$reg_count = count($this->_req_data['_REG_ID']);
2546
+		// cycle thru checkboxes
2547
+		foreach ($this->_req_data['_REG_ID'] as $REG_ID) {
2548
+			/** @var EE_Registration $REG */
2549
+			$REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
2550
+			$payments = $REG->registration_payments();
2551
+			if (! empty($payments)) {
2552
+				$name = $REG->attendee() instanceof EE_Attendee
2553
+					? $REG->attendee()->full_name()
2554
+					: esc_html__('Unknown Attendee', 'event_espresso');
2555
+				$overwrite_msgs = true;
2556
+				EE_Error::add_error(
2557
+					sprintf(
2558
+						esc_html__(
2559
+							'The registration for %s could not be trashed because it has payments attached to the related transaction.  If you wish to trash this registration you must first delete the payments on the related transaction.',
2560
+							'event_espresso'
2561
+						),
2562
+						$name
2563
+					),
2564
+					__FILE__, __FUNCTION__, __LINE__
2565
+				);
2566
+				//can't trash this registration because it has payments.
2567
+				continue;
2568
+			}
2569
+			$updated = $trash ? $REG->delete() : $REG->restore();
2570
+			if ($updated) {
2571
+				$success++;
2572
+			}
2573
+		}
2574
+		$this->_redirect_after_action(
2575
+			$success === $reg_count, // were ALL registrations affected?
2576
+			$success > 1
2577
+				? esc_html__('Registrations', 'event_espresso')
2578
+				: esc_html__('Registration', 'event_espresso'),
2579
+			$trash
2580
+				? esc_html__('moved to the trash', 'event_espresso')
2581
+				: esc_html__('restored', 'event_espresso'),
2582
+			array('action' => 'default'),
2583
+			$overwrite_msgs
2584
+		);
2585
+	}
2586
+
2587
+
2588
+	/**
2589
+	 * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2590
+	 * registration but also.
2591
+	 * 1. Removing relations to EE_Attendee
2592
+	 * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2593
+	 * ALSO trashed.
2594
+	 * 3. Deleting permanently any related Line items but only if the above conditions are met.
2595
+	 * 4. Removing relationships between all tickets and the related registrations
2596
+	 * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2597
+	 * 6. Deleting permanently any related Checkins.
2598
+	 *
2599
+	 * @return void
2600
+	 * @throws EE_Error
2601
+	 */
2602
+	protected function _delete_registrations()
2603
+	{
2604
+		$REG_MDL = EEM_Registration::instance();
2605
+		$success = 1;
2606
+		//Checkboxes
2607
+		if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2608
+			// if array has more than one element than success message should be plural
2609
+			$success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2610
+			// cycle thru checkboxes
2611
+			while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2612
+				$REG = $REG_MDL->get_one_by_ID($REG_ID);
2613
+				if ( ! $REG instanceof EE_Registration) {
2614
+					continue;
2615
+				}
2616
+				$deleted = $this->_delete_registration($REG);
2617
+				if ( ! $deleted) {
2618
+					$success = 0;
2619
+				}
2620
+			}
2621
+		} else {
2622
+			// grab single id and delete
2623
+			$REG_ID  = $this->_req_data['_REG_ID'];
2624
+			$REG     = $REG_MDL->get_one_by_ID($REG_ID);
2625
+			$deleted = $this->_delete_registration($REG);
2626
+			if ( ! $deleted) {
2627
+				$success = 0;
2628
+			}
2629
+		}
2630
+		$what        = $success > 1
2631
+			? esc_html__('Registrations', 'event_espresso')
2632
+			: esc_html__('Registration', 'event_espresso');
2633
+		$action_desc = esc_html__('permanently deleted.', 'event_espresso');
2634
+		$this->_redirect_after_action(
2635
+			$success,
2636
+			$what,
2637
+			$action_desc,
2638
+			array('action' => 'default'),
2639
+			true
2640
+		);
2641
+	}
2642
+
2643
+
2644
+	/**
2645
+	 * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2646
+	 * models get affected.
2647
+	 *
2648
+	 * @param  EE_Registration $REG registration to be deleted permenantly
2649
+	 * @return bool true = successful deletion, false = fail.
2650
+	 * @throws EE_Error
2651
+	 */
2652
+	protected function _delete_registration(EE_Registration $REG)
2653
+	{
2654
+		//first we start with the transaction... ultimately, we WILL not delete permanently if there are any related
2655
+		//registrations on the transaction that are NOT trashed.
2656
+		$TXN         = $REG->get_first_related('Transaction');
2657
+		$REGS        = $TXN->get_many_related('Registration');
2658
+		$all_trashed = true;
2659
+		foreach ($REGS as $registration) {
2660
+			if ( ! $registration->get('REG_deleted')) {
2661
+				$all_trashed = false;
2662
+			}
2663
+		}
2664
+		if ( ! $all_trashed) {
2665
+			EE_Error::add_error(
2666
+				esc_html__(
2667
+					'Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
2668
+					'event_espresso'
2669
+				),
2670
+				__FILE__, __FUNCTION__, __LINE__
2671
+			);
2672
+			return false;
2673
+		}
2674
+		//k made it here so that means we can delete all the related transactions and their answers (but let's do them
2675
+		//separately from THIS one).
2676
+		foreach ($REGS as $registration) {
2677
+			//delete related answers
2678
+			$registration->delete_related_permanently('Answer');
2679
+			//remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2680
+			$attendee = $registration->get_first_related('Attendee');
2681
+			if ($attendee instanceof EE_Attendee) {
2682
+				$registration->_remove_relation_to($attendee, 'Attendee');
2683
+			}
2684
+			//now remove relationships to tickets on this registration.
2685
+			$registration->_remove_relations('Ticket');
2686
+			//now delete permanently the checkins related to this registration.
2687
+			$registration->delete_related_permanently('Checkin');
2688
+			if ($registration->ID() === $REG->ID()) {
2689
+				continue;
2690
+			} //we don't want to delete permanently the existing registration just yet.
2691
+			//remove relation to transaction for these registrations if NOT the existing registrations
2692
+			$registration->_remove_relations('Transaction');
2693
+			//delete permanently any related messages.
2694
+			$registration->delete_related_permanently('Message');
2695
+			//now delete this registration permanently
2696
+			$registration->delete_permanently();
2697
+		}
2698
+		//now all related registrations on the transaction are handled.  So let's just handle this registration itself
2699
+		// (the transaction and line items should be all that's left).
2700
+		// delete the line items related to the transaction for this registration.
2701
+		$TXN->delete_related_permanently('Line_Item');
2702
+		//we need to remove all the relationships on the transaction
2703
+		$TXN->delete_related_permanently('Payment');
2704
+		$TXN->delete_related_permanently('Extra_Meta');
2705
+		$TXN->delete_related_permanently('Message');
2706
+		//now we can delete this REG permanently (and the transaction of course)
2707
+		$REG->delete_related_permanently('Transaction');
2708
+		return $REG->delete_permanently();
2709
+	}
2710
+
2711
+
2712
+	/**
2713
+	 *    generates HTML for the Register New Attendee Admin page
2714
+	 *
2715
+	 * @access private
2716
+	 * @throws DomainException
2717
+	 * @throws EE_Error
2718
+	 */
2719
+	public function new_registration()
2720
+	{
2721
+		if ( ! $this->_set_reg_event()) {
2722
+			throw new EE_Error(
2723
+				esc_html__(
2724
+					'Unable to continue with registering because there is no Event ID in the request',
2725
+					'event_espresso'
2726
+				)
2727
+			);
2728
+		}
2729
+		EE_Registry::instance()->REQ->set_espresso_page(true);
2730
+		// gotta start with a clean slate if we're not coming here via ajax
2731
+		if ( ! defined('DOING_AJAX')
2732
+			 && ( ! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2733
+		) {
2734
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2735
+		}
2736
+		$this->_template_args['event_name'] = '';
2737
+		// event name
2738
+		if ($this->_reg_event) {
2739
+			$this->_template_args['event_name'] = $this->_reg_event->name();
2740
+			$edit_event_url                     = self::add_query_args_and_nonce(array(
2741
+				'action' => 'edit',
2742
+				'post'   => $this->_reg_event->ID(),
2743
+			), EVENTS_ADMIN_URL);
2744
+			$edit_event_lnk                     = '<a href="'
2745
+												  . $edit_event_url
2746
+												  . '" title="'
2747
+												  . esc_attr__('Edit ', 'event_espresso')
2748
+												  . $this->_reg_event->name()
2749
+												  . '">'
2750
+												  . esc_html__('Edit Event', 'event_espresso')
2751
+												  . '</a>';
2752
+			$this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2753
+												   . $edit_event_lnk
2754
+												   . '</span>';
2755
+		}
2756
+		$this->_template_args['step_content'] = $this->_get_registration_step_content();
2757
+		if (defined('DOING_AJAX')) {
2758
+			$this->_return_json();
2759
+		}
2760
+		// grab header
2761
+		$template_path                              =
2762
+			REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2763
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path,
2764
+			$this->_template_args, true);
2765
+		//$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2766
+		// the details template wrapper
2767
+		$this->display_admin_page_with_sidebar();
2768
+	}
2769
+
2770
+
2771
+	/**
2772
+	 * This returns the content for a registration step
2773
+	 *
2774
+	 * @access protected
2775
+	 * @return string html
2776
+	 * @throws DomainException
2777
+	 * @throws EE_Error
2778
+	 */
2779
+	protected function _get_registration_step_content()
2780
+	{
2781
+		if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
2782
+			$warning_msg = sprintf(
2783
+				esc_html__(
2784
+					'%2$sWARNING!!!%3$s%1$sPlease do not use the back button to return to this page for the purpose of adding another registration.%1$sThis can result in lost and/or corrupted data.%1$sIf you wish to add another registration, then please click the%1$s%7$s"Add Another New Registration to Event"%8$s button%1$son the Transaction details page, after you are redirected.%1$s%1$s%4$s redirecting in %5$s seconds %6$s',
2785
+					'event_espresso'
2786
+				),
2787
+				'<br />',
2788
+				'<h3 class="important-notice">',
2789
+				'</h3>',
2790
+				'<div class="float-right">',
2791
+				'<span id="redirect_timer" class="important-notice">30</span>',
2792
+				'</div>',
2793
+				'<b>',
2794
+				'</b>'
2795
+			);
2796
+			return '
2797 2797
 	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg . '</p></div>
2798 2798
 	<script >
2799 2799
 		// WHOAH !!! it appears that someone is using the back button from the Transaction admin page
@@ -2806,792 +2806,792 @@  discard block
 block discarded – undo
2806 2806
 	        }
2807 2807
 	    }, 800 );
2808 2808
 	</script >';
2809
-        }
2810
-        $template_args = array(
2811
-            'title'                    => '',
2812
-            'content'                  => '',
2813
-            'step_button_text'         => '',
2814
-            'show_notification_toggle' => false,
2815
-        );
2816
-        //to indicate we're processing a new registration
2817
-        $hidden_fields = array(
2818
-            'processing_registration' => array(
2819
-                'type'  => 'hidden',
2820
-                'value' => 0,
2821
-            ),
2822
-            'event_id'                => array(
2823
-                'type'  => 'hidden',
2824
-                'value' => $this->_reg_event->ID(),
2825
-            ),
2826
-        );
2827
-        //if the cart is empty then we know we're at step one so we'll display ticket selector
2828
-        $cart = EE_Registry::instance()->SSN->cart();
2829
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2830
-        switch ($step) {
2831
-            case 'ticket' :
2832
-                $hidden_fields['processing_registration']['value'] = 1;
2833
-                $template_args['title']                            = esc_html__(
2834
-                    'Step One: Select the Ticket for this registration',
2835
-                    'event_espresso'
2836
-                );
2837
-                $template_args['content']                          =
2838
-                    EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
2839
-                $template_args['step_button_text']                 = esc_html__(
2840
-                    'Add Tickets and Continue to Registrant Details',
2841
-                    'event_espresso'
2842
-                );
2843
-                $template_args['show_notification_toggle']         = false;
2844
-                break;
2845
-            case 'questions' :
2846
-                $hidden_fields['processing_registration']['value'] = 2;
2847
-                $template_args['title']                            = esc_html__(
2848
-                    'Step Two: Add Registrant Details for this Registration',
2849
-                    'event_espresso'
2850
-                );
2851
-                //in theory we should be able to run EED_SPCO at this point because the cart should have been setup
2852
-                // properly by the first process_reg_step run.
2853
-                $template_args['content']                  =
2854
-                    EED_Single_Page_Checkout::registration_checkout_for_admin();
2855
-                $template_args['step_button_text']         = esc_html__(
2856
-                    'Save Registration and Continue to Details',
2857
-                    'event_espresso'
2858
-                );
2859
-                $template_args['show_notification_toggle'] = true;
2860
-                break;
2861
-        }
2862
-        //we come back to the process_registration_step route.
2863
-        $this->_set_add_edit_form_tags('process_reg_step', $hidden_fields);
2864
-        return EEH_Template::display_template(
2865
-            REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee_step_content.template.php',
2866
-            $template_args,
2867
-            true
2868
-        );
2869
-    }
2870
-
2871
-
2872
-    /**
2873
-     *        set_reg_event
2874
-     *
2875
-     * @access private
2876
-     * @return bool
2877
-     * @throws EE_Error
2878
-     */
2879
-    private function _set_reg_event()
2880
-    {
2881
-        if (is_object($this->_reg_event)) {
2882
-            return true;
2883
-        }
2884
-        $EVT_ID = (! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
2885
-        if ( ! $EVT_ID) {
2886
-            return false;
2887
-        }
2888
-        $this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2889
-        return true;
2890
-    }
2891
-
2892
-
2893
-    /**
2894
-     * process_reg_step
2895
-     *
2896
-     * @access        public
2897
-     * @return string
2898
-     * @throws DomainException
2899
-     * @throws EE_Error
2900
-     * @throws RuntimeException
2901
-     */
2902
-    public function process_reg_step()
2903
-    {
2904
-        EE_System::do_not_cache();
2905
-        $this->_set_reg_event();
2906
-        EE_Registry::instance()->REQ->set_espresso_page(true);
2907
-        EE_Registry::instance()->REQ->set('uts', time());
2908
-        //what step are we on?
2909
-        $cart = EE_Registry::instance()->SSN->cart();
2910
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2911
-        //if doing ajax then we need to verify the nonce
2912
-        if (defined('DOING_AJAX')) {
2913
-            $nonce = isset($this->_req_data[$this->_req_nonce])
2914
-                ? sanitize_text_field($this->_req_data[$this->_req_nonce]) : '';
2915
-            $this->_verify_nonce($nonce, $this->_req_nonce);
2916
-        }
2917
-        switch ($step) {
2918
-            case 'ticket' :
2919
-                //process ticket selection
2920
-                $success = EED_Ticket_Selector::instance()->process_ticket_selections();
2921
-                if ($success) {
2922
-                    EE_Error::add_success(
2923
-                        esc_html__(
2924
-                            'Tickets Selected. Now complete the registration.',
2925
-                            'event_espresso'
2926
-                        )
2927
-                    );
2928
-                } else {
2929
-                    $query_args['step_error'] = $this->_req_data['step_error'] = true;
2930
-                }
2931
-                if (defined('DOING_AJAX')) {
2932
-                    $this->new_registration(); //display next step
2933
-                } else {
2934
-                    $query_args = array(
2935
-                        'action'                  => 'new_registration',
2936
-                        'processing_registration' => 1,
2937
-                        'event_id'                => $this->_reg_event->ID(),
2938
-                        'uts'                     => time(),
2939
-                    );
2940
-                    $this->_redirect_after_action(
2941
-                        false,
2942
-                        '',
2943
-                        '',
2944
-                        $query_args,
2945
-                        true
2946
-                    );
2947
-                }
2948
-                break;
2949
-            case 'questions' :
2950
-                if (! isset(
2951
-                    $this->_req_data['txn_reg_status_change'],
2952
-                    $this->_req_data['txn_reg_status_change']['send_notifications'])
2953
-                ) {
2954
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
2955
-                }
2956
-                //process registration
2957
-                $transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
2958
-                if ($cart instanceof EE_Cart) {
2959
-                    $grand_total = $cart->get_cart_grand_total();
2960
-                    if ($grand_total instanceof EE_Line_Item) {
2961
-                        $grand_total->save_this_and_descendants_to_txn();
2962
-                    }
2963
-                }
2964
-                if ( ! $transaction instanceof EE_Transaction) {
2965
-                    $query_args = array(
2966
-                        'action'                  => 'new_registration',
2967
-                        'processing_registration' => 2,
2968
-                        'event_id'                => $this->_reg_event->ID(),
2969
-                        'uts'                     => time(),
2970
-                    );
2971
-                    if (defined('DOING_AJAX')) {
2972
-                        //display registration form again because there are errors (maybe validation?)
2973
-                        $this->new_registration();
2974
-                        return;
2975
-                    } else {
2976
-                        $this->_redirect_after_action(
2977
-                            false,
2978
-                            '',
2979
-                            '',
2980
-                            $query_args,
2981
-                            true
2982
-                        );
2983
-                        return;
2984
-                    }
2985
-                }
2986
-                // maybe update status, and make sure to save transaction if not done already
2987
-                if ( ! $transaction->update_status_based_on_total_paid()) {
2988
-                    $transaction->save();
2989
-                }
2990
-                EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2991
-                $this->_req_data = array();
2992
-                $query_args      = array(
2993
-                    'action'        => 'redirect_to_txn',
2994
-                    'TXN_ID'        => $transaction->ID(),
2995
-                    'EVT_ID'        => $this->_reg_event->ID(),
2996
-                    'event_name'    => urlencode($this->_reg_event->name()),
2997
-                    'redirect_from' => 'new_registration',
2998
-                );
2999
-                $this->_redirect_after_action(false, '', '', $query_args, true);
3000
-                break;
3001
-        }
3002
-        //what are you looking here for?  Should be nothing to do at this point.
3003
-    }
3004
-
3005
-
3006
-    /**
3007
-     * redirect_to_txn
3008
-     *
3009
-     * @access public
3010
-     * @return void
3011
-     * @throws EE_Error
3012
-     */
3013
-    public function redirect_to_txn()
3014
-    {
3015
-        EE_System::do_not_cache();
3016
-        EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3017
-        $query_args = array(
3018
-            'action' => 'view_transaction',
3019
-            'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
3020
-            'page'   => 'espresso_transactions',
3021
-        );
3022
-        if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
3023
-            $query_args['EVT_ID']        = $this->_req_data['EVT_ID'];
3024
-            $query_args['event_name']    = urlencode($this->_req_data['event_name']);
3025
-            $query_args['redirect_from'] = $this->_req_data['redirect_from'];
3026
-        }
3027
-        EE_Error::add_success(
3028
-            esc_html__(
3029
-                'Registration Created.  Please review the transaction and add any payments as necessary',
3030
-                'event_espresso'
3031
-            )
3032
-        );
3033
-        $this->_redirect_after_action(false, '', '', $query_args, true);
3034
-    }
3035
-
3036
-
3037
-    /**
3038
-     *        generates HTML for the Attendee Contact List
3039
-     *
3040
-     * @access protected
3041
-     * @return void
3042
-     */
3043
-    protected function _attendee_contact_list_table()
3044
-    {
3045
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3046
-        $this->_search_btn_label = esc_html__('Contacts', 'event_espresso');
3047
-        $this->display_admin_list_table_page_with_no_sidebar();
3048
-    }
3049
-
3050
-
3051
-    /**
3052
-     *        get_attendees
3053
-     *
3054
-     * @param      $per_page
3055
-     * @param bool $count whether to return count or data.
3056
-     * @param bool $trash
3057
-     * @return array
3058
-     * @throws EE_Error
3059
-     * @access public
3060
-     */
3061
-    public function get_attendees($per_page, $count = false, $trash = false)
3062
-    {
3063
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3064
-        require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
3065
-        $ATT_MDL                    = EEM_Attendee::instance();
3066
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
3067
-        switch ($this->_req_data['orderby']) {
3068
-            case 'ATT_ID':
3069
-                $orderby = 'ATT_ID';
3070
-                break;
3071
-            case 'ATT_fname':
3072
-                $orderby = 'ATT_fname';
3073
-                break;
3074
-            case 'ATT_email':
3075
-                $orderby = 'ATT_email';
3076
-                break;
3077
-            case 'ATT_city':
3078
-                $orderby = 'ATT_city';
3079
-                break;
3080
-            case 'STA_ID':
3081
-                $orderby = 'STA_ID';
3082
-                break;
3083
-            case 'CNT_ID':
3084
-                $orderby = 'CNT_ID';
3085
-                break;
3086
-            default:
3087
-                $orderby = 'ATT_lname';
3088
-        }
3089
-        $sort         = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
3090
-            ? $this->_req_data['order']
3091
-            : 'ASC';
3092
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
3093
-            ? $this->_req_data['paged']
3094
-            : 1;
3095
-        $per_page     = isset($per_page) && ! empty($per_page) ? $per_page : 10;
3096
-        $per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
3097
-            ? $this->_req_data['perpage']
3098
-            : $per_page;
3099
-        $_where       = array();
3100
-        if ( ! empty($this->_req_data['s'])) {
3101
-            $sstr         = '%' . $this->_req_data['s'] . '%';
3102
-            $_where['OR'] = array(
3103
-                'Registration.Event.EVT_name'       => array('LIKE', $sstr),
3104
-                'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
3105
-                'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
3106
-                'ATT_fname'                         => array('LIKE', $sstr),
3107
-                'ATT_lname'                         => array('LIKE', $sstr),
3108
-                'ATT_short_bio'                     => array('LIKE', $sstr),
3109
-                'ATT_email'                         => array('LIKE', $sstr),
3110
-                'ATT_address'                       => array('LIKE', $sstr),
3111
-                'ATT_address2'                      => array('LIKE', $sstr),
3112
-                'ATT_city'                          => array('LIKE', $sstr),
3113
-                'Country.CNT_name'                  => array('LIKE', $sstr),
3114
-                'State.STA_name'                    => array('LIKE', $sstr),
3115
-                'ATT_phone'                         => array('LIKE', $sstr),
3116
-                'Registration.REG_final_price'      => array('LIKE', $sstr),
3117
-                'Registration.REG_code'             => array('LIKE', $sstr),
3118
-                'Registration.REG_count'            => array('LIKE', $sstr),
3119
-                'Registration.REG_group_size'       => array('LIKE', $sstr),
3120
-            );
3121
-        }
3122
-        $offset = ($current_page - 1) * $per_page;
3123
-        $limit  = $count ? null : array($offset, $per_page);
3124
-        if ($trash) {
3125
-            $_where['status'] = array('!=', 'publish');
3126
-            $all_attendees    = $count
3127
-                ? $ATT_MDL->count(array(
3128
-                    $_where,
3129
-                    'order_by' => array($orderby => $sort),
3130
-                    'limit'    => $limit,
3131
-                ), 'ATT_ID', true)
3132
-                : $ATT_MDL->get_all(array(
3133
-                    $_where,
3134
-                    'order_by' => array($orderby => $sort),
3135
-                    'limit'    => $limit,
3136
-                ));
3137
-        } else {
3138
-            $_where['status'] = array('IN', array('publish'));
3139
-            $all_attendees    = $count
3140
-                ? $ATT_MDL->count(array(
3141
-                    $_where,
3142
-                    'order_by' => array($orderby => $sort),
3143
-                    'limit'    => $limit,
3144
-                ), 'ATT_ID', true)
3145
-                : $ATT_MDL->get_all(array(
3146
-                    $_where,
3147
-                    'order_by' => array($orderby => $sort),
3148
-                    'limit'    => $limit,
3149
-                ));
3150
-        }
3151
-        return $all_attendees;
3152
-    }
3153
-
3154
-
3155
-    /**
3156
-     * This is just taking care of resending the registration confirmation
3157
-     *
3158
-     * @access protected
3159
-     * @return void
3160
-     */
3161
-    protected function _resend_registration()
3162
-    {
3163
-        $this->_process_resend_registration();
3164
-        $query_args = isset($this->_req_data['redirect_to'])
3165
-            ? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
3166
-            : array('action' => 'default');
3167
-        $this->_redirect_after_action(false, '', '', $query_args, true);
3168
-    }
3169
-
3170
-    /**
3171
-     * Creates a registration report, but accepts the name of a method to use for preparing the query parameters
3172
-     * to use when selecting registrations
3173
-     * @param string $method_name_for_getting_query_params the name of the method (on this class) to use for preparing
3174
-     *                                                     the query parameters from the request
3175
-     * @return void ends the request with a redirect or download
3176
-     */
3177
-    public function _registrations_report_base( $method_name_for_getting_query_params )
3178
-    {
3179
-        if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3180
-            wp_redirect(EE_Admin_Page::add_query_args_and_nonce(
3181
-                array(
3182
-                    'page'        => 'espresso_batch',
3183
-                    'batch'       => 'file',
3184
-                    'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3185
-                    'filters'     => urlencode(
3186
-                        serialize(
3187
-                            call_user_func(
3188
-                                array( $this, $method_name_for_getting_query_params ),
3189
-                                EEH_Array::is_set(
3190
-                                    $this->_req_data,
3191
-                                    'filters',
3192
-                                    array()
3193
-                                )
3194
-                            )
3195
-                        )
3196
-                ),
3197
-                'use_filters' => EEH_Array::is_set($this->_req_data, 'use_filters', false),
3198
-                'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
3199
-                'return_url'  => urlencode($this->_req_data['return_url']),
3200
-            )));
3201
-        } else {
3202
-            $new_request_args = array(
3203
-                'export' => 'report',
3204
-                'action' => 'registrations_report_for_event',
3205
-                'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3206
-            );
3207
-            $this->_req_data = array_merge($this->_req_data, $new_request_args);
3208
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3209
-                require_once(EE_CLASSES . 'EE_Export.class.php');
3210
-                $EE_Export = EE_Export::instance($this->_req_data);
3211
-                $EE_Export->export();
3212
-            }
3213
-        }
3214
-    }
3215
-
3216
-
3217
-
3218
-    /**
3219
-     * Creates a registration report using only query parameters in the request
3220
-     * @return void
3221
-     */
3222
-    public function _registrations_report()
3223
-    {
3224
-        $this->_registrations_report_base('_get_registration_query_parameters');
3225
-    }
3226
-
3227
-
3228
-    public function _contact_list_export()
3229
-    {
3230
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3231
-            require_once(EE_CLASSES . 'EE_Export.class.php');
3232
-            $EE_Export = EE_Export::instance($this->_req_data);
3233
-            $EE_Export->export_attendees();
3234
-        }
3235
-    }
3236
-
3237
-
3238
-    public function _contact_list_report()
3239
-    {
3240
-        if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3241
-            wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
3242
-                'page'        => 'espresso_batch',
3243
-                'batch'       => 'file',
3244
-                'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
3245
-                'return_url'  => urlencode($this->_req_data['return_url']),
3246
-            )));
3247
-        } else {
3248
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3249
-                require_once(EE_CLASSES . 'EE_Export.class.php');
3250
-                $EE_Export = EE_Export::instance($this->_req_data);
3251
-                $EE_Export->report_attendees();
3252
-            }
3253
-        }
3254
-    }
3255
-
3256
-
3257
-
3258
-
3259
-
3260
-    /***************************************        ATTENDEE DETAILS        ***************************************/
3261
-    /**
3262
-     * This duplicates the attendee object for the given incoming registration id and attendee_id.
3263
-     *
3264
-     * @return void
3265
-     * @throws EE_Error
3266
-     */
3267
-    protected function _duplicate_attendee()
3268
-    {
3269
-        $action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
3270
-        //verify we have necessary info
3271
-        if (empty($this->_req_data['_REG_ID'])) {
3272
-            EE_Error::add_error(
3273
-                esc_html__(
3274
-                    'Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
3275
-                    'event_espresso'
3276
-                ), __FILE__, __LINE__, __FUNCTION__
3277
-            );
3278
-            $query_args = array('action' => $action);
3279
-            $this->_redirect_after_action('', '', '', $query_args, true);
3280
-        }
3281
-        //okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
3282
-        $registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
3283
-        $attendee     = $registration->attendee();
3284
-        //remove relation of existing attendee on registration
3285
-        $registration->_remove_relation_to($attendee, 'Attendee');
3286
-        //new attendee
3287
-        $new_attendee = clone $attendee;
3288
-        $new_attendee->set('ATT_ID', 0);
3289
-        $new_attendee->save();
3290
-        //add new attendee to reg
3291
-        $registration->_add_relation_to($new_attendee, 'Attendee');
3292
-        EE_Error::add_success(
3293
-            esc_html__(
3294
-                'New Contact record created.  Now make any edits you wish to make for this contact.',
3295
-                'event_espresso'
3296
-            )
3297
-        );
3298
-        //redirect to edit page for attendee
3299
-        $query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
3300
-        $this->_redirect_after_action('', '', '', $query_args, true);
3301
-    }
3302
-
3303
-
3304
-    //related to cpt routes
3305
-    protected function _insert_update_cpt_item($post_id, $post)
3306
-    {
3307
-        $success  = true;
3308
-        $attendee = EEM_Attendee::instance()->get_one_by_ID($post_id);
3309
-        //for attendee updates
3310
-        if ($post->post_type = 'espresso_attendees' && ! empty($attendee)) {
3311
-            //note we should only be UPDATING attendees at this point.
3312
-            $updated_fields = array(
3313
-                'ATT_fname'     => $this->_req_data['ATT_fname'],
3314
-                'ATT_lname'     => $this->_req_data['ATT_lname'],
3315
-                'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
3316
-                'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
3317
-                'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
3318
-                'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
3319
-                'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
3320
-                'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
3321
-                'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
3322
-                'ATT_email'     => isset($this->_req_data['ATT_email']) ? $this->_req_data['ATT_email'] : '',
3323
-                'ATT_phone'     => isset($this->_req_data['ATT_phone']) ? $this->_req_data['ATT_phone'] : '',
3324
-            );
3325
-            foreach ($updated_fields as $field => $value) {
3326
-                $attendee->set($field, $value);
3327
-            }
3328
-            $success                   = $attendee->save();
3329
-            $attendee_update_callbacks = apply_filters(
3330
-                'FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
3331
-                array()
3332
-            );
3333
-            foreach ($attendee_update_callbacks as $a_callback) {
3334
-                if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
3335
-                    throw new EE_Error(
3336
-                        sprintf(
3337
-                            esc_html__(
3338
-                                'The %s callback given for the "FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update" filter is not a valid callback.  Please check the spelling.',
3339
-                                'event_espresso'
3340
-                            ),
3341
-                            $a_callback
3342
-                        )
3343
-                    );
3344
-                }
3345
-            }
3346
-        }
3347
-        if ($success === false) {
3348
-            EE_Error::add_error(
3349
-                esc_html__(
3350
-                    'Something went wrong with updating the meta table data for the registration.',
3351
-                    'event_espresso'
3352
-                ),
3353
-                __FILE__, __FUNCTION__, __LINE__
3354
-            );
3355
-        }
3356
-    }
3357
-
3358
-
3359
-    public function trash_cpt_item($post_id)
3360
-    {
3361
-    }
3362
-
3363
-
3364
-    public function delete_cpt_item($post_id)
3365
-    {
3366
-    }
3367
-
3368
-
3369
-    public function restore_cpt_item($post_id)
3370
-    {
3371
-    }
3372
-
3373
-
3374
-    protected function _restore_cpt_item($post_id, $revision_id)
3375
-    {
3376
-    }
3377
-
3378
-
3379
-    public function attendee_editor_metaboxes()
3380
-    {
3381
-        $this->verify_cpt_object();
3382
-        remove_meta_box(
3383
-            'postexcerpt',
3384
-            esc_html__('Excerpt', 'event_espresso'),
3385
-            'post_excerpt_meta_box',
3386
-            $this->_cpt_routes[$this->_req_action],
3387
-            'normal',
3388
-            'core'
3389
-        );
3390
-        remove_meta_box('commentstatusdiv', $this->_cpt_routes[$this->_req_action], 'normal', 'core');
3391
-        if (post_type_supports('espresso_attendees', 'excerpt')) {
3392
-            add_meta_box(
3393
-                'postexcerpt',
3394
-                esc_html__('Short Biography', 'event_espresso'),
3395
-                'post_excerpt_meta_box',
3396
-                $this->_cpt_routes[$this->_req_action],
3397
-                'normal'
3398
-            );
3399
-        }
3400
-        if (post_type_supports('espresso_attendees', 'comments')) {
3401
-            add_meta_box(
3402
-                'commentsdiv',
3403
-                esc_html__('Notes on the Contact', 'event_espresso'),
3404
-                'post_comment_meta_box',
3405
-                $this->_cpt_routes[$this->_req_action],
3406
-                'normal',
3407
-                'core'
3408
-            );
3409
-        }
3410
-        add_meta_box(
3411
-            'attendee_contact_info',
3412
-            esc_html__('Contact Info', 'event_espresso'),
3413
-            array($this, 'attendee_contact_info'),
3414
-            $this->_cpt_routes[$this->_req_action],
3415
-            'side',
3416
-            'core'
3417
-        );
3418
-        add_meta_box(
3419
-            'attendee_details_address',
3420
-            esc_html__('Address Details', 'event_espresso'),
3421
-            array($this, 'attendee_address_details'),
3422
-            $this->_cpt_routes[$this->_req_action],
3423
-            'normal',
3424
-            'core'
3425
-        );
3426
-        add_meta_box(
3427
-            'attendee_registrations',
3428
-            esc_html__('Registrations for this Contact', 'event_espresso'),
3429
-            array($this, 'attendee_registrations_meta_box'),
3430
-            $this->_cpt_routes[$this->_req_action],
3431
-            'normal',
3432
-            'high'
3433
-        );
3434
-    }
3435
-
3436
-
3437
-    /**
3438
-     * Metabox for attendee contact info
3439
-     *
3440
-     * @param  WP_Post $post wp post object
3441
-     * @return string attendee contact info ( and form )
3442
-     * @throws DomainException
3443
-     */
3444
-    public function attendee_contact_info($post)
3445
-    {
3446
-        //get attendee object ( should already have it )
3447
-        $this->_template_args['attendee'] = $this->_cpt_model_obj;
3448
-        $template                         = REG_TEMPLATE_PATH . 'attendee_contact_info_metabox_content.template.php';
3449
-        EEH_Template::display_template($template, $this->_template_args);
3450
-    }
3451
-
3452
-
3453
-    /**
3454
-     * Metabox for attendee details
3455
-     *
3456
-     * @param  WP_Post $post wp post object
3457
-     * @return string attendee address details (and form)
3458
-     * @throws DomainException
3459
-     */
3460
-    public function attendee_address_details($post)
3461
-    {
3462
-        //get attendee object (should already have it)
3463
-        $this->_template_args['attendee']     = $this->_cpt_model_obj;
3464
-        $this->_template_args['state_html']   = EEH_Form_Fields::generate_form_input(
3465
-            new EE_Question_Form_Input(
3466
-                EE_Question::new_instance(
3467
-                    array(
3468
-                        'QST_ID'           => 0,
3469
-                        'QST_display_text' => esc_html__('State/Province', 'event_espresso'),
3470
-                        'QST_system'       => 'admin-state',
3471
-                    )
3472
-                ),
3473
-                EE_Answer::new_instance(
3474
-                    array(
3475
-                        'ANS_ID'    => 0,
3476
-                        'ANS_value' => $this->_cpt_model_obj->state_ID(),
3477
-                    )
3478
-                ),
3479
-                array(
3480
-                    'input_id'       => 'STA_ID',
3481
-                    'input_name'     => 'STA_ID',
3482
-                    'input_prefix'   => '',
3483
-                    'append_qstn_id' => false,
3484
-                )
3485
-            )
3486
-        );
3487
-        $this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(
3488
-            new EE_Question_Form_Input(
3489
-                EE_Question::new_instance(
3490
-                    array(
3491
-                        'QST_ID'           => 0,
3492
-                        'QST_display_text' => esc_html__('Country', 'event_espresso'),
3493
-                        'QST_system'       => 'admin-country',
3494
-                    )
3495
-                ),
3496
-                EE_Answer::new_instance(
3497
-                    array(
3498
-                        'ANS_ID'    => 0,
3499
-                        'ANS_value' => $this->_cpt_model_obj->country_ID(),
3500
-                    )
3501
-                ),
3502
-                array(
3503
-                    'input_id'       => 'CNT_ISO',
3504
-                    'input_name'     => 'CNT_ISO',
3505
-                    'input_prefix'   => '',
3506
-                    'append_qstn_id' => false,
3507
-                )
3508
-            )
3509
-        );
3510
-        $template                             =
3511
-            REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
3512
-        EEH_Template::display_template($template, $this->_template_args);
3513
-    }
3514
-
3515
-
3516
-    /**
3517
-     *        _attendee_details
3518
-     *
3519
-     * @access protected
3520
-     * @param $post
3521
-     * @return void
3522
-     * @throws DomainException
3523
-     * @throws EE_Error
3524
-     */
3525
-    public function attendee_registrations_meta_box($post)
3526
-    {
3527
-        $this->_template_args['attendee']      = $this->_cpt_model_obj;
3528
-        $this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
3529
-        $template                              =
3530
-            REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
3531
-        EEH_Template::display_template($template, $this->_template_args);
3532
-    }
3533
-
3534
-
3535
-    /**
3536
-     * add in the form fields for the attendee edit
3537
-     *
3538
-     * @param  WP_Post $post wp post object
3539
-     * @return string html for new form.
3540
-     * @throws DomainException
3541
-     */
3542
-    public function after_title_form_fields($post)
3543
-    {
3544
-        if ($post->post_type == 'espresso_attendees') {
3545
-            $template                  = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
3546
-            $template_args['attendee'] = $this->_cpt_model_obj;
3547
-            EEH_Template::display_template($template, $template_args);
3548
-        }
3549
-    }
3550
-
3551
-
3552
-    /**
3553
-     *        _trash_or_restore_attendee
3554
-     *
3555
-     * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
3556
-     * @return void
3557
-     * @throws EE_Error
3558
-     * @access protected
3559
-     */
3560
-    protected function _trash_or_restore_attendees($trash = true)
3561
-    {
3562
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3563
-        $ATT_MDL = EEM_Attendee::instance();
3564
-        $success = 1;
3565
-        //Checkboxes
3566
-        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3567
-            // if array has more than one element than success message should be plural
3568
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3569
-            // cycle thru checkboxes
3570
-            while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
3571
-                $updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
3572
-                    : $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
3573
-                if ( ! $updated) {
3574
-                    $success = 0;
3575
-                }
3576
-            }
3577
-        } else {
3578
-            // grab single id and delete
3579
-            $ATT_ID = absint($this->_req_data['ATT_ID']);
3580
-            //get attendee
3581
-            $att     = $ATT_MDL->get_one_by_ID($ATT_ID);
3582
-            $updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3583
-            $updated = $att->save();
3584
-            if ( ! $updated) {
3585
-                $success = 0;
3586
-            }
3587
-        }
3588
-        $what        = $success > 1
3589
-            ? esc_html__('Contacts', 'event_espresso')
3590
-            : esc_html__('Contact', 'event_espresso');
3591
-        $action_desc = $trash
3592
-            ? esc_html__('moved to the trash', 'event_espresso')
3593
-            : esc_html__('restored', 'event_espresso');
3594
-        $this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
3595
-    }
2809
+		}
2810
+		$template_args = array(
2811
+			'title'                    => '',
2812
+			'content'                  => '',
2813
+			'step_button_text'         => '',
2814
+			'show_notification_toggle' => false,
2815
+		);
2816
+		//to indicate we're processing a new registration
2817
+		$hidden_fields = array(
2818
+			'processing_registration' => array(
2819
+				'type'  => 'hidden',
2820
+				'value' => 0,
2821
+			),
2822
+			'event_id'                => array(
2823
+				'type'  => 'hidden',
2824
+				'value' => $this->_reg_event->ID(),
2825
+			),
2826
+		);
2827
+		//if the cart is empty then we know we're at step one so we'll display ticket selector
2828
+		$cart = EE_Registry::instance()->SSN->cart();
2829
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2830
+		switch ($step) {
2831
+			case 'ticket' :
2832
+				$hidden_fields['processing_registration']['value'] = 1;
2833
+				$template_args['title']                            = esc_html__(
2834
+					'Step One: Select the Ticket for this registration',
2835
+					'event_espresso'
2836
+				);
2837
+				$template_args['content']                          =
2838
+					EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
2839
+				$template_args['step_button_text']                 = esc_html__(
2840
+					'Add Tickets and Continue to Registrant Details',
2841
+					'event_espresso'
2842
+				);
2843
+				$template_args['show_notification_toggle']         = false;
2844
+				break;
2845
+			case 'questions' :
2846
+				$hidden_fields['processing_registration']['value'] = 2;
2847
+				$template_args['title']                            = esc_html__(
2848
+					'Step Two: Add Registrant Details for this Registration',
2849
+					'event_espresso'
2850
+				);
2851
+				//in theory we should be able to run EED_SPCO at this point because the cart should have been setup
2852
+				// properly by the first process_reg_step run.
2853
+				$template_args['content']                  =
2854
+					EED_Single_Page_Checkout::registration_checkout_for_admin();
2855
+				$template_args['step_button_text']         = esc_html__(
2856
+					'Save Registration and Continue to Details',
2857
+					'event_espresso'
2858
+				);
2859
+				$template_args['show_notification_toggle'] = true;
2860
+				break;
2861
+		}
2862
+		//we come back to the process_registration_step route.
2863
+		$this->_set_add_edit_form_tags('process_reg_step', $hidden_fields);
2864
+		return EEH_Template::display_template(
2865
+			REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee_step_content.template.php',
2866
+			$template_args,
2867
+			true
2868
+		);
2869
+	}
2870
+
2871
+
2872
+	/**
2873
+	 *        set_reg_event
2874
+	 *
2875
+	 * @access private
2876
+	 * @return bool
2877
+	 * @throws EE_Error
2878
+	 */
2879
+	private function _set_reg_event()
2880
+	{
2881
+		if (is_object($this->_reg_event)) {
2882
+			return true;
2883
+		}
2884
+		$EVT_ID = (! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
2885
+		if ( ! $EVT_ID) {
2886
+			return false;
2887
+		}
2888
+		$this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2889
+		return true;
2890
+	}
2891
+
2892
+
2893
+	/**
2894
+	 * process_reg_step
2895
+	 *
2896
+	 * @access        public
2897
+	 * @return string
2898
+	 * @throws DomainException
2899
+	 * @throws EE_Error
2900
+	 * @throws RuntimeException
2901
+	 */
2902
+	public function process_reg_step()
2903
+	{
2904
+		EE_System::do_not_cache();
2905
+		$this->_set_reg_event();
2906
+		EE_Registry::instance()->REQ->set_espresso_page(true);
2907
+		EE_Registry::instance()->REQ->set('uts', time());
2908
+		//what step are we on?
2909
+		$cart = EE_Registry::instance()->SSN->cart();
2910
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2911
+		//if doing ajax then we need to verify the nonce
2912
+		if (defined('DOING_AJAX')) {
2913
+			$nonce = isset($this->_req_data[$this->_req_nonce])
2914
+				? sanitize_text_field($this->_req_data[$this->_req_nonce]) : '';
2915
+			$this->_verify_nonce($nonce, $this->_req_nonce);
2916
+		}
2917
+		switch ($step) {
2918
+			case 'ticket' :
2919
+				//process ticket selection
2920
+				$success = EED_Ticket_Selector::instance()->process_ticket_selections();
2921
+				if ($success) {
2922
+					EE_Error::add_success(
2923
+						esc_html__(
2924
+							'Tickets Selected. Now complete the registration.',
2925
+							'event_espresso'
2926
+						)
2927
+					);
2928
+				} else {
2929
+					$query_args['step_error'] = $this->_req_data['step_error'] = true;
2930
+				}
2931
+				if (defined('DOING_AJAX')) {
2932
+					$this->new_registration(); //display next step
2933
+				} else {
2934
+					$query_args = array(
2935
+						'action'                  => 'new_registration',
2936
+						'processing_registration' => 1,
2937
+						'event_id'                => $this->_reg_event->ID(),
2938
+						'uts'                     => time(),
2939
+					);
2940
+					$this->_redirect_after_action(
2941
+						false,
2942
+						'',
2943
+						'',
2944
+						$query_args,
2945
+						true
2946
+					);
2947
+				}
2948
+				break;
2949
+			case 'questions' :
2950
+				if (! isset(
2951
+					$this->_req_data['txn_reg_status_change'],
2952
+					$this->_req_data['txn_reg_status_change']['send_notifications'])
2953
+				) {
2954
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
2955
+				}
2956
+				//process registration
2957
+				$transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
2958
+				if ($cart instanceof EE_Cart) {
2959
+					$grand_total = $cart->get_cart_grand_total();
2960
+					if ($grand_total instanceof EE_Line_Item) {
2961
+						$grand_total->save_this_and_descendants_to_txn();
2962
+					}
2963
+				}
2964
+				if ( ! $transaction instanceof EE_Transaction) {
2965
+					$query_args = array(
2966
+						'action'                  => 'new_registration',
2967
+						'processing_registration' => 2,
2968
+						'event_id'                => $this->_reg_event->ID(),
2969
+						'uts'                     => time(),
2970
+					);
2971
+					if (defined('DOING_AJAX')) {
2972
+						//display registration form again because there are errors (maybe validation?)
2973
+						$this->new_registration();
2974
+						return;
2975
+					} else {
2976
+						$this->_redirect_after_action(
2977
+							false,
2978
+							'',
2979
+							'',
2980
+							$query_args,
2981
+							true
2982
+						);
2983
+						return;
2984
+					}
2985
+				}
2986
+				// maybe update status, and make sure to save transaction if not done already
2987
+				if ( ! $transaction->update_status_based_on_total_paid()) {
2988
+					$transaction->save();
2989
+				}
2990
+				EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2991
+				$this->_req_data = array();
2992
+				$query_args      = array(
2993
+					'action'        => 'redirect_to_txn',
2994
+					'TXN_ID'        => $transaction->ID(),
2995
+					'EVT_ID'        => $this->_reg_event->ID(),
2996
+					'event_name'    => urlencode($this->_reg_event->name()),
2997
+					'redirect_from' => 'new_registration',
2998
+				);
2999
+				$this->_redirect_after_action(false, '', '', $query_args, true);
3000
+				break;
3001
+		}
3002
+		//what are you looking here for?  Should be nothing to do at this point.
3003
+	}
3004
+
3005
+
3006
+	/**
3007
+	 * redirect_to_txn
3008
+	 *
3009
+	 * @access public
3010
+	 * @return void
3011
+	 * @throws EE_Error
3012
+	 */
3013
+	public function redirect_to_txn()
3014
+	{
3015
+		EE_System::do_not_cache();
3016
+		EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3017
+		$query_args = array(
3018
+			'action' => 'view_transaction',
3019
+			'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
3020
+			'page'   => 'espresso_transactions',
3021
+		);
3022
+		if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
3023
+			$query_args['EVT_ID']        = $this->_req_data['EVT_ID'];
3024
+			$query_args['event_name']    = urlencode($this->_req_data['event_name']);
3025
+			$query_args['redirect_from'] = $this->_req_data['redirect_from'];
3026
+		}
3027
+		EE_Error::add_success(
3028
+			esc_html__(
3029
+				'Registration Created.  Please review the transaction and add any payments as necessary',
3030
+				'event_espresso'
3031
+			)
3032
+		);
3033
+		$this->_redirect_after_action(false, '', '', $query_args, true);
3034
+	}
3035
+
3036
+
3037
+	/**
3038
+	 *        generates HTML for the Attendee Contact List
3039
+	 *
3040
+	 * @access protected
3041
+	 * @return void
3042
+	 */
3043
+	protected function _attendee_contact_list_table()
3044
+	{
3045
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3046
+		$this->_search_btn_label = esc_html__('Contacts', 'event_espresso');
3047
+		$this->display_admin_list_table_page_with_no_sidebar();
3048
+	}
3049
+
3050
+
3051
+	/**
3052
+	 *        get_attendees
3053
+	 *
3054
+	 * @param      $per_page
3055
+	 * @param bool $count whether to return count or data.
3056
+	 * @param bool $trash
3057
+	 * @return array
3058
+	 * @throws EE_Error
3059
+	 * @access public
3060
+	 */
3061
+	public function get_attendees($per_page, $count = false, $trash = false)
3062
+	{
3063
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3064
+		require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
3065
+		$ATT_MDL                    = EEM_Attendee::instance();
3066
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
3067
+		switch ($this->_req_data['orderby']) {
3068
+			case 'ATT_ID':
3069
+				$orderby = 'ATT_ID';
3070
+				break;
3071
+			case 'ATT_fname':
3072
+				$orderby = 'ATT_fname';
3073
+				break;
3074
+			case 'ATT_email':
3075
+				$orderby = 'ATT_email';
3076
+				break;
3077
+			case 'ATT_city':
3078
+				$orderby = 'ATT_city';
3079
+				break;
3080
+			case 'STA_ID':
3081
+				$orderby = 'STA_ID';
3082
+				break;
3083
+			case 'CNT_ID':
3084
+				$orderby = 'CNT_ID';
3085
+				break;
3086
+			default:
3087
+				$orderby = 'ATT_lname';
3088
+		}
3089
+		$sort         = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
3090
+			? $this->_req_data['order']
3091
+			: 'ASC';
3092
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
3093
+			? $this->_req_data['paged']
3094
+			: 1;
3095
+		$per_page     = isset($per_page) && ! empty($per_page) ? $per_page : 10;
3096
+		$per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
3097
+			? $this->_req_data['perpage']
3098
+			: $per_page;
3099
+		$_where       = array();
3100
+		if ( ! empty($this->_req_data['s'])) {
3101
+			$sstr         = '%' . $this->_req_data['s'] . '%';
3102
+			$_where['OR'] = array(
3103
+				'Registration.Event.EVT_name'       => array('LIKE', $sstr),
3104
+				'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
3105
+				'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
3106
+				'ATT_fname'                         => array('LIKE', $sstr),
3107
+				'ATT_lname'                         => array('LIKE', $sstr),
3108
+				'ATT_short_bio'                     => array('LIKE', $sstr),
3109
+				'ATT_email'                         => array('LIKE', $sstr),
3110
+				'ATT_address'                       => array('LIKE', $sstr),
3111
+				'ATT_address2'                      => array('LIKE', $sstr),
3112
+				'ATT_city'                          => array('LIKE', $sstr),
3113
+				'Country.CNT_name'                  => array('LIKE', $sstr),
3114
+				'State.STA_name'                    => array('LIKE', $sstr),
3115
+				'ATT_phone'                         => array('LIKE', $sstr),
3116
+				'Registration.REG_final_price'      => array('LIKE', $sstr),
3117
+				'Registration.REG_code'             => array('LIKE', $sstr),
3118
+				'Registration.REG_count'            => array('LIKE', $sstr),
3119
+				'Registration.REG_group_size'       => array('LIKE', $sstr),
3120
+			);
3121
+		}
3122
+		$offset = ($current_page - 1) * $per_page;
3123
+		$limit  = $count ? null : array($offset, $per_page);
3124
+		if ($trash) {
3125
+			$_where['status'] = array('!=', 'publish');
3126
+			$all_attendees    = $count
3127
+				? $ATT_MDL->count(array(
3128
+					$_where,
3129
+					'order_by' => array($orderby => $sort),
3130
+					'limit'    => $limit,
3131
+				), 'ATT_ID', true)
3132
+				: $ATT_MDL->get_all(array(
3133
+					$_where,
3134
+					'order_by' => array($orderby => $sort),
3135
+					'limit'    => $limit,
3136
+				));
3137
+		} else {
3138
+			$_where['status'] = array('IN', array('publish'));
3139
+			$all_attendees    = $count
3140
+				? $ATT_MDL->count(array(
3141
+					$_where,
3142
+					'order_by' => array($orderby => $sort),
3143
+					'limit'    => $limit,
3144
+				), 'ATT_ID', true)
3145
+				: $ATT_MDL->get_all(array(
3146
+					$_where,
3147
+					'order_by' => array($orderby => $sort),
3148
+					'limit'    => $limit,
3149
+				));
3150
+		}
3151
+		return $all_attendees;
3152
+	}
3153
+
3154
+
3155
+	/**
3156
+	 * This is just taking care of resending the registration confirmation
3157
+	 *
3158
+	 * @access protected
3159
+	 * @return void
3160
+	 */
3161
+	protected function _resend_registration()
3162
+	{
3163
+		$this->_process_resend_registration();
3164
+		$query_args = isset($this->_req_data['redirect_to'])
3165
+			? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
3166
+			: array('action' => 'default');
3167
+		$this->_redirect_after_action(false, '', '', $query_args, true);
3168
+	}
3169
+
3170
+	/**
3171
+	 * Creates a registration report, but accepts the name of a method to use for preparing the query parameters
3172
+	 * to use when selecting registrations
3173
+	 * @param string $method_name_for_getting_query_params the name of the method (on this class) to use for preparing
3174
+	 *                                                     the query parameters from the request
3175
+	 * @return void ends the request with a redirect or download
3176
+	 */
3177
+	public function _registrations_report_base( $method_name_for_getting_query_params )
3178
+	{
3179
+		if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3180
+			wp_redirect(EE_Admin_Page::add_query_args_and_nonce(
3181
+				array(
3182
+					'page'        => 'espresso_batch',
3183
+					'batch'       => 'file',
3184
+					'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3185
+					'filters'     => urlencode(
3186
+						serialize(
3187
+							call_user_func(
3188
+								array( $this, $method_name_for_getting_query_params ),
3189
+								EEH_Array::is_set(
3190
+									$this->_req_data,
3191
+									'filters',
3192
+									array()
3193
+								)
3194
+							)
3195
+						)
3196
+				),
3197
+				'use_filters' => EEH_Array::is_set($this->_req_data, 'use_filters', false),
3198
+				'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
3199
+				'return_url'  => urlencode($this->_req_data['return_url']),
3200
+			)));
3201
+		} else {
3202
+			$new_request_args = array(
3203
+				'export' => 'report',
3204
+				'action' => 'registrations_report_for_event',
3205
+				'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3206
+			);
3207
+			$this->_req_data = array_merge($this->_req_data, $new_request_args);
3208
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3209
+				require_once(EE_CLASSES . 'EE_Export.class.php');
3210
+				$EE_Export = EE_Export::instance($this->_req_data);
3211
+				$EE_Export->export();
3212
+			}
3213
+		}
3214
+	}
3215
+
3216
+
3217
+
3218
+	/**
3219
+	 * Creates a registration report using only query parameters in the request
3220
+	 * @return void
3221
+	 */
3222
+	public function _registrations_report()
3223
+	{
3224
+		$this->_registrations_report_base('_get_registration_query_parameters');
3225
+	}
3226
+
3227
+
3228
+	public function _contact_list_export()
3229
+	{
3230
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3231
+			require_once(EE_CLASSES . 'EE_Export.class.php');
3232
+			$EE_Export = EE_Export::instance($this->_req_data);
3233
+			$EE_Export->export_attendees();
3234
+		}
3235
+	}
3236
+
3237
+
3238
+	public function _contact_list_report()
3239
+	{
3240
+		if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3241
+			wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
3242
+				'page'        => 'espresso_batch',
3243
+				'batch'       => 'file',
3244
+				'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
3245
+				'return_url'  => urlencode($this->_req_data['return_url']),
3246
+			)));
3247
+		} else {
3248
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3249
+				require_once(EE_CLASSES . 'EE_Export.class.php');
3250
+				$EE_Export = EE_Export::instance($this->_req_data);
3251
+				$EE_Export->report_attendees();
3252
+			}
3253
+		}
3254
+	}
3255
+
3256
+
3257
+
3258
+
3259
+
3260
+	/***************************************        ATTENDEE DETAILS        ***************************************/
3261
+	/**
3262
+	 * This duplicates the attendee object for the given incoming registration id and attendee_id.
3263
+	 *
3264
+	 * @return void
3265
+	 * @throws EE_Error
3266
+	 */
3267
+	protected function _duplicate_attendee()
3268
+	{
3269
+		$action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
3270
+		//verify we have necessary info
3271
+		if (empty($this->_req_data['_REG_ID'])) {
3272
+			EE_Error::add_error(
3273
+				esc_html__(
3274
+					'Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
3275
+					'event_espresso'
3276
+				), __FILE__, __LINE__, __FUNCTION__
3277
+			);
3278
+			$query_args = array('action' => $action);
3279
+			$this->_redirect_after_action('', '', '', $query_args, true);
3280
+		}
3281
+		//okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
3282
+		$registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
3283
+		$attendee     = $registration->attendee();
3284
+		//remove relation of existing attendee on registration
3285
+		$registration->_remove_relation_to($attendee, 'Attendee');
3286
+		//new attendee
3287
+		$new_attendee = clone $attendee;
3288
+		$new_attendee->set('ATT_ID', 0);
3289
+		$new_attendee->save();
3290
+		//add new attendee to reg
3291
+		$registration->_add_relation_to($new_attendee, 'Attendee');
3292
+		EE_Error::add_success(
3293
+			esc_html__(
3294
+				'New Contact record created.  Now make any edits you wish to make for this contact.',
3295
+				'event_espresso'
3296
+			)
3297
+		);
3298
+		//redirect to edit page for attendee
3299
+		$query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
3300
+		$this->_redirect_after_action('', '', '', $query_args, true);
3301
+	}
3302
+
3303
+
3304
+	//related to cpt routes
3305
+	protected function _insert_update_cpt_item($post_id, $post)
3306
+	{
3307
+		$success  = true;
3308
+		$attendee = EEM_Attendee::instance()->get_one_by_ID($post_id);
3309
+		//for attendee updates
3310
+		if ($post->post_type = 'espresso_attendees' && ! empty($attendee)) {
3311
+			//note we should only be UPDATING attendees at this point.
3312
+			$updated_fields = array(
3313
+				'ATT_fname'     => $this->_req_data['ATT_fname'],
3314
+				'ATT_lname'     => $this->_req_data['ATT_lname'],
3315
+				'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
3316
+				'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
3317
+				'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
3318
+				'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
3319
+				'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
3320
+				'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
3321
+				'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
3322
+				'ATT_email'     => isset($this->_req_data['ATT_email']) ? $this->_req_data['ATT_email'] : '',
3323
+				'ATT_phone'     => isset($this->_req_data['ATT_phone']) ? $this->_req_data['ATT_phone'] : '',
3324
+			);
3325
+			foreach ($updated_fields as $field => $value) {
3326
+				$attendee->set($field, $value);
3327
+			}
3328
+			$success                   = $attendee->save();
3329
+			$attendee_update_callbacks = apply_filters(
3330
+				'FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
3331
+				array()
3332
+			);
3333
+			foreach ($attendee_update_callbacks as $a_callback) {
3334
+				if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
3335
+					throw new EE_Error(
3336
+						sprintf(
3337
+							esc_html__(
3338
+								'The %s callback given for the "FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update" filter is not a valid callback.  Please check the spelling.',
3339
+								'event_espresso'
3340
+							),
3341
+							$a_callback
3342
+						)
3343
+					);
3344
+				}
3345
+			}
3346
+		}
3347
+		if ($success === false) {
3348
+			EE_Error::add_error(
3349
+				esc_html__(
3350
+					'Something went wrong with updating the meta table data for the registration.',
3351
+					'event_espresso'
3352
+				),
3353
+				__FILE__, __FUNCTION__, __LINE__
3354
+			);
3355
+		}
3356
+	}
3357
+
3358
+
3359
+	public function trash_cpt_item($post_id)
3360
+	{
3361
+	}
3362
+
3363
+
3364
+	public function delete_cpt_item($post_id)
3365
+	{
3366
+	}
3367
+
3368
+
3369
+	public function restore_cpt_item($post_id)
3370
+	{
3371
+	}
3372
+
3373
+
3374
+	protected function _restore_cpt_item($post_id, $revision_id)
3375
+	{
3376
+	}
3377
+
3378
+
3379
+	public function attendee_editor_metaboxes()
3380
+	{
3381
+		$this->verify_cpt_object();
3382
+		remove_meta_box(
3383
+			'postexcerpt',
3384
+			esc_html__('Excerpt', 'event_espresso'),
3385
+			'post_excerpt_meta_box',
3386
+			$this->_cpt_routes[$this->_req_action],
3387
+			'normal',
3388
+			'core'
3389
+		);
3390
+		remove_meta_box('commentstatusdiv', $this->_cpt_routes[$this->_req_action], 'normal', 'core');
3391
+		if (post_type_supports('espresso_attendees', 'excerpt')) {
3392
+			add_meta_box(
3393
+				'postexcerpt',
3394
+				esc_html__('Short Biography', 'event_espresso'),
3395
+				'post_excerpt_meta_box',
3396
+				$this->_cpt_routes[$this->_req_action],
3397
+				'normal'
3398
+			);
3399
+		}
3400
+		if (post_type_supports('espresso_attendees', 'comments')) {
3401
+			add_meta_box(
3402
+				'commentsdiv',
3403
+				esc_html__('Notes on the Contact', 'event_espresso'),
3404
+				'post_comment_meta_box',
3405
+				$this->_cpt_routes[$this->_req_action],
3406
+				'normal',
3407
+				'core'
3408
+			);
3409
+		}
3410
+		add_meta_box(
3411
+			'attendee_contact_info',
3412
+			esc_html__('Contact Info', 'event_espresso'),
3413
+			array($this, 'attendee_contact_info'),
3414
+			$this->_cpt_routes[$this->_req_action],
3415
+			'side',
3416
+			'core'
3417
+		);
3418
+		add_meta_box(
3419
+			'attendee_details_address',
3420
+			esc_html__('Address Details', 'event_espresso'),
3421
+			array($this, 'attendee_address_details'),
3422
+			$this->_cpt_routes[$this->_req_action],
3423
+			'normal',
3424
+			'core'
3425
+		);
3426
+		add_meta_box(
3427
+			'attendee_registrations',
3428
+			esc_html__('Registrations for this Contact', 'event_espresso'),
3429
+			array($this, 'attendee_registrations_meta_box'),
3430
+			$this->_cpt_routes[$this->_req_action],
3431
+			'normal',
3432
+			'high'
3433
+		);
3434
+	}
3435
+
3436
+
3437
+	/**
3438
+	 * Metabox for attendee contact info
3439
+	 *
3440
+	 * @param  WP_Post $post wp post object
3441
+	 * @return string attendee contact info ( and form )
3442
+	 * @throws DomainException
3443
+	 */
3444
+	public function attendee_contact_info($post)
3445
+	{
3446
+		//get attendee object ( should already have it )
3447
+		$this->_template_args['attendee'] = $this->_cpt_model_obj;
3448
+		$template                         = REG_TEMPLATE_PATH . 'attendee_contact_info_metabox_content.template.php';
3449
+		EEH_Template::display_template($template, $this->_template_args);
3450
+	}
3451
+
3452
+
3453
+	/**
3454
+	 * Metabox for attendee details
3455
+	 *
3456
+	 * @param  WP_Post $post wp post object
3457
+	 * @return string attendee address details (and form)
3458
+	 * @throws DomainException
3459
+	 */
3460
+	public function attendee_address_details($post)
3461
+	{
3462
+		//get attendee object (should already have it)
3463
+		$this->_template_args['attendee']     = $this->_cpt_model_obj;
3464
+		$this->_template_args['state_html']   = EEH_Form_Fields::generate_form_input(
3465
+			new EE_Question_Form_Input(
3466
+				EE_Question::new_instance(
3467
+					array(
3468
+						'QST_ID'           => 0,
3469
+						'QST_display_text' => esc_html__('State/Province', 'event_espresso'),
3470
+						'QST_system'       => 'admin-state',
3471
+					)
3472
+				),
3473
+				EE_Answer::new_instance(
3474
+					array(
3475
+						'ANS_ID'    => 0,
3476
+						'ANS_value' => $this->_cpt_model_obj->state_ID(),
3477
+					)
3478
+				),
3479
+				array(
3480
+					'input_id'       => 'STA_ID',
3481
+					'input_name'     => 'STA_ID',
3482
+					'input_prefix'   => '',
3483
+					'append_qstn_id' => false,
3484
+				)
3485
+			)
3486
+		);
3487
+		$this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(
3488
+			new EE_Question_Form_Input(
3489
+				EE_Question::new_instance(
3490
+					array(
3491
+						'QST_ID'           => 0,
3492
+						'QST_display_text' => esc_html__('Country', 'event_espresso'),
3493
+						'QST_system'       => 'admin-country',
3494
+					)
3495
+				),
3496
+				EE_Answer::new_instance(
3497
+					array(
3498
+						'ANS_ID'    => 0,
3499
+						'ANS_value' => $this->_cpt_model_obj->country_ID(),
3500
+					)
3501
+				),
3502
+				array(
3503
+					'input_id'       => 'CNT_ISO',
3504
+					'input_name'     => 'CNT_ISO',
3505
+					'input_prefix'   => '',
3506
+					'append_qstn_id' => false,
3507
+				)
3508
+			)
3509
+		);
3510
+		$template                             =
3511
+			REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
3512
+		EEH_Template::display_template($template, $this->_template_args);
3513
+	}
3514
+
3515
+
3516
+	/**
3517
+	 *        _attendee_details
3518
+	 *
3519
+	 * @access protected
3520
+	 * @param $post
3521
+	 * @return void
3522
+	 * @throws DomainException
3523
+	 * @throws EE_Error
3524
+	 */
3525
+	public function attendee_registrations_meta_box($post)
3526
+	{
3527
+		$this->_template_args['attendee']      = $this->_cpt_model_obj;
3528
+		$this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
3529
+		$template                              =
3530
+			REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
3531
+		EEH_Template::display_template($template, $this->_template_args);
3532
+	}
3533
+
3534
+
3535
+	/**
3536
+	 * add in the form fields for the attendee edit
3537
+	 *
3538
+	 * @param  WP_Post $post wp post object
3539
+	 * @return string html for new form.
3540
+	 * @throws DomainException
3541
+	 */
3542
+	public function after_title_form_fields($post)
3543
+	{
3544
+		if ($post->post_type == 'espresso_attendees') {
3545
+			$template                  = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
3546
+			$template_args['attendee'] = $this->_cpt_model_obj;
3547
+			EEH_Template::display_template($template, $template_args);
3548
+		}
3549
+	}
3550
+
3551
+
3552
+	/**
3553
+	 *        _trash_or_restore_attendee
3554
+	 *
3555
+	 * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
3556
+	 * @return void
3557
+	 * @throws EE_Error
3558
+	 * @access protected
3559
+	 */
3560
+	protected function _trash_or_restore_attendees($trash = true)
3561
+	{
3562
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3563
+		$ATT_MDL = EEM_Attendee::instance();
3564
+		$success = 1;
3565
+		//Checkboxes
3566
+		if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3567
+			// if array has more than one element than success message should be plural
3568
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3569
+			// cycle thru checkboxes
3570
+			while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
3571
+				$updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
3572
+					: $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
3573
+				if ( ! $updated) {
3574
+					$success = 0;
3575
+				}
3576
+			}
3577
+		} else {
3578
+			// grab single id and delete
3579
+			$ATT_ID = absint($this->_req_data['ATT_ID']);
3580
+			//get attendee
3581
+			$att     = $ATT_MDL->get_one_by_ID($ATT_ID);
3582
+			$updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3583
+			$updated = $att->save();
3584
+			if ( ! $updated) {
3585
+				$success = 0;
3586
+			}
3587
+		}
3588
+		$what        = $success > 1
3589
+			? esc_html__('Contacts', 'event_espresso')
3590
+			: esc_html__('Contact', 'event_espresso');
3591
+		$action_desc = $trash
3592
+			? esc_html__('moved to the trash', 'event_espresso')
3593
+			: esc_html__('restored', 'event_espresso');
3594
+		$this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
3595
+	}
3596 3596
 
3597 3597
 }
Please login to merge, or discard this patch.
admin_pages/events/Events_Admin_List_Table.class.php 2 patches
Indentation   +541 added lines, -541 removed lines patch added patch discarded remove patch
@@ -18,545 +18,545 @@
 block discarded – undo
18 18
 class Events_Admin_List_Table extends EE_Admin_List_Table
19 19
 {
20 20
 
21
-    /**
22
-     * @var EE_Datetime
23
-     */
24
-    private $_dtt;
25
-
26
-
27
-
28
-    /**
29
-     * Initial setup of data properties for the list table.
30
-     */
31
-    protected function _setup_data()
32
-    {
33
-        $this->_data = $this->_admin_page->get_events($this->_per_page, $this->_current_page);
34
-        $this->_all_data_count = $this->_admin_page->get_events(0, 0, true);
35
-    }
36
-
37
-
38
-
39
-    /**
40
-     * Set up of additional properties for the list table.
41
-     */
42
-    protected function _set_properties()
43
-    {
44
-        $this->_wp_list_args = array(
45
-            'singular' => esc_html__('event', 'event_espresso'),
46
-            'plural'   => esc_html__('events', 'event_espresso'),
47
-            'ajax'     => true, //for now
48
-            'screen'   => $this->_admin_page->get_current_screen()->id,
49
-        );
50
-        $this->_columns = array(
51
-            'cb'              => '<input type="checkbox" />',
52
-            'id'              => esc_html__('ID', 'event_espresso'),
53
-            'name'            => esc_html__('Name', 'event_espresso'),
54
-            'author'          => esc_html__('Author', 'event_espresso'),
55
-            'venue'           => esc_html__('Venue', 'event_espresso'),
56
-            'start_date_time' => esc_html__('Event Start', 'event_espresso'),
57
-            'reg_begins'      => esc_html__('On Sale', 'event_espresso'),
58
-            'attendees'       => '<span class="dashicons dashicons-groups ee-icon-color-ee-green ee-icon-size-20">'
59
-                                 . '</span>',
60
-            //'tkts_sold' => esc_html__('Tickets Sold', 'event_espresso'),
61
-            'actions'         => esc_html__('Actions', 'event_espresso'),
62
-        );
63
-        $this->_sortable_columns = array(
64
-            'id'              => array('EVT_ID' => true),
65
-            'name'            => array('EVT_name' => false),
66
-            'author'          => array('EVT_wp_user' => false),
67
-            'venue'           => array('Venue.VNU_name' => false),
68
-            'start_date_time' => array('Datetime.DTT_EVT_start' => false),
69
-            'reg_begins'      => array('Datetime.Ticket.TKT_start_date' => false),
70
-        );
71
-        $this->_primary_column = 'id';
72
-        $this->_hidden_columns = array('author');
73
-    }
74
-
75
-
76
-
77
-    /**
78
-     * @return array
79
-     */
80
-    protected function _get_table_filters()
81
-    {
82
-        return array(); //no filters with decaf
83
-    }
84
-
85
-
86
-
87
-    /**
88
-     * Setup of views properties.
89
-     *
90
-     * @throws InvalidDataTypeException
91
-     * @throws InvalidInterfaceException
92
-     * @throws InvalidArgumentException
93
-     */
94
-    protected function _add_view_counts()
95
-    {
96
-        $this->_views['all']['count'] = $this->_admin_page->total_events();
97
-        $this->_views['draft']['count'] = $this->_admin_page->total_events_draft();
98
-        if (EE_Registry::instance()->CAP->current_user_can(
99
-            'ee_delete_events',
100
-            'espresso_events_trash_events'
101
-        )) {
102
-            $this->_views['trash']['count'] = $this->_admin_page->total_trashed_events();
103
-        }
104
-    }
105
-
106
-
107
-
108
-    /**
109
-     * @param EE_Event $item
110
-     * @return string
111
-     * @throws EE_Error
112
-     */
113
-    protected function _get_row_class($item)
114
-    {
115
-        $class = parent::_get_row_class($item);
116
-        //add status class
117
-        $class .= $item instanceof EE_Event
118
-            ? ' ee-status-strip event-status-' . $item->get_active_status()
119
-            : '';
120
-        if ($this->_has_checkbox_column) {
121
-            $class .= ' has-checkbox-column';
122
-        }
123
-        return $class;
124
-    }
125
-
126
-
127
-
128
-    /**
129
-     * @param EE_Event $item
130
-     * @return string
131
-     * @throws EE_Error
132
-     */
133
-    public function column_status(EE_Event $item)
134
-    {
135
-        return '<span class="ee-status-strip ee-status-strip-td event-status-'
136
-               . $item->get_active_status()
137
-               . '"></span>';
138
-    }
139
-
140
-
141
-
142
-    /**
143
-     * @param  EE_Event $item
144
-     * @return string
145
-     * @throws EE_Error
146
-     */
147
-    public function column_cb($item)
148
-    {
149
-        if (! $item instanceof EE_Event) {
150
-            return '';
151
-        }
152
-        $this->_dtt = $item->primary_datetime(); //set this for use in other columns
153
-        //does event have any attached registrations?
154
-        $regs = $item->count_related('Registration');
155
-        return $regs > 0 && $this->_view === 'trash'
156
-            ? '<span class="ee-lock-icon"></span>'
157
-            : sprintf(
158
-                '<input type="checkbox" name="EVT_IDs[]" value="%s" />',
159
-                $item->ID()
160
-            );
161
-    }
162
-
163
-
164
-
165
-    /**
166
-     * @param EE_Event $item
167
-     * @return mixed|string
168
-     * @throws EE_Error
169
-     */
170
-    public function column_id(EE_Event $item)
171
-    {
172
-        $content = $item->ID();
173
-        $content .= '  <span class="show-on-mobile-view-only">' . $item->name() . '</span>';
174
-        return $content;
175
-    }
176
-
177
-
178
-
179
-    /**
180
-     * @param EE_Event $item
181
-     * @return string
182
-     * @throws EE_Error
183
-     * @throws InvalidArgumentException
184
-     * @throws InvalidDataTypeException
185
-     * @throws InvalidInterfaceException
186
-     */
187
-    public function column_name(EE_Event $item)
188
-    {
189
-        $edit_query_args = array(
190
-            'action' => 'edit',
191
-            'post'   => $item->ID(),
192
-        );
193
-        $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
194
-        $actions = $this->_column_name_action_setup($item);
195
-        $status = ''; //$item->status() !== 'publish' ? ' (' . $item->status() . ')' : '';
196
-        $content = '<strong><a class="row-title" href="'
197
-                   . $edit_link . '">'
198
-                   . $item->name()
199
-                   . '</a></strong>'
200
-                   . $status;
201
-        $content .= '<br><span class="ee-status-text-small">'
202
-                    . EEH_Template::pretty_status(
203
-                $item->get_active_status(),
204
-                false,
205
-                'sentence'
206
-            )
207
-                    . '</span>';
208
-        $content .= $this->row_actions($actions);
209
-        return $content;
210
-    }
211
-
212
-
213
-
214
-    /**
215
-     * Just a method for setting up the actions for the name column
216
-     *
217
-     * @param EE_Event $item
218
-     * @return array array of actions
219
-     * @throws EE_Error
220
-     * @throws InvalidArgumentException
221
-     * @throws InvalidDataTypeException
222
-     * @throws InvalidInterfaceException
223
-     */
224
-    protected function _column_name_action_setup(EE_Event $item)
225
-    {
226
-        //todo: remove when attendees is active
227
-        if (! defined('REG_ADMIN_URL')) {
228
-            define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
229
-        }
230
-        $actions = array();
231
-        $restore_event_link = '';
232
-        $delete_event_link = '';
233
-        $trash_event_link = '';
234
-        if (EE_Registry::instance()->CAP->current_user_can(
235
-            'ee_edit_event',
236
-            'espresso_events_edit',
237
-            $item->ID()
238
-        )) {
239
-            $edit_query_args = array(
240
-                'action' => 'edit',
241
-                'post'   => $item->ID(),
242
-            );
243
-            $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
244
-            $actions['edit'] = '<a href="' . $edit_link . '"'
245
-                               . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
246
-                               . esc_html__('Edit', 'event_espresso')
247
-                               . '</a>';
248
-        }
249
-        if (
250
-            EE_Registry::instance()->CAP->current_user_can(
251
-                'ee_read_registrations',
252
-                'espresso_registrations_view_registration'
253
-            )
254
-            && EE_Registry::instance()->CAP->current_user_can(
255
-                'ee_read_event',
256
-                'espresso_registrations_view_registration',
257
-                $item->ID()
258
-            )
259
-        ) {
260
-            $attendees_query_args = array(
261
-                'action'   => 'default',
262
-                'event_id' => $item->ID(),
263
-            );
264
-            $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
265
-            $actions['attendees'] = '<a href="' . $attendees_link . '"'
266
-                                    . ' title="' . esc_attr__('View Registrations', 'event_espresso') . '">'
267
-                                    . esc_html__('Registrations', 'event_espresso')
268
-                                    . '</a>';
269
-        }
270
-        if (
271
-        EE_Registry::instance()->CAP->current_user_can(
272
-            'ee_delete_event',
273
-            'espresso_events_trash_event',
274
-            $item->ID()
275
-        )
276
-        ) {
277
-            $trash_event_query_args = array(
278
-                'action' => 'trash_event',
279
-                'EVT_ID' => $item->ID(),
280
-            );
281
-            $trash_event_link = EE_Admin_Page::add_query_args_and_nonce(
282
-                $trash_event_query_args,
283
-                EVENTS_ADMIN_URL
284
-            );
285
-        }
286
-        if (
287
-        EE_Registry::instance()->CAP->current_user_can(
288
-            'ee_delete_event',
289
-            'espresso_events_restore_event',
290
-            $item->ID()
291
-        )
292
-        ) {
293
-            $restore_event_query_args = array(
294
-                'action' => 'restore_event',
295
-                'EVT_ID' => $item->ID(),
296
-            );
297
-            $restore_event_link = EE_Admin_Page::add_query_args_and_nonce(
298
-                $restore_event_query_args,
299
-                EVENTS_ADMIN_URL
300
-            );
301
-        }
302
-        if (
303
-        EE_Registry::instance()->CAP->current_user_can(
304
-            'ee_delete_event',
305
-            'espresso_events_delete_event',
306
-            $item->ID()
307
-        )
308
-        ) {
309
-            $delete_event_query_args = array(
310
-                'action' => 'delete_event',
311
-                'EVT_ID' => $item->ID(),
312
-            );
313
-            $delete_event_link = EE_Admin_Page::add_query_args_and_nonce(
314
-                $delete_event_query_args,
315
-                EVENTS_ADMIN_URL
316
-            );
317
-        }
318
-        $view_link = get_permalink($item->ID());
319
-        $actions['view'] = '<a href="' . $view_link . '"'
320
-                           . ' title="' . esc_attr__('View Event', 'event_espresso') . '">'
321
-                           . esc_html__('View', 'event_espresso')
322
-                           . '</a>';
323
-        if ($item->get('status') === 'trash') {
324
-            if (EE_Registry::instance()->CAP->current_user_can(
325
-                'ee_delete_event',
326
-                'espresso_events_restore_event',
327
-                $item->ID()
328
-            )) {
329
-                $actions['restore_from_trash'] = '<a href="' . $restore_event_link . '"'
330
-                                                 . ' title="' . esc_attr__('Restore from Trash', 'event_espresso')
331
-                                                 . '">'
332
-                                                 . esc_html__('Restore from Trash', 'event_espresso')
333
-                                                 . '</a>';
334
-            }
335
-            if (
336
-                $item->count_related('Registration') === 0
337
-                && EE_Registry::instance()->CAP->current_user_can(
338
-                    'ee_delete_event',
339
-                    'espresso_events_delete_event',
340
-                    $item->ID()
341
-                )
342
-            ) {
343
-                $actions['delete'] = '<a href="' . $delete_event_link . '"'
344
-                                     . ' title="' . esc_attr__('Delete Permanently', 'event_espresso') . '">'
345
-                                     . esc_html__('Delete Permanently', 'event_espresso')
346
-                                     . '</a>';
347
-            }
348
-        } else {
349
-            if (
350
-                EE_Registry::instance()->CAP->current_user_can(
351
-                    'ee_delete_event',
352
-                    'espresso_events_trash_event',
353
-                    $item->ID()
354
-                )
355
-            ) {
356
-                $actions['move to trash'] = '<a href="' . $trash_event_link . '"'
357
-                                            . ' title="' . esc_attr__('Trash Event', 'event_espresso') . '">'
358
-                                            . esc_html__('Trash', 'event_espresso')
359
-                                            . '</a>';
360
-            }
361
-        }
362
-        return $actions;
363
-    }
364
-
365
-
366
-
367
-    /**
368
-     * @param EE_Event $item
369
-     * @return string
370
-     * @throws EE_Error
371
-     */
372
-    public function column_author(EE_Event $item)
373
-    {
374
-        //user author info
375
-        $event_author = get_userdata($item->wp_user());
376
-        $gravatar = get_avatar($item->wp_user(), '15');
377
-        //filter link
378
-        $query_args = array(
379
-            'action'      => 'default',
380
-            'EVT_wp_user' => $item->wp_user(),
381
-        );
382
-        $filter_url = EE_Admin_Page::add_query_args_and_nonce($query_args, EVENTS_ADMIN_URL);
383
-        return $gravatar . '  <a href="' . $filter_url . '"'
384
-               . ' title="' . esc_attr__('Click to filter events by this author.', 'event_espresso') . '">'
385
-               . $event_author->display_name
386
-               . '</a>';
387
-    }
388
-
389
-
390
-
391
-    /**
392
-     * @param EE_Event $item
393
-     * @return string
394
-     * @throws EE_Error
395
-     */
396
-    public function column_venue(EE_Event $item)
397
-    {
398
-        $venue = $item->get_first_related('Venue');
399
-        return ! empty($venue)
400
-            ? $venue->name()
401
-            : '';
402
-    }
403
-
404
-
405
-
406
-    /**
407
-     * @param EE_Event $item
408
-     * @throws EE_Error
409
-     */
410
-    public function column_start_date_time(EE_Event $item)
411
-    {
412
-        echo ! empty($this->_dtt)
413
-            ? $this->_dtt->get_i18n_datetime('DTT_EVT_start')
414
-            : esc_html__('No Date was saved for this Event', 'event_espresso');
415
-        //display in user's timezone?
416
-        echo ! empty($this->_dtt)
417
-            ? $this->_dtt->display_in_my_timezone(
418
-                'DTT_EVT_start',
419
-                'get_i18n_datetime',
420
-                '',
421
-                'My Timezone: '
422
-            )
423
-            : '';
424
-    }
425
-
426
-
427
-
428
-    /**
429
-     * @param EE_Event $item
430
-     * @throws EE_Error
431
-     */
432
-    public function column_reg_begins(EE_Event $item)
433
-    {
434
-        $reg_start = $item->get_ticket_with_earliest_start_time();
435
-        echo ! empty($reg_start)
436
-            ? $reg_start->get_i18n_datetime('TKT_start_date')
437
-            : esc_html__('No Tickets have been setup for this Event', 'event_espresso');
438
-        //display in user's timezone?
439
-        echo ! empty($reg_start)
440
-            ? $reg_start->display_in_my_timezone(
441
-                'TKT_start_date',
442
-                'get_i18n_datetime',
443
-                '',
444
-                'My Timezone: '
445
-            )
446
-            : '';
447
-    }
448
-
449
-
450
-
451
-    /**
452
-     * @param EE_Event $item
453
-     * @return int|string
454
-     * @throws EE_Error
455
-     * @throws InvalidArgumentException
456
-     * @throws InvalidDataTypeException
457
-     * @throws InvalidInterfaceException
458
-     */
459
-    public function column_attendees(EE_Event $item)
460
-    {
461
-        $attendees_query_args = array(
462
-            'action'   => 'default',
463
-            'event_id' => $item->ID(),
464
-        );
465
-        $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
466
-        $registered_attendees = EEM_Registration::instance()->get_event_registration_count($item->ID());
467
-        return EE_Registry::instance()->CAP->current_user_can(
468
-            'ee_read_event',
469
-            'espresso_registrations_view_registration',
470
-            $item->ID()
471
-        )
472
-               && EE_Registry::instance()->CAP->current_user_can(
473
-            'ee_read_registrations',
474
-            'espresso_registrations_view_registration'
475
-        )
476
-            ? '<a href="' . $attendees_link . '">' . $registered_attendees . '</a>'
477
-            : $registered_attendees;
478
-    }
479
-
480
-
481
-
482
-    /**
483
-     * @param EE_Event $item
484
-     * @return float
485
-     * @throws EE_Error
486
-     * @throws InvalidArgumentException
487
-     * @throws InvalidDataTypeException
488
-     * @throws InvalidInterfaceException
489
-     */
490
-    public function column_tkts_sold(EE_Event $item)
491
-    {
492
-        return EEM_Ticket::instance()->sum(array(array('Datetime.EVT_ID' => $item->ID())), 'TKT_sold');
493
-    }
494
-
495
-
496
-
497
-    /**
498
-     * @param EE_Event $item
499
-     * @return string
500
-     * @throws EE_Error
501
-     * @throws InvalidArgumentException
502
-     * @throws InvalidDataTypeException
503
-     * @throws InvalidInterfaceException
504
-     */
505
-    public function column_actions(EE_Event $item)
506
-    {
507
-        //todo: remove when attendees is active
508
-        if (! defined('REG_ADMIN_URL')) {
509
-            define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
510
-        }
511
-        $action_links = array();
512
-        $view_link = get_permalink($item->ID());
513
-        $action_links[] = '<a href="' . $view_link . '"'
514
-                         . ' title="' . esc_attr__('View Event', 'event_espresso') . '" target="_blank">';
515
-        $action_links[] = '<div class="dashicons dashicons-search"></div></a>';
516
-        if (EE_Registry::instance()->CAP->current_user_can(
517
-            'ee_edit_event',
518
-            'espresso_events_edit',
519
-            $item->ID()
520
-        )) {
521
-            $edit_query_args = array(
522
-                'action' => 'edit',
523
-                'post'   => $item->ID(),
524
-            );
525
-            $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
526
-            $action_links[] = '<a href="' . $edit_link . '"'
527
-                             . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
528
-                             . '<div class="ee-icon ee-icon-calendar-edit"></div>'
529
-                             . '</a>';
530
-        }
531
-        if (
532
-            EE_Registry::instance()->CAP->current_user_can(
533
-                'ee_read_registrations',
534
-                'espresso_registrations_view_registration'
535
-            ) && EE_Registry::instance()->CAP->current_user_can(
536
-                'ee_read_event',
537
-                'espresso_registrations_view_registration',
538
-                $item->ID()
539
-            )
540
-        ) {
541
-            $attendees_query_args = array(
542
-                'action'   => 'default',
543
-                'event_id' => $item->ID(),
544
-            );
545
-            $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
546
-            $action_links[] = '<a href="' . $attendees_link . '"'
547
-                             . ' title="' . esc_attr__('View Registrants', 'event_espresso') . '">'
548
-                             . '<div class="dashicons dashicons-groups"></div>'
549
-                             . '</a>';
550
-        }
551
-        $action_links = apply_filters(
552
-            'FHEE__Events_Admin_List_Table__column_actions__action_links',
553
-            $action_links,
554
-            $item
555
-        );
556
-        return $this->_action_string(
557
-            implode("\n\t", $action_links),
558
-            $item,
559
-            'div'
560
-        );
561
-    }
21
+	/**
22
+	 * @var EE_Datetime
23
+	 */
24
+	private $_dtt;
25
+
26
+
27
+
28
+	/**
29
+	 * Initial setup of data properties for the list table.
30
+	 */
31
+	protected function _setup_data()
32
+	{
33
+		$this->_data = $this->_admin_page->get_events($this->_per_page, $this->_current_page);
34
+		$this->_all_data_count = $this->_admin_page->get_events(0, 0, true);
35
+	}
36
+
37
+
38
+
39
+	/**
40
+	 * Set up of additional properties for the list table.
41
+	 */
42
+	protected function _set_properties()
43
+	{
44
+		$this->_wp_list_args = array(
45
+			'singular' => esc_html__('event', 'event_espresso'),
46
+			'plural'   => esc_html__('events', 'event_espresso'),
47
+			'ajax'     => true, //for now
48
+			'screen'   => $this->_admin_page->get_current_screen()->id,
49
+		);
50
+		$this->_columns = array(
51
+			'cb'              => '<input type="checkbox" />',
52
+			'id'              => esc_html__('ID', 'event_espresso'),
53
+			'name'            => esc_html__('Name', 'event_espresso'),
54
+			'author'          => esc_html__('Author', 'event_espresso'),
55
+			'venue'           => esc_html__('Venue', 'event_espresso'),
56
+			'start_date_time' => esc_html__('Event Start', 'event_espresso'),
57
+			'reg_begins'      => esc_html__('On Sale', 'event_espresso'),
58
+			'attendees'       => '<span class="dashicons dashicons-groups ee-icon-color-ee-green ee-icon-size-20">'
59
+								 . '</span>',
60
+			//'tkts_sold' => esc_html__('Tickets Sold', 'event_espresso'),
61
+			'actions'         => esc_html__('Actions', 'event_espresso'),
62
+		);
63
+		$this->_sortable_columns = array(
64
+			'id'              => array('EVT_ID' => true),
65
+			'name'            => array('EVT_name' => false),
66
+			'author'          => array('EVT_wp_user' => false),
67
+			'venue'           => array('Venue.VNU_name' => false),
68
+			'start_date_time' => array('Datetime.DTT_EVT_start' => false),
69
+			'reg_begins'      => array('Datetime.Ticket.TKT_start_date' => false),
70
+		);
71
+		$this->_primary_column = 'id';
72
+		$this->_hidden_columns = array('author');
73
+	}
74
+
75
+
76
+
77
+	/**
78
+	 * @return array
79
+	 */
80
+	protected function _get_table_filters()
81
+	{
82
+		return array(); //no filters with decaf
83
+	}
84
+
85
+
86
+
87
+	/**
88
+	 * Setup of views properties.
89
+	 *
90
+	 * @throws InvalidDataTypeException
91
+	 * @throws InvalidInterfaceException
92
+	 * @throws InvalidArgumentException
93
+	 */
94
+	protected function _add_view_counts()
95
+	{
96
+		$this->_views['all']['count'] = $this->_admin_page->total_events();
97
+		$this->_views['draft']['count'] = $this->_admin_page->total_events_draft();
98
+		if (EE_Registry::instance()->CAP->current_user_can(
99
+			'ee_delete_events',
100
+			'espresso_events_trash_events'
101
+		)) {
102
+			$this->_views['trash']['count'] = $this->_admin_page->total_trashed_events();
103
+		}
104
+	}
105
+
106
+
107
+
108
+	/**
109
+	 * @param EE_Event $item
110
+	 * @return string
111
+	 * @throws EE_Error
112
+	 */
113
+	protected function _get_row_class($item)
114
+	{
115
+		$class = parent::_get_row_class($item);
116
+		//add status class
117
+		$class .= $item instanceof EE_Event
118
+			? ' ee-status-strip event-status-' . $item->get_active_status()
119
+			: '';
120
+		if ($this->_has_checkbox_column) {
121
+			$class .= ' has-checkbox-column';
122
+		}
123
+		return $class;
124
+	}
125
+
126
+
127
+
128
+	/**
129
+	 * @param EE_Event $item
130
+	 * @return string
131
+	 * @throws EE_Error
132
+	 */
133
+	public function column_status(EE_Event $item)
134
+	{
135
+		return '<span class="ee-status-strip ee-status-strip-td event-status-'
136
+			   . $item->get_active_status()
137
+			   . '"></span>';
138
+	}
139
+
140
+
141
+
142
+	/**
143
+	 * @param  EE_Event $item
144
+	 * @return string
145
+	 * @throws EE_Error
146
+	 */
147
+	public function column_cb($item)
148
+	{
149
+		if (! $item instanceof EE_Event) {
150
+			return '';
151
+		}
152
+		$this->_dtt = $item->primary_datetime(); //set this for use in other columns
153
+		//does event have any attached registrations?
154
+		$regs = $item->count_related('Registration');
155
+		return $regs > 0 && $this->_view === 'trash'
156
+			? '<span class="ee-lock-icon"></span>'
157
+			: sprintf(
158
+				'<input type="checkbox" name="EVT_IDs[]" value="%s" />',
159
+				$item->ID()
160
+			);
161
+	}
162
+
163
+
164
+
165
+	/**
166
+	 * @param EE_Event $item
167
+	 * @return mixed|string
168
+	 * @throws EE_Error
169
+	 */
170
+	public function column_id(EE_Event $item)
171
+	{
172
+		$content = $item->ID();
173
+		$content .= '  <span class="show-on-mobile-view-only">' . $item->name() . '</span>';
174
+		return $content;
175
+	}
176
+
177
+
178
+
179
+	/**
180
+	 * @param EE_Event $item
181
+	 * @return string
182
+	 * @throws EE_Error
183
+	 * @throws InvalidArgumentException
184
+	 * @throws InvalidDataTypeException
185
+	 * @throws InvalidInterfaceException
186
+	 */
187
+	public function column_name(EE_Event $item)
188
+	{
189
+		$edit_query_args = array(
190
+			'action' => 'edit',
191
+			'post'   => $item->ID(),
192
+		);
193
+		$edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
194
+		$actions = $this->_column_name_action_setup($item);
195
+		$status = ''; //$item->status() !== 'publish' ? ' (' . $item->status() . ')' : '';
196
+		$content = '<strong><a class="row-title" href="'
197
+				   . $edit_link . '">'
198
+				   . $item->name()
199
+				   . '</a></strong>'
200
+				   . $status;
201
+		$content .= '<br><span class="ee-status-text-small">'
202
+					. EEH_Template::pretty_status(
203
+				$item->get_active_status(),
204
+				false,
205
+				'sentence'
206
+			)
207
+					. '</span>';
208
+		$content .= $this->row_actions($actions);
209
+		return $content;
210
+	}
211
+
212
+
213
+
214
+	/**
215
+	 * Just a method for setting up the actions for the name column
216
+	 *
217
+	 * @param EE_Event $item
218
+	 * @return array array of actions
219
+	 * @throws EE_Error
220
+	 * @throws InvalidArgumentException
221
+	 * @throws InvalidDataTypeException
222
+	 * @throws InvalidInterfaceException
223
+	 */
224
+	protected function _column_name_action_setup(EE_Event $item)
225
+	{
226
+		//todo: remove when attendees is active
227
+		if (! defined('REG_ADMIN_URL')) {
228
+			define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
229
+		}
230
+		$actions = array();
231
+		$restore_event_link = '';
232
+		$delete_event_link = '';
233
+		$trash_event_link = '';
234
+		if (EE_Registry::instance()->CAP->current_user_can(
235
+			'ee_edit_event',
236
+			'espresso_events_edit',
237
+			$item->ID()
238
+		)) {
239
+			$edit_query_args = array(
240
+				'action' => 'edit',
241
+				'post'   => $item->ID(),
242
+			);
243
+			$edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
244
+			$actions['edit'] = '<a href="' . $edit_link . '"'
245
+							   . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
246
+							   . esc_html__('Edit', 'event_espresso')
247
+							   . '</a>';
248
+		}
249
+		if (
250
+			EE_Registry::instance()->CAP->current_user_can(
251
+				'ee_read_registrations',
252
+				'espresso_registrations_view_registration'
253
+			)
254
+			&& EE_Registry::instance()->CAP->current_user_can(
255
+				'ee_read_event',
256
+				'espresso_registrations_view_registration',
257
+				$item->ID()
258
+			)
259
+		) {
260
+			$attendees_query_args = array(
261
+				'action'   => 'default',
262
+				'event_id' => $item->ID(),
263
+			);
264
+			$attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
265
+			$actions['attendees'] = '<a href="' . $attendees_link . '"'
266
+									. ' title="' . esc_attr__('View Registrations', 'event_espresso') . '">'
267
+									. esc_html__('Registrations', 'event_espresso')
268
+									. '</a>';
269
+		}
270
+		if (
271
+		EE_Registry::instance()->CAP->current_user_can(
272
+			'ee_delete_event',
273
+			'espresso_events_trash_event',
274
+			$item->ID()
275
+		)
276
+		) {
277
+			$trash_event_query_args = array(
278
+				'action' => 'trash_event',
279
+				'EVT_ID' => $item->ID(),
280
+			);
281
+			$trash_event_link = EE_Admin_Page::add_query_args_and_nonce(
282
+				$trash_event_query_args,
283
+				EVENTS_ADMIN_URL
284
+			);
285
+		}
286
+		if (
287
+		EE_Registry::instance()->CAP->current_user_can(
288
+			'ee_delete_event',
289
+			'espresso_events_restore_event',
290
+			$item->ID()
291
+		)
292
+		) {
293
+			$restore_event_query_args = array(
294
+				'action' => 'restore_event',
295
+				'EVT_ID' => $item->ID(),
296
+			);
297
+			$restore_event_link = EE_Admin_Page::add_query_args_and_nonce(
298
+				$restore_event_query_args,
299
+				EVENTS_ADMIN_URL
300
+			);
301
+		}
302
+		if (
303
+		EE_Registry::instance()->CAP->current_user_can(
304
+			'ee_delete_event',
305
+			'espresso_events_delete_event',
306
+			$item->ID()
307
+		)
308
+		) {
309
+			$delete_event_query_args = array(
310
+				'action' => 'delete_event',
311
+				'EVT_ID' => $item->ID(),
312
+			);
313
+			$delete_event_link = EE_Admin_Page::add_query_args_and_nonce(
314
+				$delete_event_query_args,
315
+				EVENTS_ADMIN_URL
316
+			);
317
+		}
318
+		$view_link = get_permalink($item->ID());
319
+		$actions['view'] = '<a href="' . $view_link . '"'
320
+						   . ' title="' . esc_attr__('View Event', 'event_espresso') . '">'
321
+						   . esc_html__('View', 'event_espresso')
322
+						   . '</a>';
323
+		if ($item->get('status') === 'trash') {
324
+			if (EE_Registry::instance()->CAP->current_user_can(
325
+				'ee_delete_event',
326
+				'espresso_events_restore_event',
327
+				$item->ID()
328
+			)) {
329
+				$actions['restore_from_trash'] = '<a href="' . $restore_event_link . '"'
330
+												 . ' title="' . esc_attr__('Restore from Trash', 'event_espresso')
331
+												 . '">'
332
+												 . esc_html__('Restore from Trash', 'event_espresso')
333
+												 . '</a>';
334
+			}
335
+			if (
336
+				$item->count_related('Registration') === 0
337
+				&& EE_Registry::instance()->CAP->current_user_can(
338
+					'ee_delete_event',
339
+					'espresso_events_delete_event',
340
+					$item->ID()
341
+				)
342
+			) {
343
+				$actions['delete'] = '<a href="' . $delete_event_link . '"'
344
+									 . ' title="' . esc_attr__('Delete Permanently', 'event_espresso') . '">'
345
+									 . esc_html__('Delete Permanently', 'event_espresso')
346
+									 . '</a>';
347
+			}
348
+		} else {
349
+			if (
350
+				EE_Registry::instance()->CAP->current_user_can(
351
+					'ee_delete_event',
352
+					'espresso_events_trash_event',
353
+					$item->ID()
354
+				)
355
+			) {
356
+				$actions['move to trash'] = '<a href="' . $trash_event_link . '"'
357
+											. ' title="' . esc_attr__('Trash Event', 'event_espresso') . '">'
358
+											. esc_html__('Trash', 'event_espresso')
359
+											. '</a>';
360
+			}
361
+		}
362
+		return $actions;
363
+	}
364
+
365
+
366
+
367
+	/**
368
+	 * @param EE_Event $item
369
+	 * @return string
370
+	 * @throws EE_Error
371
+	 */
372
+	public function column_author(EE_Event $item)
373
+	{
374
+		//user author info
375
+		$event_author = get_userdata($item->wp_user());
376
+		$gravatar = get_avatar($item->wp_user(), '15');
377
+		//filter link
378
+		$query_args = array(
379
+			'action'      => 'default',
380
+			'EVT_wp_user' => $item->wp_user(),
381
+		);
382
+		$filter_url = EE_Admin_Page::add_query_args_and_nonce($query_args, EVENTS_ADMIN_URL);
383
+		return $gravatar . '  <a href="' . $filter_url . '"'
384
+			   . ' title="' . esc_attr__('Click to filter events by this author.', 'event_espresso') . '">'
385
+			   . $event_author->display_name
386
+			   . '</a>';
387
+	}
388
+
389
+
390
+
391
+	/**
392
+	 * @param EE_Event $item
393
+	 * @return string
394
+	 * @throws EE_Error
395
+	 */
396
+	public function column_venue(EE_Event $item)
397
+	{
398
+		$venue = $item->get_first_related('Venue');
399
+		return ! empty($venue)
400
+			? $venue->name()
401
+			: '';
402
+	}
403
+
404
+
405
+
406
+	/**
407
+	 * @param EE_Event $item
408
+	 * @throws EE_Error
409
+	 */
410
+	public function column_start_date_time(EE_Event $item)
411
+	{
412
+		echo ! empty($this->_dtt)
413
+			? $this->_dtt->get_i18n_datetime('DTT_EVT_start')
414
+			: esc_html__('No Date was saved for this Event', 'event_espresso');
415
+		//display in user's timezone?
416
+		echo ! empty($this->_dtt)
417
+			? $this->_dtt->display_in_my_timezone(
418
+				'DTT_EVT_start',
419
+				'get_i18n_datetime',
420
+				'',
421
+				'My Timezone: '
422
+			)
423
+			: '';
424
+	}
425
+
426
+
427
+
428
+	/**
429
+	 * @param EE_Event $item
430
+	 * @throws EE_Error
431
+	 */
432
+	public function column_reg_begins(EE_Event $item)
433
+	{
434
+		$reg_start = $item->get_ticket_with_earliest_start_time();
435
+		echo ! empty($reg_start)
436
+			? $reg_start->get_i18n_datetime('TKT_start_date')
437
+			: esc_html__('No Tickets have been setup for this Event', 'event_espresso');
438
+		//display in user's timezone?
439
+		echo ! empty($reg_start)
440
+			? $reg_start->display_in_my_timezone(
441
+				'TKT_start_date',
442
+				'get_i18n_datetime',
443
+				'',
444
+				'My Timezone: '
445
+			)
446
+			: '';
447
+	}
448
+
449
+
450
+
451
+	/**
452
+	 * @param EE_Event $item
453
+	 * @return int|string
454
+	 * @throws EE_Error
455
+	 * @throws InvalidArgumentException
456
+	 * @throws InvalidDataTypeException
457
+	 * @throws InvalidInterfaceException
458
+	 */
459
+	public function column_attendees(EE_Event $item)
460
+	{
461
+		$attendees_query_args = array(
462
+			'action'   => 'default',
463
+			'event_id' => $item->ID(),
464
+		);
465
+		$attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
466
+		$registered_attendees = EEM_Registration::instance()->get_event_registration_count($item->ID());
467
+		return EE_Registry::instance()->CAP->current_user_can(
468
+			'ee_read_event',
469
+			'espresso_registrations_view_registration',
470
+			$item->ID()
471
+		)
472
+			   && EE_Registry::instance()->CAP->current_user_can(
473
+			'ee_read_registrations',
474
+			'espresso_registrations_view_registration'
475
+		)
476
+			? '<a href="' . $attendees_link . '">' . $registered_attendees . '</a>'
477
+			: $registered_attendees;
478
+	}
479
+
480
+
481
+
482
+	/**
483
+	 * @param EE_Event $item
484
+	 * @return float
485
+	 * @throws EE_Error
486
+	 * @throws InvalidArgumentException
487
+	 * @throws InvalidDataTypeException
488
+	 * @throws InvalidInterfaceException
489
+	 */
490
+	public function column_tkts_sold(EE_Event $item)
491
+	{
492
+		return EEM_Ticket::instance()->sum(array(array('Datetime.EVT_ID' => $item->ID())), 'TKT_sold');
493
+	}
494
+
495
+
496
+
497
+	/**
498
+	 * @param EE_Event $item
499
+	 * @return string
500
+	 * @throws EE_Error
501
+	 * @throws InvalidArgumentException
502
+	 * @throws InvalidDataTypeException
503
+	 * @throws InvalidInterfaceException
504
+	 */
505
+	public function column_actions(EE_Event $item)
506
+	{
507
+		//todo: remove when attendees is active
508
+		if (! defined('REG_ADMIN_URL')) {
509
+			define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
510
+		}
511
+		$action_links = array();
512
+		$view_link = get_permalink($item->ID());
513
+		$action_links[] = '<a href="' . $view_link . '"'
514
+						 . ' title="' . esc_attr__('View Event', 'event_espresso') . '" target="_blank">';
515
+		$action_links[] = '<div class="dashicons dashicons-search"></div></a>';
516
+		if (EE_Registry::instance()->CAP->current_user_can(
517
+			'ee_edit_event',
518
+			'espresso_events_edit',
519
+			$item->ID()
520
+		)) {
521
+			$edit_query_args = array(
522
+				'action' => 'edit',
523
+				'post'   => $item->ID(),
524
+			);
525
+			$edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
526
+			$action_links[] = '<a href="' . $edit_link . '"'
527
+							 . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
528
+							 . '<div class="ee-icon ee-icon-calendar-edit"></div>'
529
+							 . '</a>';
530
+		}
531
+		if (
532
+			EE_Registry::instance()->CAP->current_user_can(
533
+				'ee_read_registrations',
534
+				'espresso_registrations_view_registration'
535
+			) && EE_Registry::instance()->CAP->current_user_can(
536
+				'ee_read_event',
537
+				'espresso_registrations_view_registration',
538
+				$item->ID()
539
+			)
540
+		) {
541
+			$attendees_query_args = array(
542
+				'action'   => 'default',
543
+				'event_id' => $item->ID(),
544
+			);
545
+			$attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
546
+			$action_links[] = '<a href="' . $attendees_link . '"'
547
+							 . ' title="' . esc_attr__('View Registrants', 'event_espresso') . '">'
548
+							 . '<div class="dashicons dashicons-groups"></div>'
549
+							 . '</a>';
550
+		}
551
+		$action_links = apply_filters(
552
+			'FHEE__Events_Admin_List_Table__column_actions__action_links',
553
+			$action_links,
554
+			$item
555
+		);
556
+		return $this->_action_string(
557
+			implode("\n\t", $action_links),
558
+			$item,
559
+			'div'
560
+		);
561
+	}
562 562
 }
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
         $class = parent::_get_row_class($item);
116 116
         //add status class
117 117
         $class .= $item instanceof EE_Event
118
-            ? ' ee-status-strip event-status-' . $item->get_active_status()
118
+            ? ' ee-status-strip event-status-'.$item->get_active_status()
119 119
             : '';
120 120
         if ($this->_has_checkbox_column) {
121 121
             $class .= ' has-checkbox-column';
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
      */
147 147
     public function column_cb($item)
148 148
     {
149
-        if (! $item instanceof EE_Event) {
149
+        if ( ! $item instanceof EE_Event) {
150 150
             return '';
151 151
         }
152 152
         $this->_dtt = $item->primary_datetime(); //set this for use in other columns
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
     public function column_id(EE_Event $item)
171 171
     {
172 172
         $content = $item->ID();
173
-        $content .= '  <span class="show-on-mobile-view-only">' . $item->name() . '</span>';
173
+        $content .= '  <span class="show-on-mobile-view-only">'.$item->name().'</span>';
174 174
         return $content;
175 175
     }
176 176
 
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
         $actions = $this->_column_name_action_setup($item);
195 195
         $status = ''; //$item->status() !== 'publish' ? ' (' . $item->status() . ')' : '';
196 196
         $content = '<strong><a class="row-title" href="'
197
-                   . $edit_link . '">'
197
+                   . $edit_link.'">'
198 198
                    . $item->name()
199 199
                    . '</a></strong>'
200 200
                    . $status;
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
     protected function _column_name_action_setup(EE_Event $item)
225 225
     {
226 226
         //todo: remove when attendees is active
227
-        if (! defined('REG_ADMIN_URL')) {
227
+        if ( ! defined('REG_ADMIN_URL')) {
228 228
             define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
229 229
         }
230 230
         $actions = array();
@@ -241,8 +241,8 @@  discard block
 block discarded – undo
241 241
                 'post'   => $item->ID(),
242 242
             );
243 243
             $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
244
-            $actions['edit'] = '<a href="' . $edit_link . '"'
245
-                               . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
244
+            $actions['edit'] = '<a href="'.$edit_link.'"'
245
+                               . ' title="'.esc_attr__('Edit Event', 'event_espresso').'">'
246 246
                                . esc_html__('Edit', 'event_espresso')
247 247
                                . '</a>';
248 248
         }
@@ -262,8 +262,8 @@  discard block
 block discarded – undo
262 262
                 'event_id' => $item->ID(),
263 263
             );
264 264
             $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
265
-            $actions['attendees'] = '<a href="' . $attendees_link . '"'
266
-                                    . ' title="' . esc_attr__('View Registrations', 'event_espresso') . '">'
265
+            $actions['attendees'] = '<a href="'.$attendees_link.'"'
266
+                                    . ' title="'.esc_attr__('View Registrations', 'event_espresso').'">'
267 267
                                     . esc_html__('Registrations', 'event_espresso')
268 268
                                     . '</a>';
269 269
         }
@@ -316,8 +316,8 @@  discard block
 block discarded – undo
316 316
             );
317 317
         }
318 318
         $view_link = get_permalink($item->ID());
319
-        $actions['view'] = '<a href="' . $view_link . '"'
320
-                           . ' title="' . esc_attr__('View Event', 'event_espresso') . '">'
319
+        $actions['view'] = '<a href="'.$view_link.'"'
320
+                           . ' title="'.esc_attr__('View Event', 'event_espresso').'">'
321 321
                            . esc_html__('View', 'event_espresso')
322 322
                            . '</a>';
323 323
         if ($item->get('status') === 'trash') {
@@ -326,8 +326,8 @@  discard block
 block discarded – undo
326 326
                 'espresso_events_restore_event',
327 327
                 $item->ID()
328 328
             )) {
329
-                $actions['restore_from_trash'] = '<a href="' . $restore_event_link . '"'
330
-                                                 . ' title="' . esc_attr__('Restore from Trash', 'event_espresso')
329
+                $actions['restore_from_trash'] = '<a href="'.$restore_event_link.'"'
330
+                                                 . ' title="'.esc_attr__('Restore from Trash', 'event_espresso')
331 331
                                                  . '">'
332 332
                                                  . esc_html__('Restore from Trash', 'event_espresso')
333 333
                                                  . '</a>';
@@ -340,8 +340,8 @@  discard block
 block discarded – undo
340 340
                     $item->ID()
341 341
                 )
342 342
             ) {
343
-                $actions['delete'] = '<a href="' . $delete_event_link . '"'
344
-                                     . ' title="' . esc_attr__('Delete Permanently', 'event_espresso') . '">'
343
+                $actions['delete'] = '<a href="'.$delete_event_link.'"'
344
+                                     . ' title="'.esc_attr__('Delete Permanently', 'event_espresso').'">'
345 345
                                      . esc_html__('Delete Permanently', 'event_espresso')
346 346
                                      . '</a>';
347 347
             }
@@ -353,8 +353,8 @@  discard block
 block discarded – undo
353 353
                     $item->ID()
354 354
                 )
355 355
             ) {
356
-                $actions['move to trash'] = '<a href="' . $trash_event_link . '"'
357
-                                            . ' title="' . esc_attr__('Trash Event', 'event_espresso') . '">'
356
+                $actions['move to trash'] = '<a href="'.$trash_event_link.'"'
357
+                                            . ' title="'.esc_attr__('Trash Event', 'event_espresso').'">'
358 358
                                             . esc_html__('Trash', 'event_espresso')
359 359
                                             . '</a>';
360 360
             }
@@ -380,8 +380,8 @@  discard block
 block discarded – undo
380 380
             'EVT_wp_user' => $item->wp_user(),
381 381
         );
382 382
         $filter_url = EE_Admin_Page::add_query_args_and_nonce($query_args, EVENTS_ADMIN_URL);
383
-        return $gravatar . '  <a href="' . $filter_url . '"'
384
-               . ' title="' . esc_attr__('Click to filter events by this author.', 'event_espresso') . '">'
383
+        return $gravatar.'  <a href="'.$filter_url.'"'
384
+               . ' title="'.esc_attr__('Click to filter events by this author.', 'event_espresso').'">'
385 385
                . $event_author->display_name
386 386
                . '</a>';
387 387
     }
@@ -473,7 +473,7 @@  discard block
 block discarded – undo
473 473
             'ee_read_registrations',
474 474
             'espresso_registrations_view_registration'
475 475
         )
476
-            ? '<a href="' . $attendees_link . '">' . $registered_attendees . '</a>'
476
+            ? '<a href="'.$attendees_link.'">'.$registered_attendees.'</a>'
477 477
             : $registered_attendees;
478 478
     }
479 479
 
@@ -505,13 +505,13 @@  discard block
 block discarded – undo
505 505
     public function column_actions(EE_Event $item)
506 506
     {
507 507
         //todo: remove when attendees is active
508
-        if (! defined('REG_ADMIN_URL')) {
508
+        if ( ! defined('REG_ADMIN_URL')) {
509 509
             define('REG_ADMIN_URL', EVENTS_ADMIN_URL);
510 510
         }
511 511
         $action_links = array();
512 512
         $view_link = get_permalink($item->ID());
513
-        $action_links[] = '<a href="' . $view_link . '"'
514
-                         . ' title="' . esc_attr__('View Event', 'event_espresso') . '" target="_blank">';
513
+        $action_links[] = '<a href="'.$view_link.'"'
514
+                         . ' title="'.esc_attr__('View Event', 'event_espresso').'" target="_blank">';
515 515
         $action_links[] = '<div class="dashicons dashicons-search"></div></a>';
516 516
         if (EE_Registry::instance()->CAP->current_user_can(
517 517
             'ee_edit_event',
@@ -523,8 +523,8 @@  discard block
 block discarded – undo
523 523
                 'post'   => $item->ID(),
524 524
             );
525 525
             $edit_link = EE_Admin_Page::add_query_args_and_nonce($edit_query_args, EVENTS_ADMIN_URL);
526
-            $action_links[] = '<a href="' . $edit_link . '"'
527
-                             . ' title="' . esc_attr__('Edit Event', 'event_espresso') . '">'
526
+            $action_links[] = '<a href="'.$edit_link.'"'
527
+                             . ' title="'.esc_attr__('Edit Event', 'event_espresso').'">'
528 528
                              . '<div class="ee-icon ee-icon-calendar-edit"></div>'
529 529
                              . '</a>';
530 530
         }
@@ -543,8 +543,8 @@  discard block
 block discarded – undo
543 543
                 'event_id' => $item->ID(),
544 544
             );
545 545
             $attendees_link = EE_Admin_Page::add_query_args_and_nonce($attendees_query_args, REG_ADMIN_URL);
546
-            $action_links[] = '<a href="' . $attendees_link . '"'
547
-                             . ' title="' . esc_attr__('View Registrants', 'event_espresso') . '">'
546
+            $action_links[] = '<a href="'.$attendees_link.'"'
547
+                             . ' title="'.esc_attr__('View Registrants', 'event_espresso').'">'
548 548
                              . '<div class="dashicons dashicons-groups"></div>'
549 549
                              . '</a>';
550 550
         }
Please login to merge, or discard this patch.
core/services/loaders/CachingLoader.php 2 patches
Indentation   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -21,146 +21,146 @@
 block discarded – undo
21 21
 class CachingLoader extends LoaderDecorator
22 22
 {
23 23
 
24
-    /**
25
-     * @var CollectionInterface $cache
26
-     */
27
-    protected $cache;
28
-
29
-    /**
30
-     * @var string $identifier
31
-     */
32
-    protected $identifier;
33
-
34
-
35
-
36
-    /**
37
-     * CachingLoader constructor.
38
-     *
39
-     * @param LoaderDecoratorInterface $loader
40
-     * @param CollectionInterface      $cache
41
-     * @param string                   $identifier
42
-     * @throws InvalidDataTypeException
43
-     */
44
-    public function __construct(LoaderDecoratorInterface $loader, CollectionInterface $cache, $identifier = '')
45
-    {
46
-        parent::__construct($loader);
47
-        $this->cache = $cache;
48
-        $this->setIdentifier($identifier);
49
-        if ($this->identifier !== '') {
50
-            // to only clear this cache, and assuming an identifier has been set, simply do the following:
51
-            // do_action('AHEE__EventEspresso\core\services\loaders\CachingLoader__resetCache__IDENTIFIER');
52
-            // where "IDENTIFIER" = the string that was set during construction
53
-            add_action(
54
-                "AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__{$identifier}",
55
-                array($this, 'reset')
56
-            );
57
-        }
58
-        // to clear ALL caches, simply do the following:
59
-        // do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache');
60
-        add_action(
61
-            'AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache',
62
-            array($this, 'reset')
63
-        );
64
-    }
65
-
66
-
67
-
68
-    /**
69
-     * @return string
70
-     */
71
-    public function identifier()
72
-    {
73
-        return $this->identifier;
74
-    }
75
-
76
-
77
-
78
-    /**
79
-     * @param string $identifier
80
-     * @throws InvalidDataTypeException
81
-     */
82
-    private function setIdentifier($identifier)
83
-    {
84
-        if ( ! is_string($identifier)) {
85
-            throw new InvalidDataTypeException('$identifier', $identifier, 'string');
86
-        }
87
-        $this->identifier = $identifier;
88
-    }
89
-
90
-
91
-
92
-    /**
93
-     * @param string $fqcn
94
-     * @param array  $arguments
95
-     * @param bool   $shared
96
-     * @return mixed
97
-     */
98
-    public function load($fqcn, $arguments = array(), $shared = true)
99
-    {
100
-        $fqcn = ltrim($fqcn, '\\');
101
-        // caching can be turned off via the following code:
102
-        // add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
103
-        if(
104
-            apply_filters(
105
-                'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
106
-                false,
107
-                $this
108
-            )
109
-        ){
110
-            // even though $shared might be true, caching should be bypassed for whatever reason,
111
-            // so we don't want the core loader to cache anything, therefore caching is turned off
112
-            return $this->loader->load($fqcn, $arguments, false);
113
-        }
114
-        $identifier = md5($fqcn . $this->getIdentifierForArgument($arguments));
115
-        if($this->cache->has($identifier)){
116
-            return $this->cache->get($identifier);
117
-        }
118
-        $object = $this->loader->load($fqcn, $arguments, $shared);
119
-        if($object instanceof $fqcn){
120
-            $this->cache->add($object, $identifier);
121
-        }
122
-        return $object;
123
-    }
124
-
125
-
126
-
127
-    /**
128
-     * empties cache and calls reset() on loader if method exists
129
-     */
130
-    public function reset()
131
-    {
132
-        $this->cache->trashAndDetachAll();
133
-        $this->loader->reset();
134
-    }
135
-
136
-
137
-
138
-    /**
139
-     * build a string representation of a class' arguments
140
-     * (mostly because Closures can't be serialized)
141
-     *
142
-     * @param array $arguments
143
-     * @return string
144
-     */
145
-    private function getIdentifierForArgument(array $arguments)
146
-    {
147
-        $identifier = '';
148
-        foreach ($arguments as $argument) {
149
-            switch (true) {
150
-                case is_object($argument) :
151
-                case $argument instanceof Closure :
152
-                    $identifier .= spl_object_hash($argument);
153
-                    break;
154
-                case is_array($argument) :
155
-                    $identifier .= $this->getIdentifierForArgument($argument);
156
-                    break;
157
-                default :
158
-                    $identifier .= $argument;
159
-                    break;
160
-            }
161
-        }
162
-        return $identifier;
163
-    }
24
+	/**
25
+	 * @var CollectionInterface $cache
26
+	 */
27
+	protected $cache;
28
+
29
+	/**
30
+	 * @var string $identifier
31
+	 */
32
+	protected $identifier;
33
+
34
+
35
+
36
+	/**
37
+	 * CachingLoader constructor.
38
+	 *
39
+	 * @param LoaderDecoratorInterface $loader
40
+	 * @param CollectionInterface      $cache
41
+	 * @param string                   $identifier
42
+	 * @throws InvalidDataTypeException
43
+	 */
44
+	public function __construct(LoaderDecoratorInterface $loader, CollectionInterface $cache, $identifier = '')
45
+	{
46
+		parent::__construct($loader);
47
+		$this->cache = $cache;
48
+		$this->setIdentifier($identifier);
49
+		if ($this->identifier !== '') {
50
+			// to only clear this cache, and assuming an identifier has been set, simply do the following:
51
+			// do_action('AHEE__EventEspresso\core\services\loaders\CachingLoader__resetCache__IDENTIFIER');
52
+			// where "IDENTIFIER" = the string that was set during construction
53
+			add_action(
54
+				"AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__{$identifier}",
55
+				array($this, 'reset')
56
+			);
57
+		}
58
+		// to clear ALL caches, simply do the following:
59
+		// do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache');
60
+		add_action(
61
+			'AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache',
62
+			array($this, 'reset')
63
+		);
64
+	}
65
+
66
+
67
+
68
+	/**
69
+	 * @return string
70
+	 */
71
+	public function identifier()
72
+	{
73
+		return $this->identifier;
74
+	}
75
+
76
+
77
+
78
+	/**
79
+	 * @param string $identifier
80
+	 * @throws InvalidDataTypeException
81
+	 */
82
+	private function setIdentifier($identifier)
83
+	{
84
+		if ( ! is_string($identifier)) {
85
+			throw new InvalidDataTypeException('$identifier', $identifier, 'string');
86
+		}
87
+		$this->identifier = $identifier;
88
+	}
89
+
90
+
91
+
92
+	/**
93
+	 * @param string $fqcn
94
+	 * @param array  $arguments
95
+	 * @param bool   $shared
96
+	 * @return mixed
97
+	 */
98
+	public function load($fqcn, $arguments = array(), $shared = true)
99
+	{
100
+		$fqcn = ltrim($fqcn, '\\');
101
+		// caching can be turned off via the following code:
102
+		// add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
103
+		if(
104
+			apply_filters(
105
+				'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
106
+				false,
107
+				$this
108
+			)
109
+		){
110
+			// even though $shared might be true, caching should be bypassed for whatever reason,
111
+			// so we don't want the core loader to cache anything, therefore caching is turned off
112
+			return $this->loader->load($fqcn, $arguments, false);
113
+		}
114
+		$identifier = md5($fqcn . $this->getIdentifierForArgument($arguments));
115
+		if($this->cache->has($identifier)){
116
+			return $this->cache->get($identifier);
117
+		}
118
+		$object = $this->loader->load($fqcn, $arguments, $shared);
119
+		if($object instanceof $fqcn){
120
+			$this->cache->add($object, $identifier);
121
+		}
122
+		return $object;
123
+	}
124
+
125
+
126
+
127
+	/**
128
+	 * empties cache and calls reset() on loader if method exists
129
+	 */
130
+	public function reset()
131
+	{
132
+		$this->cache->trashAndDetachAll();
133
+		$this->loader->reset();
134
+	}
135
+
136
+
137
+
138
+	/**
139
+	 * build a string representation of a class' arguments
140
+	 * (mostly because Closures can't be serialized)
141
+	 *
142
+	 * @param array $arguments
143
+	 * @return string
144
+	 */
145
+	private function getIdentifierForArgument(array $arguments)
146
+	{
147
+		$identifier = '';
148
+		foreach ($arguments as $argument) {
149
+			switch (true) {
150
+				case is_object($argument) :
151
+				case $argument instanceof Closure :
152
+					$identifier .= spl_object_hash($argument);
153
+					break;
154
+				case is_array($argument) :
155
+					$identifier .= $this->getIdentifierForArgument($argument);
156
+					break;
157
+				default :
158
+					$identifier .= $argument;
159
+					break;
160
+			}
161
+		}
162
+		return $identifier;
163
+	}
164 164
 
165 165
 
166 166
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -100,23 +100,23 @@
 block discarded – undo
100 100
         $fqcn = ltrim($fqcn, '\\');
101 101
         // caching can be turned off via the following code:
102 102
         // add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
103
-        if(
103
+        if (
104 104
             apply_filters(
105 105
                 'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
106 106
                 false,
107 107
                 $this
108 108
             )
109
-        ){
109
+        ) {
110 110
             // even though $shared might be true, caching should be bypassed for whatever reason,
111 111
             // so we don't want the core loader to cache anything, therefore caching is turned off
112 112
             return $this->loader->load($fqcn, $arguments, false);
113 113
         }
114
-        $identifier = md5($fqcn . $this->getIdentifierForArgument($arguments));
115
-        if($this->cache->has($identifier)){
114
+        $identifier = md5($fqcn.$this->getIdentifierForArgument($arguments));
115
+        if ($this->cache->has($identifier)) {
116 116
             return $this->cache->get($identifier);
117 117
         }
118 118
         $object = $this->loader->load($fqcn, $arguments, $shared);
119
-        if($object instanceof $fqcn){
119
+        if ($object instanceof $fqcn) {
120 120
             $this->cache->add($object, $identifier);
121 121
         }
122 122
         return $object;
Please login to merge, or discard this patch.
core/libraries/payment_methods/EEI_Payment_Method_Interfaces.php 2 patches
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -1,7 +1,5 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-use EventEspresso\core\services\orm\ModelFieldFactory;
4
-
5 3
 if ( ! defined('EVENT_ESPRESSO_VERSION')) { exit('No direct script access allowed'); }
6 4
 
7 5
 /**
Please login to merge, or discard this patch.
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -99,34 +99,34 @@  discard block
 block discarded – undo
99 99
 	 */
100 100
 	public function set_extra_accntng($extra_accounting_info);
101 101
 
102
-    /**
103
-     * Gets the first event for this payment (it's possible that it could be for multiple)
104
-     *
105
-     * @param EE_Payment $payment
106
-     * @return EE_Event|null
107
-     */
108
-    public function get_first_event();
109
-
110
-    /**
111
-     * Gets the name of the first event for which is being paid
112
-     *
113
-     * @param EE_Payment $payment
114
-     * @return string
115
-     */
116
-    public function get_first_event_name();
117
-
118
-    /**
119
-     * Returns the payment's transaction's primary registration
120
-     *
121
-     * @return EE_Registration|null
122
-     */
123
-    public function get_primary_registration();
124
-
125
-    /**
126
-     * Gets the payment's transaction's primary registration's attendee, or null
127
-     * @return EE_Attendee|null
128
-     */
129
-    public function get_primary_attendee();
102
+	/**
103
+	 * Gets the first event for this payment (it's possible that it could be for multiple)
104
+	 *
105
+	 * @param EE_Payment $payment
106
+	 * @return EE_Event|null
107
+	 */
108
+	public function get_first_event();
109
+
110
+	/**
111
+	 * Gets the name of the first event for which is being paid
112
+	 *
113
+	 * @param EE_Payment $payment
114
+	 * @return string
115
+	 */
116
+	public function get_first_event_name();
117
+
118
+	/**
119
+	 * Returns the payment's transaction's primary registration
120
+	 *
121
+	 * @return EE_Registration|null
122
+	 */
123
+	public function get_primary_registration();
124
+
125
+	/**
126
+	 * Gets the payment's transaction's primary registration's attendee, or null
127
+	 * @return EE_Attendee|null
128
+	 */
129
+	public function get_primary_attendee();
130 130
 }
131 131
 
132 132
 
@@ -164,12 +164,12 @@  discard block
 block discarded – undo
164 164
 
165 165
 
166 166
 
167
-    /**
168
-     * Function that returns an instance of this class.
169
-     *
170
-     * @param null              $timezone
171
-     * @return EEMI_Payment
172
-     */
167
+	/**
168
+	 * Function that returns an instance of this class.
169
+	 *
170
+	 * @param null              $timezone
171
+	 * @return EEMI_Payment
172
+	 */
173 173
 	public static function instance($timezone = null);
174 174
 
175 175
 	/**
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('ABSPATH')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /*
5 5
   Plugin Name:		Event Espresso
@@ -40,243 +40,243 @@  discard block
 block discarded – undo
40 40
  * @since            4.0
41 41
  */
42 42
 if (function_exists('espresso_version')) {
43
-    /**
44
-     *    espresso_duplicate_plugin_error
45
-     *    displays if more than one version of EE is activated at the same time
46
-     */
47
-    function espresso_duplicate_plugin_error()
48
-    {
49
-        ?>
43
+	/**
44
+	 *    espresso_duplicate_plugin_error
45
+	 *    displays if more than one version of EE is activated at the same time
46
+	 */
47
+	function espresso_duplicate_plugin_error()
48
+	{
49
+		?>
50 50
         <div class="error">
51 51
             <p>
52 52
                 <?php echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                ); ?>
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+				); ?>
56 56
             </p>
57 57
         </div>
58 58
         <?php
59
-        espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-    }
59
+		espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+	}
61 61
 
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
-    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
+	if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                            esc_html__(
79
-                                    'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                                    'event_espresso'
81
-                            ),
82
-                            EE_MIN_PHP_VER_REQUIRED,
83
-                            PHP_VERSION,
84
-                            '<br/>',
85
-                            '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+							esc_html__(
79
+									'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+									'event_espresso'
81
+							),
82
+							EE_MIN_PHP_VER_REQUIRED,
83
+							PHP_VERSION,
84
+							'<br/>',
85
+							'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        /**
97
-         * espresso_version
98
-         * Returns the plugin version
99
-         *
100
-         * @return string
101
-         */
102
-        function espresso_version()
103
-        {
104
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.46.rc.038');
105
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		/**
97
+		 * espresso_version
98
+		 * Returns the plugin version
99
+		 *
100
+		 * @return string
101
+		 */
102
+		function espresso_version()
103
+		{
104
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.46.rc.038');
105
+		}
106 106
 
107
-        // define versions
108
-        define('EVENT_ESPRESSO_VERSION', espresso_version());
109
-        define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
-        define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
-        define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
-        //used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
-        if ( ! defined('DS')) {
115
-            define('DS', '/');
116
-        }
117
-        if ( ! defined('PS')) {
118
-            define('PS', PATH_SEPARATOR);
119
-        }
120
-        if ( ! defined('SP')) {
121
-            define('SP', ' ');
122
-        }
123
-        if ( ! defined('EENL')) {
124
-            define('EENL', "\n");
125
-        }
126
-        define('EE_SUPPORT_EMAIL', '[email protected]');
127
-        // define the plugin directory and URL
128
-        define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
-        define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
-        define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
-        // main root folder paths
132
-        define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
-        define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
-        define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
-        define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
-        define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
-        define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
-        define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
-        define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
-        // core system paths
141
-        define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
-        define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
-        define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
-        define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
-        define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
-        define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
-        define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
-        define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
-        define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
-        define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
-        define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
-        define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
-        // gateways
154
-        define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
-        define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
-        // asset URL paths
157
-        define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
-        define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
-        define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
-        define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
-        define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
-        define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
-        // define upload paths
164
-        $uploads = wp_upload_dir();
165
-        // define the uploads directory and URL
166
-        define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
-        define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
-        // define the templates directory and URL
169
-        define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
-        define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
-        // define the gateway directory and URL
172
-        define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
-        define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
-        // languages folder/path
175
-        define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
-        define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
-        //check for dompdf fonts in uploads
178
-        if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
-            define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
-        }
181
-        //ajax constants
182
-        define(
183
-                'EE_FRONT_AJAX',
184
-                isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
-        );
186
-        define(
187
-                'EE_ADMIN_AJAX',
188
-                isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
-        );
190
-        //just a handy constant occasionally needed for finding values representing infinity in the DB
191
-        //you're better to use this than its straight value (currently -1) in case you ever
192
-        //want to change its default value! or find when -1 means infinity
193
-        define('EE_INF_IN_DB', -1);
194
-        define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
-        define('EE_DEBUG', false);
196
-        // for older WP versions
197
-        if ( ! defined('MONTH_IN_SECONDS')) {
198
-            define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
-        }
200
-        /**
201
-         *    espresso_plugin_activation
202
-         *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
-         */
204
-        function espresso_plugin_activation()
205
-        {
206
-            update_option('ee_espresso_activation', true);
207
-        }
107
+		// define versions
108
+		define('EVENT_ESPRESSO_VERSION', espresso_version());
109
+		define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
+		define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
+		define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
+		//used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
+		if ( ! defined('DS')) {
115
+			define('DS', '/');
116
+		}
117
+		if ( ! defined('PS')) {
118
+			define('PS', PATH_SEPARATOR);
119
+		}
120
+		if ( ! defined('SP')) {
121
+			define('SP', ' ');
122
+		}
123
+		if ( ! defined('EENL')) {
124
+			define('EENL', "\n");
125
+		}
126
+		define('EE_SUPPORT_EMAIL', '[email protected]');
127
+		// define the plugin directory and URL
128
+		define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
+		define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
+		define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
+		// main root folder paths
132
+		define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
+		define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
+		define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
+		define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
+		define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
+		define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
+		define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
+		define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
+		// core system paths
141
+		define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
+		define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
+		define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
+		define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
+		define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
+		define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
+		define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
+		define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
+		define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
+		define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
+		define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
+		define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
+		// gateways
154
+		define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
+		define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
+		// asset URL paths
157
+		define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
+		define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
+		define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
+		define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
+		define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
+		define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
+		// define upload paths
164
+		$uploads = wp_upload_dir();
165
+		// define the uploads directory and URL
166
+		define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
+		define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
+		// define the templates directory and URL
169
+		define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
+		define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
+		// define the gateway directory and URL
172
+		define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
+		define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
+		// languages folder/path
175
+		define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
+		define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
+		//check for dompdf fonts in uploads
178
+		if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
+			define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
+		}
181
+		//ajax constants
182
+		define(
183
+				'EE_FRONT_AJAX',
184
+				isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
+		);
186
+		define(
187
+				'EE_ADMIN_AJAX',
188
+				isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
+		);
190
+		//just a handy constant occasionally needed for finding values representing infinity in the DB
191
+		//you're better to use this than its straight value (currently -1) in case you ever
192
+		//want to change its default value! or find when -1 means infinity
193
+		define('EE_INF_IN_DB', -1);
194
+		define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
+		define('EE_DEBUG', false);
196
+		// for older WP versions
197
+		if ( ! defined('MONTH_IN_SECONDS')) {
198
+			define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
+		}
200
+		/**
201
+		 *    espresso_plugin_activation
202
+		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
+		 */
204
+		function espresso_plugin_activation()
205
+		{
206
+			update_option('ee_espresso_activation', true);
207
+		}
208 208
 
209
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
-        /**
211
-         *    espresso_load_error_handling
212
-         *    this function loads EE's class for handling exceptions and errors
213
-         */
214
-        function espresso_load_error_handling()
215
-        {
216
-            // load debugging tools
217
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
-                EEH_Debug_Tools::instance();
220
-            }
221
-            // load error handling
222
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
-                require_once(EE_CORE . 'EE_Error.core.php');
224
-            } else {
225
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
-            }
227
-        }
209
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
+		/**
211
+		 *    espresso_load_error_handling
212
+		 *    this function loads EE's class for handling exceptions and errors
213
+		 */
214
+		function espresso_load_error_handling()
215
+		{
216
+			// load debugging tools
217
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
+				EEH_Debug_Tools::instance();
220
+			}
221
+			// load error handling
222
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
+				require_once(EE_CORE . 'EE_Error.core.php');
224
+			} else {
225
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
+			}
227
+		}
228 228
 
229
-        /**
230
-         *    espresso_load_required
231
-         *    given a class name and path, this function will load that file or throw an exception
232
-         *
233
-         * @param    string $classname
234
-         * @param    string $full_path_to_file
235
-         * @throws    EE_Error
236
-         */
237
-        function espresso_load_required($classname, $full_path_to_file)
238
-        {
239
-            static $error_handling_loaded = false;
240
-            if ( ! $error_handling_loaded) {
241
-                espresso_load_error_handling();
242
-                $error_handling_loaded = true;
243
-            }
244
-            if (is_readable($full_path_to_file)) {
245
-                require_once($full_path_to_file);
246
-            } else {
247
-                throw new EE_Error (
248
-                        sprintf(
249
-                                esc_html__(
250
-                                        'The %s class file could not be located or is not readable due to file permissions.',
251
-                                        'event_espresso'
252
-                                ),
253
-                                $classname
254
-                        )
255
-                );
256
-            }
257
-        }
229
+		/**
230
+		 *    espresso_load_required
231
+		 *    given a class name and path, this function will load that file or throw an exception
232
+		 *
233
+		 * @param    string $classname
234
+		 * @param    string $full_path_to_file
235
+		 * @throws    EE_Error
236
+		 */
237
+		function espresso_load_required($classname, $full_path_to_file)
238
+		{
239
+			static $error_handling_loaded = false;
240
+			if ( ! $error_handling_loaded) {
241
+				espresso_load_error_handling();
242
+				$error_handling_loaded = true;
243
+			}
244
+			if (is_readable($full_path_to_file)) {
245
+				require_once($full_path_to_file);
246
+			} else {
247
+				throw new EE_Error (
248
+						sprintf(
249
+								esc_html__(
250
+										'The %s class file could not be located or is not readable due to file permissions.',
251
+										'event_espresso'
252
+								),
253
+								$classname
254
+						)
255
+				);
256
+			}
257
+		}
258 258
 
259
-        espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
-        espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
-        espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
-        new EE_Bootstrap();
263
-    }
259
+		espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
+		espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
+		espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
+		new EE_Bootstrap();
263
+	}
264 264
 }
265 265
 if ( ! function_exists('espresso_deactivate_plugin')) {
266
-    /**
267
-     *    deactivate_plugin
268
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
-     *
270
-     * @access public
271
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
-     * @return    void
273
-     */
274
-    function espresso_deactivate_plugin($plugin_basename = '')
275
-    {
276
-        if ( ! function_exists('deactivate_plugins')) {
277
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
-        }
279
-        unset($_GET['activate'], $_REQUEST['activate']);
280
-        deactivate_plugins($plugin_basename);
281
-    }
266
+	/**
267
+	 *    deactivate_plugin
268
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
+	 *
270
+	 * @access public
271
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
+	 * @return    void
273
+	 */
274
+	function espresso_deactivate_plugin($plugin_basename = '')
275
+	{
276
+		if ( ! function_exists('deactivate_plugins')) {
277
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
+		}
279
+		unset($_GET['activate'], $_REQUEST['activate']);
280
+		deactivate_plugins($plugin_basename);
281
+	}
282 282
 }
283 283
\ No newline at end of file
Please login to merge, or discard this patch.
core/EE_Registry.core.php 3 patches
Doc Comments   +1 added lines, -3 removed lines patch added patch discarded remove patch
@@ -279,6 +279,7 @@  discard block
 block discarded – undo
279 279
 
280 280
     /**
281 281
      * @param mixed string | EED_Module $module
282
+     * @param string $module
282 283
      * @throws EE_Error
283 284
      * @throws ReflectionException
284 285
      */
@@ -644,8 +645,6 @@  discard block
 block discarded – undo
644 645
      * @param bool|string $class_name   Fully Qualified Class Name
645 646
      * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
646 647
      * @param bool        $cache        whether to cache the instantiated object for reuse
647
-     * @param bool        $from_db      some classes are instantiated from the db
648
-     *                                  and thus call a different method to instantiate
649 648
      * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
650 649
      * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
651 650
      * @return bool|null|mixed          null = failure to load or instantiate class object.
@@ -979,7 +978,6 @@  discard block
 block discarded – undo
979 978
      * @param string $class_name
980 979
      * @param array  $arguments
981 980
      * @param string $type
982
-     * @param bool   $from_db
983 981
      * @return null|object
984 982
      * @throws EE_Error
985 983
      * @throws ReflectionException
Please login to merge, or discard this patch.
Indentation   +1474 added lines, -1474 removed lines patch added patch discarded remove patch
@@ -22,1480 +22,1480 @@
 block discarded – undo
22 22
 class EE_Registry implements ResettableInterface
23 23
 {
24 24
 
25
-    /**
26
-     * @var EE_Registry $_instance
27
-     */
28
-    private static $_instance;
29
-
30
-    /**
31
-     * @var EE_Dependency_Map $_dependency_map
32
-     */
33
-    protected $_dependency_map;
34
-
35
-    /**
36
-     * @var array $_class_abbreviations
37
-     */
38
-    protected $_class_abbreviations = array();
39
-
40
-    /**
41
-     * @var CommandBusInterface $BUS
42
-     */
43
-    public $BUS;
44
-
45
-    /**
46
-     * @var EE_Cart $CART
47
-     */
48
-    public $CART;
49
-
50
-    /**
51
-     * @var EE_Config $CFG
52
-     */
53
-    public $CFG;
54
-
55
-    /**
56
-     * @var EE_Network_Config $NET_CFG
57
-     */
58
-    public $NET_CFG;
59
-
60
-    /**
61
-     * StdClass object for storing library classes in
62
-     *
63
-     * @var StdClass $LIB
64
-     */
65
-    public $LIB;
66
-
67
-    /**
68
-     * @var EE_Request_Handler $REQ
69
-     */
70
-    public $REQ;
71
-
72
-    /**
73
-     * @var EE_Session $SSN
74
-     */
75
-    public $SSN;
76
-
77
-    /**
78
-     * @since 4.5.0
79
-     * @var EE_Capabilities $CAP
80
-     */
81
-    public $CAP;
82
-
83
-    /**
84
-     * @since 4.9.0
85
-     * @var EE_Message_Resource_Manager $MRM
86
-     */
87
-    public $MRM;
88
-
89
-
90
-    /**
91
-     * @var Registry $AssetsRegistry
92
-     */
93
-    public $AssetsRegistry;
94
-
95
-    /**
96
-     * StdClass object for holding addons which have registered themselves to work with EE core
97
-     *
98
-     * @var EE_Addon[] $addons
99
-     */
100
-    public $addons;
101
-
102
-    /**
103
-     * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
104
-     *
105
-     * @var EEM_Base[] $models
106
-     */
107
-    public $models = array();
108
-
109
-    /**
110
-     * @var EED_Module[] $modules
111
-     */
112
-    public $modules;
113
-
114
-    /**
115
-     * @var EES_Shortcode[] $shortcodes
116
-     */
117
-    public $shortcodes;
118
-
119
-    /**
120
-     * @var WP_Widget[] $widgets
121
-     */
122
-    public $widgets;
123
-
124
-    /**
125
-     * this is an array of all implemented model names (i.e. not the parent abstract models, or models
126
-     * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
127
-     * Keys are model "short names" (eg "Event") as used in model relations, and values are
128
-     * classnames (eg "EEM_Event")
129
-     *
130
-     * @var array $non_abstract_db_models
131
-     */
132
-    public $non_abstract_db_models = array();
133
-
134
-
135
-    /**
136
-     * internationalization for JS strings
137
-     *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
138
-     *    in js file:  var translatedString = eei18n.string_key;
139
-     *
140
-     * @var array $i18n_js_strings
141
-     */
142
-    public static $i18n_js_strings = array();
143
-
144
-
145
-    /**
146
-     * $main_file - path to espresso.php
147
-     *
148
-     * @var array $main_file
149
-     */
150
-    public $main_file;
151
-
152
-    /**
153
-     * array of ReflectionClass objects where the key is the class name
154
-     *
155
-     * @var ReflectionClass[] $_reflectors
156
-     */
157
-    public $_reflectors;
158
-
159
-    /**
160
-     * boolean flag to indicate whether or not to load/save dependencies from/to the cache
161
-     *
162
-     * @var boolean $_cache_on
163
-     */
164
-    protected $_cache_on = true;
165
-
166
-
167
-
168
-    /**
169
-     * @singleton method used to instantiate class object
170
-     * @param  EE_Dependency_Map $dependency_map
171
-     * @return EE_Registry instance
172
-     * @throws InvalidArgumentException
173
-     * @throws InvalidInterfaceException
174
-     * @throws InvalidDataTypeException
175
-     */
176
-    public static function instance(EE_Dependency_Map $dependency_map = null)
177
-    {
178
-        // check if class object is instantiated
179
-        if (! self::$_instance instanceof EE_Registry) {
180
-            self::$_instance = new self($dependency_map);
181
-        }
182
-        return self::$_instance;
183
-    }
184
-
185
-
186
-
187
-    /**
188
-     * protected constructor to prevent direct creation
189
-     *
190
-     * @Constructor
191
-     * @param  EE_Dependency_Map $dependency_map
192
-     * @throws InvalidDataTypeException
193
-     * @throws InvalidInterfaceException
194
-     * @throws InvalidArgumentException
195
-     */
196
-    protected function __construct(EE_Dependency_Map $dependency_map)
197
-    {
198
-        $this->_dependency_map = $dependency_map;
199
-        $this->LIB = new stdClass();
200
-        $this->addons = new stdClass();
201
-        $this->modules = new stdClass();
202
-        $this->shortcodes = new stdClass();
203
-        $this->widgets = new stdClass();
204
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
205
-    }
206
-
207
-
208
-
209
-    /**
210
-     * initialize
211
-     *
212
-     * @throws EE_Error
213
-     * @throws ReflectionException
214
-     */
215
-    public function initialize()
216
-    {
217
-        $this->_class_abbreviations = apply_filters(
218
-            'FHEE__EE_Registry____construct___class_abbreviations',
219
-            array(
220
-                'EE_Config'                                       => 'CFG',
221
-                'EE_Session'                                      => 'SSN',
222
-                'EE_Capabilities'                                 => 'CAP',
223
-                'EE_Cart'                                         => 'CART',
224
-                'EE_Network_Config'                               => 'NET_CFG',
225
-                'EE_Request_Handler'                              => 'REQ',
226
-                'EE_Message_Resource_Manager'                     => 'MRM',
227
-                'EventEspresso\core\services\commands\CommandBus' => 'BUS',
228
-                'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
229
-            )
230
-        );
231
-        $this->load_core('Base', array(), true);
232
-        // add our request and response objects to the cache
233
-        $request_loader = $this->_dependency_map->class_loader('EE_Request');
234
-        $this->_set_cached_class(
235
-            $request_loader(),
236
-            'EE_Request'
237
-        );
238
-        $response_loader = $this->_dependency_map->class_loader('EE_Response');
239
-        $this->_set_cached_class(
240
-            $response_loader(),
241
-            'EE_Response'
242
-        );
243
-        add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
244
-    }
245
-
246
-
247
-
248
-    /**
249
-     * @return void
250
-     */
251
-    public function init()
252
-    {
253
-        // Get current page protocol
254
-        $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
255
-        // Output admin-ajax.php URL with same protocol as current page
256
-        self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
257
-        self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
258
-    }
259
-
260
-
261
-
262
-    /**
263
-     * localize_i18n_js_strings
264
-     *
265
-     * @return string
266
-     */
267
-    public static function localize_i18n_js_strings()
268
-    {
269
-        $i18n_js_strings = (array)self::$i18n_js_strings;
270
-        foreach ($i18n_js_strings as $key => $value) {
271
-            if (is_scalar($value)) {
272
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
273
-            }
274
-        }
275
-        return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
276
-    }
277
-
278
-
279
-
280
-    /**
281
-     * @param mixed string | EED_Module $module
282
-     * @throws EE_Error
283
-     * @throws ReflectionException
284
-     */
285
-    public function add_module($module)
286
-    {
287
-        if ($module instanceof EED_Module) {
288
-            $module_class = get_class($module);
289
-            $this->modules->{$module_class} = $module;
290
-        } else {
291
-            if (! class_exists('EE_Module_Request_Router')) {
292
-                $this->load_core('Module_Request_Router');
293
-            }
294
-            EE_Module_Request_Router::module_factory($module);
295
-        }
296
-    }
297
-
298
-
299
-
300
-    /**
301
-     * @param string $module_name
302
-     * @return mixed EED_Module | NULL
303
-     */
304
-    public function get_module($module_name = '')
305
-    {
306
-        return isset($this->modules->{$module_name})
307
-            ? $this->modules->{$module_name}
308
-            : null;
309
-    }
310
-
311
-
312
-
313
-    /**
314
-     * loads core classes - must be singletons
315
-     *
316
-     * @param string $class_name - simple class name ie: session
317
-     * @param mixed  $arguments
318
-     * @param bool   $load_only
319
-     * @return mixed
320
-     * @throws EE_Error
321
-     * @throws ReflectionException
322
-     */
323
-    public function load_core($class_name, $arguments = array(), $load_only = false)
324
-    {
325
-        $core_paths = apply_filters(
326
-            'FHEE__EE_Registry__load_core__core_paths',
327
-            array(
328
-                EE_CORE,
329
-                EE_ADMIN,
330
-                EE_CPTS,
331
-                EE_CORE . 'data_migration_scripts' . DS,
332
-                EE_CORE . 'capabilities' . DS,
333
-                EE_CORE . 'request_stack' . DS,
334
-                EE_CORE . 'middleware' . DS,
335
-            )
336
-        );
337
-        // retrieve instantiated class
338
-        return $this->_load(
339
-            $core_paths,
340
-            'EE_',
341
-            $class_name,
342
-            'core',
343
-            $arguments,
344
-            true,
345
-            $load_only
346
-        );
347
-    }
348
-
349
-
350
-
351
-    /**
352
-     * loads service classes
353
-     *
354
-     * @param string $class_name - simple class name ie: session
355
-     * @param mixed  $arguments
356
-     * @param bool   $load_only
357
-     * @return mixed
358
-     * @throws EE_Error
359
-     * @throws ReflectionException
360
-     */
361
-    public function load_service($class_name, $arguments = array(), $load_only = false)
362
-    {
363
-        $service_paths = apply_filters(
364
-            'FHEE__EE_Registry__load_service__service_paths',
365
-            array(
366
-                EE_CORE . 'services' . DS,
367
-            )
368
-        );
369
-        // retrieve instantiated class
370
-        return $this->_load(
371
-            $service_paths,
372
-            'EE_',
373
-            $class_name,
374
-            'class',
375
-            $arguments,
376
-            true,
377
-            $load_only
378
-        );
379
-    }
380
-
381
-
382
-
383
-    /**
384
-     * loads data_migration_scripts
385
-     *
386
-     * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
387
-     * @param mixed  $arguments
388
-     * @return EE_Data_Migration_Script_Base|mixed
389
-     * @throws EE_Error
390
-     * @throws ReflectionException
391
-     */
392
-    public function load_dms($class_name, $arguments = array())
393
-    {
394
-        // retrieve instantiated class
395
-        return $this->_load(
396
-            EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
397
-            'EE_DMS_',
398
-            $class_name,
399
-            'dms',
400
-            $arguments,
401
-            false
402
-        );
403
-    }
404
-
405
-
406
-
407
-    /**
408
-     * loads object creating classes - must be singletons
409
-     *
410
-     * @param string $class_name - simple class name ie: attendee
411
-     * @param mixed  $arguments  - an array of arguments to pass to the class
412
-     * @param bool   $from_db    - deprecated
413
-     * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
414
-     *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
415
-     * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
416
-     *                           (default)
417
-     * @return EE_Base_Class | bool
418
-     * @throws EE_Error
419
-     * @throws ReflectionException
420
-     */
421
-    public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
422
-    {
423
-        $paths = apply_filters(
424
-            'FHEE__EE_Registry__load_class__paths', array(
425
-            EE_CORE,
426
-            EE_CLASSES,
427
-            EE_BUSINESS,
428
-        )
429
-        );
430
-        // retrieve instantiated class
431
-        return $this->_load(
432
-            $paths,
433
-            'EE_',
434
-            $class_name,
435
-            'class',
436
-            $arguments,
437
-            $cache,
438
-            $load_only
439
-        );
440
-    }
441
-
442
-
443
-
444
-    /**
445
-     * loads helper classes - must be singletons
446
-     *
447
-     * @param string $class_name - simple class name ie: price
448
-     * @param mixed  $arguments
449
-     * @param bool   $load_only
450
-     * @return EEH_Base | bool
451
-     * @throws EE_Error
452
-     * @throws ReflectionException
453
-     */
454
-    public function load_helper($class_name, $arguments = array(), $load_only = true)
455
-    {
456
-        // todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
457
-        $helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
458
-        // retrieve instantiated class
459
-        return $this->_load(
460
-            $helper_paths,
461
-            'EEH_',
462
-            $class_name,
463
-            'helper',
464
-            $arguments,
465
-            true,
466
-            $load_only
467
-        );
468
-    }
469
-
470
-
471
-
472
-    /**
473
-     * loads core classes - must be singletons
474
-     *
475
-     * @param string $class_name - simple class name ie: session
476
-     * @param mixed  $arguments
477
-     * @param bool   $load_only
478
-     * @param bool   $cache      whether to cache the object or not.
479
-     * @return mixed
480
-     * @throws EE_Error
481
-     * @throws ReflectionException
482
-     */
483
-    public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
484
-    {
485
-        $paths = array(
486
-            EE_LIBRARIES,
487
-            EE_LIBRARIES . 'messages' . DS,
488
-            EE_LIBRARIES . 'shortcodes' . DS,
489
-            EE_LIBRARIES . 'qtips' . DS,
490
-            EE_LIBRARIES . 'payment_methods' . DS,
491
-        );
492
-        // retrieve instantiated class
493
-        return $this->_load(
494
-            $paths,
495
-            'EE_',
496
-            $class_name,
497
-            'lib',
498
-            $arguments,
499
-            $cache,
500
-            $load_only
501
-        );
502
-    }
503
-
504
-
505
-
506
-    /**
507
-     * loads model classes - must be singletons
508
-     *
509
-     * @param string $class_name - simple class name ie: price
510
-     * @param mixed  $arguments
511
-     * @param bool   $load_only
512
-     * @return EEM_Base | bool
513
-     * @throws EE_Error
514
-     * @throws ReflectionException
515
-     */
516
-    public function load_model($class_name, $arguments = array(), $load_only = false)
517
-    {
518
-        $paths = apply_filters(
519
-            'FHEE__EE_Registry__load_model__paths', array(
520
-            EE_MODELS,
521
-            EE_CORE,
522
-        )
523
-        );
524
-        // retrieve instantiated class
525
-        return $this->_load(
526
-            $paths,
527
-            'EEM_',
528
-            $class_name,
529
-            'model',
530
-            $arguments,
531
-            true,
532
-            $load_only
533
-        );
534
-    }
535
-
536
-
537
-
538
-    /**
539
-     * loads model classes - must be singletons
540
-     *
541
-     * @param string $class_name - simple class name ie: price
542
-     * @param mixed  $arguments
543
-     * @param bool   $load_only
544
-     * @return mixed | bool
545
-     * @throws EE_Error
546
-     * @throws ReflectionException
547
-     */
548
-    public function load_model_class($class_name, $arguments = array(), $load_only = true)
549
-    {
550
-        $paths = array(
551
-            EE_MODELS . 'fields' . DS,
552
-            EE_MODELS . 'helpers' . DS,
553
-            EE_MODELS . 'relations' . DS,
554
-            EE_MODELS . 'strategies' . DS,
555
-        );
556
-        // retrieve instantiated class
557
-        return $this->_load(
558
-            $paths,
559
-            'EE_',
560
-            $class_name,
561
-            '',
562
-            $arguments,
563
-            true,
564
-            $load_only
565
-        );
566
-    }
567
-
568
-
569
-
570
-    /**
571
-     * Determines if $model_name is the name of an actual EE model.
572
-     *
573
-     * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
574
-     * @return boolean
575
-     */
576
-    public function is_model_name($model_name)
577
-    {
578
-        return isset($this->models[$model_name]);
579
-    }
580
-
581
-
582
-
583
-    /**
584
-     * generic class loader
585
-     *
586
-     * @param string $path_to_file - directory path to file location, not including filename
587
-     * @param string $file_name    - file name  ie:  my_file.php, including extension
588
-     * @param string $type         - file type - core? class? helper? model?
589
-     * @param mixed  $arguments
590
-     * @param bool   $load_only
591
-     * @return mixed
592
-     * @throws EE_Error
593
-     * @throws ReflectionException
594
-     */
595
-    public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
596
-    {
597
-        // retrieve instantiated class
598
-        return $this->_load(
599
-            $path_to_file,
600
-            '',
601
-            $file_name,
602
-            $type,
603
-            $arguments,
604
-            true,
605
-            $load_only
606
-        );
607
-    }
608
-
609
-
610
-
611
-    /**
612
-     * @param string $path_to_file - directory path to file location, not including filename
613
-     * @param string $class_name   - full class name  ie:  My_Class
614
-     * @param string $type         - file type - core? class? helper? model?
615
-     * @param mixed  $arguments
616
-     * @param bool   $load_only
617
-     * @return bool|EE_Addon|object
618
-     * @throws EE_Error
619
-     * @throws ReflectionException
620
-     */
621
-    public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
622
-    {
623
-        // retrieve instantiated class
624
-        return $this->_load(
625
-            $path_to_file,
626
-            'addon',
627
-            $class_name,
628
-            $type,
629
-            $arguments,
630
-            true,
631
-            $load_only
632
-        );
633
-    }
634
-
635
-
636
-
637
-    /**
638
-     * instantiates, caches, and automatically resolves dependencies
639
-     * for classes that use a Fully Qualified Class Name.
640
-     * if the class is not capable of being loaded using PSR-4 autoloading,
641
-     * then you need to use one of the existing load_*() methods
642
-     * which can resolve the classname and filepath from the passed arguments
643
-     *
644
-     * @param bool|string $class_name   Fully Qualified Class Name
645
-     * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
646
-     * @param bool        $cache        whether to cache the instantiated object for reuse
647
-     * @param bool        $from_db      some classes are instantiated from the db
648
-     *                                  and thus call a different method to instantiate
649
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
650
-     * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
651
-     * @return bool|null|mixed          null = failure to load or instantiate class object.
652
-     *                                  object = class loaded and instantiated successfully.
653
-     *                                  bool = fail or success when $load_only is true
654
-     * @throws EE_Error
655
-     * @throws ReflectionException
656
-     */
657
-    public function create(
658
-        $class_name = false,
659
-        $arguments = array(),
660
-        $cache = true,
661
-        $load_only = false,
662
-        $addon = false
663
-    ) {
664
-        $class_name = ltrim($class_name, '\\');
665
-        $class_name = $this->_dependency_map->get_alias($class_name);
666
-        if (! class_exists($class_name)) {
667
-            // maybe the class is registered with a preceding \
668
-            $class_name = strpos($class_name, '\\') !== 0
669
-                ? '\\' . $class_name
670
-                : $class_name;
671
-            // still doesn't exist ?
672
-            if (! class_exists($class_name)) {
673
-                return null;
674
-            }
675
-        }
676
-        // if we're only loading the class and it already exists, then let's just return true immediately
677
-        if ($load_only) {
678
-            return true;
679
-        }
680
-        $addon = $addon
681
-            ? 'addon'
682
-            : '';
683
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
684
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
685
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
686
-        if ($this->_cache_on && $cache && ! $load_only) {
687
-            // return object if it's already cached
688
-            $cached_class = $this->_get_cached_class($class_name, $addon);
689
-            if ($cached_class !== null) {
690
-                return $cached_class;
691
-            }
692
-        }
693
-        // obtain the loader method from the dependency map
694
-        $loader = $this->_dependency_map->class_loader($class_name);
695
-        // instantiate the requested object
696
-        if ($loader instanceof Closure) {
697
-            $class_obj = $loader($arguments);
698
-        } else if ($loader && method_exists($this, $loader)) {
699
-            $class_obj = $this->{$loader}($class_name, $arguments);
700
-        } else {
701
-            $class_obj = $this->_create_object($class_name, $arguments, $addon);
702
-        }
703
-        if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
704
-            // save it for later... kinda like gum  { : $
705
-            $this->_set_cached_class($class_obj, $class_name, $addon);
706
-        }
707
-        $this->_cache_on = true;
708
-        return $class_obj;
709
-    }
710
-
711
-
712
-
713
-    /**
714
-     * instantiates, caches, and injects dependencies for classes
715
-     *
716
-     * @param array       $file_paths   an array of paths to folders to look in
717
-     * @param string      $class_prefix EE  or EEM or... ???
718
-     * @param bool|string $class_name   $class name
719
-     * @param string      $type         file type - core? class? helper? model?
720
-     * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
721
-     * @param bool        $cache        whether to cache the instantiated object for reuse
722
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
723
-     * @return bool|null|object null = failure to load or instantiate class object.
724
-     *                                  object = class loaded and instantiated successfully.
725
-     *                                  bool = fail or success when $load_only is true
726
-     * @throws EE_Error
727
-     * @throws ReflectionException
728
-     */
729
-    protected function _load(
730
-        $file_paths = array(),
731
-        $class_prefix = 'EE_',
732
-        $class_name = false,
733
-        $type = 'class',
734
-        $arguments = array(),
735
-        $cache = true,
736
-        $load_only = false
737
-    ) {
738
-        $class_name = ltrim($class_name, '\\');
739
-        // strip php file extension
740
-        $class_name = str_replace('.php', '', trim($class_name));
741
-        // does the class have a prefix ?
742
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
743
-            // make sure $class_prefix is uppercase
744
-            $class_prefix = strtoupper(trim($class_prefix));
745
-            // add class prefix ONCE!!!
746
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
747
-        }
748
-        $class_name = $this->_dependency_map->get_alias($class_name);
749
-        $class_exists = class_exists($class_name);
750
-        // if we're only loading the class and it already exists, then let's just return true immediately
751
-        if ($load_only && $class_exists) {
752
-            return true;
753
-        }
754
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
755
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
756
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
757
-        if ($this->_cache_on && $cache && ! $load_only) {
758
-            // return object if it's already cached
759
-            $cached_class = $this->_get_cached_class($class_name, $class_prefix);
760
-            if ($cached_class !== null) {
761
-                return $cached_class;
762
-            }
763
-        }
764
-        // if the class doesn't already exist.. then we need to try and find the file and load it
765
-        if (! $class_exists) {
766
-            // get full path to file
767
-            $path = $this->_resolve_path($class_name, $type, $file_paths);
768
-            // load the file
769
-            $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
770
-            // if loading failed, or we are only loading a file but NOT instantiating an object
771
-            if (! $loaded || $load_only) {
772
-                // return boolean if only loading, or null if an object was expected
773
-                return $load_only
774
-                    ? $loaded
775
-                    : null;
776
-            }
777
-        }
778
-        // instantiate the requested object
779
-        $class_obj = $this->_create_object($class_name, $arguments, $type);
780
-        if ($this->_cache_on && $cache) {
781
-            // save it for later... kinda like gum  { : $
782
-            $this->_set_cached_class($class_obj, $class_name, $class_prefix);
783
-        }
784
-        $this->_cache_on = true;
785
-        return $class_obj;
786
-    }
787
-
788
-
789
-
790
-    /**
791
-     * @param string $class_name
792
-     * @param string $default have to specify something, but not anything that will conflict
793
-     * @return mixed|string
794
-     */
795
-    protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
796
-    {
797
-        return isset($this->_class_abbreviations[$class_name])
798
-            ? $this->_class_abbreviations[$class_name]
799
-            : $default;
800
-    }
801
-
802
-    /**
803
-     * attempts to find a cached version of the requested class
804
-     * by looking in the following places:
805
-     *        $this->{$class_abbreviation}            ie:    $this->CART
806
-     *        $this->{$class_name}                        ie:    $this->Some_Class
807
-     *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
808
-     *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
809
-     *
810
-     * @param string $class_name
811
-     * @param string $class_prefix
812
-     * @return mixed
813
-     */
814
-    protected function _get_cached_class($class_name, $class_prefix = '')
815
-    {
816
-        if ($class_name === 'EE_Registry') {
817
-            return $this;
818
-        }
819
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
820
-        $class_name = str_replace('\\', '_', $class_name);
821
-        // check if class has already been loaded, and return it if it has been
822
-        if (isset($this->{$class_abbreviation})) {
823
-            return $this->{$class_abbreviation};
824
-        }
825
-        if (isset ($this->{$class_name})) {
826
-            return $this->{$class_name};
827
-        }
828
-        if (isset ($this->LIB->{$class_name})) {
829
-            return $this->LIB->{$class_name};
830
-        }
831
-        if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
832
-            return $this->addons->{$class_name};
833
-        }
834
-        return null;
835
-    }
836
-
837
-
838
-
839
-    /**
840
-     * removes a cached version of the requested class
841
-     *
842
-     * @param string  $class_name
843
-     * @param boolean $addon
844
-     * @return boolean
845
-     */
846
-    public function clear_cached_class($class_name, $addon = false)
847
-    {
848
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
849
-        $class_name = str_replace('\\', '_', $class_name);
850
-        // check if class has already been loaded, and return it if it has been
851
-        if (isset($this->{$class_abbreviation})) {
852
-            $this->{$class_abbreviation} = null;
853
-            return true;
854
-        }
855
-        if (isset($this->{$class_name})) {
856
-            $this->{$class_name} = null;
857
-            return true;
858
-        }
859
-        if (isset($this->LIB->{$class_name})) {
860
-            unset($this->LIB->{$class_name});
861
-            return true;
862
-        }
863
-        if ($addon && isset($this->addons->{$class_name})) {
864
-            unset($this->addons->{$class_name});
865
-            return true;
866
-        }
867
-        return false;
868
-    }
869
-
870
-
871
-
872
-    /**
873
-     * attempts to find a full valid filepath for the requested class.
874
-     * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
875
-     * then returns that path if the target file has been found and is readable
876
-     *
877
-     * @param string $class_name
878
-     * @param string $type
879
-     * @param array  $file_paths
880
-     * @return string | bool
881
-     */
882
-    protected function _resolve_path($class_name, $type = '', $file_paths = array())
883
-    {
884
-        // make sure $file_paths is an array
885
-        $file_paths = is_array($file_paths)
886
-            ? $file_paths
887
-            : array($file_paths);
888
-        // cycle thru paths
889
-        foreach ($file_paths as $key => $file_path) {
890
-            // convert all separators to proper DS, if no filepath, then use EE_CLASSES
891
-            $file_path = $file_path
892
-                ? str_replace(array('/', '\\'), DS, $file_path)
893
-                : EE_CLASSES;
894
-            // prep file type
895
-            $type = ! empty($type)
896
-                ? trim($type, '.') . '.'
897
-                : '';
898
-            // build full file path
899
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
900
-            //does the file exist and can be read ?
901
-            if (is_readable($file_paths[$key])) {
902
-                return $file_paths[$key];
903
-            }
904
-        }
905
-        return false;
906
-    }
907
-
908
-
909
-
910
-    /**
911
-     * basically just performs a require_once()
912
-     * but with some error handling
913
-     *
914
-     * @param  string $path
915
-     * @param  string $class_name
916
-     * @param  string $type
917
-     * @param  array  $file_paths
918
-     * @return bool
919
-     * @throws EE_Error
920
-     * @throws ReflectionException
921
-     */
922
-    protected function _require_file($path, $class_name, $type = '', $file_paths = array())
923
-    {
924
-        // don't give up! you gotta...
925
-        try {
926
-            //does the file exist and can it be read ?
927
-            if (! $path) {
928
-                // so sorry, can't find the file
929
-                throw new EE_Error (
930
-                    sprintf(
931
-                        esc_html__(
932
-                            'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
933
-                            'event_espresso'
934
-                        ),
935
-                        trim($type, '.'),
936
-                        $class_name,
937
-                        '<br />' . implode(',<br />', $file_paths)
938
-                    )
939
-                );
940
-            }
941
-            // get the file
942
-            require_once($path);
943
-            // if the class isn't already declared somewhere
944
-            if (class_exists($class_name, false) === false) {
945
-                // so sorry, not a class
946
-                throw new EE_Error(
947
-                    sprintf(
948
-                        esc_html__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
949
-                        $type,
950
-                        $path,
951
-                        $class_name
952
-                    )
953
-                );
954
-            }
955
-        } catch (EE_Error $e) {
956
-            $e->get_error();
957
-            return false;
958
-        }
959
-        return true;
960
-    }
961
-
962
-
963
-
964
-    /**
965
-     * _create_object
966
-     * Attempts to instantiate the requested class via any of the
967
-     * commonly used instantiation methods employed throughout EE.
968
-     * The priority for instantiation is as follows:
969
-     *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
970
-     *        - model objects via their 'new_instance_from_db' method
971
-     *        - model objects via their 'new_instance' method
972
-     *        - "singleton" classes" via their 'instance' method
973
-     *    - standard instantiable classes via their __constructor
974
-     * Prior to instantiation, if the classname exists in the dependency_map,
975
-     * then the constructor for the requested class will be examined to determine
976
-     * if any dependencies exist, and if they can be injected.
977
-     * If so, then those classes will be added to the array of arguments passed to the constructor
978
-     *
979
-     * @param string $class_name
980
-     * @param array  $arguments
981
-     * @param string $type
982
-     * @param bool   $from_db
983
-     * @return null|object
984
-     * @throws EE_Error
985
-     * @throws ReflectionException
986
-     */
987
-    protected function _create_object($class_name, $arguments = array(), $type = '')
988
-    {
989
-        $class_obj = null;
990
-        $instantiation_mode = '0) none';
991
-        // don't give up! you gotta...
992
-        try {
993
-            // create reflection
994
-            $reflector = $this->get_ReflectionClass($class_name);
995
-            // make sure arguments are an array
996
-            $arguments = is_array($arguments)
997
-                ? $arguments
998
-                : array($arguments);
999
-            // and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1000
-            // else wrap it in an additional array so that it doesn't get split into multiple parameters
1001
-            $arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1002
-                ? $arguments
1003
-                : array($arguments);
1004
-            // attempt to inject dependencies ?
1005
-            if ($this->_dependency_map->has($class_name)) {
1006
-                $arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1007
-            }
1008
-            // instantiate the class if possible
1009
-            if ($reflector->isAbstract()) {
1010
-                // nothing to instantiate, loading file was enough
1011
-                // does not throw an exception so $instantiation_mode is unused
1012
-                // $instantiation_mode = "1) no constructor abstract class";
1013
-                $class_obj = true;
1014
-            } else if (empty($arguments) && $reflector->getConstructor() === null && $reflector->isInstantiable()) {
1015
-                // no constructor = static methods only... nothing to instantiate, loading file was enough
1016
-                $instantiation_mode = '2) no constructor but instantiable';
1017
-                $class_obj = $reflector->newInstance();
1018
-            } else if (method_exists($class_name, 'new_instance')) {
1019
-                $instantiation_mode = '4) new_instance()';
1020
-                $class_obj = call_user_func_array(array($class_name, 'new_instance'), $arguments);
1021
-            } else if (method_exists($class_name, 'instance')) {
1022
-                $instantiation_mode = '5) instance()';
1023
-                $class_obj = call_user_func_array(array($class_name, 'instance'), $arguments);
1024
-            } else if ($reflector->isInstantiable()) {
1025
-                $instantiation_mode = '6) constructor';
1026
-                $class_obj = $reflector->newInstanceArgs($arguments);
1027
-            } else {
1028
-                // heh ? something's not right !
1029
-                throw new EE_Error(
1030
-                    sprintf(
1031
-                        esc_html__('The %s file %s could not be instantiated.', 'event_espresso'),
1032
-                        $type,
1033
-                        $class_name
1034
-                    )
1035
-                );
1036
-            }
1037
-        } catch (Exception $e) {
1038
-            if (! $e instanceof EE_Error) {
1039
-                $e = new EE_Error(
1040
-                    sprintf(
1041
-                        esc_html__(
1042
-                            'The following error occurred while attempting to instantiate "%1$s": %2$s %3$s %2$s instantiation mode : %4$s',
1043
-                            'event_espresso'
1044
-                        ),
1045
-                        $class_name,
1046
-                        '<br />',
1047
-                        $e->getMessage(),
1048
-                        $instantiation_mode
1049
-                    )
1050
-                );
1051
-            }
1052
-            $e->get_error();
1053
-        }
1054
-        return $class_obj;
1055
-    }
1056
-
1057
-
1058
-
1059
-    /**
1060
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1061
-     * @param array $array
1062
-     * @return bool
1063
-     */
1064
-    protected function _array_is_numerically_and_sequentially_indexed(array $array)
1065
-    {
1066
-        return ! empty($array)
1067
-            ? array_keys($array) === range(0, count($array) - 1)
1068
-            : true;
1069
-    }
1070
-
1071
-
1072
-
1073
-    /**
1074
-     * getReflectionClass
1075
-     * checks if a ReflectionClass object has already been generated for a class
1076
-     * and returns that instead of creating a new one
1077
-     *
1078
-     * @param string $class_name
1079
-     * @return ReflectionClass
1080
-     * @throws ReflectionException
1081
-     */
1082
-    public function get_ReflectionClass($class_name)
1083
-    {
1084
-        if (
1085
-            ! isset($this->_reflectors[$class_name])
1086
-            || ! $this->_reflectors[$class_name] instanceof ReflectionClass
1087
-        ) {
1088
-            $this->_reflectors[$class_name] = new ReflectionClass($class_name);
1089
-        }
1090
-        return $this->_reflectors[$class_name];
1091
-    }
1092
-
1093
-
1094
-
1095
-    /**
1096
-     * _resolve_dependencies
1097
-     * examines the constructor for the requested class to determine
1098
-     * if any dependencies exist, and if they can be injected.
1099
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1100
-     * PLZ NOTE: this is achieved by type hinting the constructor params
1101
-     * For example:
1102
-     *        if attempting to load a class "Foo" with the following constructor:
1103
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
1104
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
1105
-     *        but only IF they are NOT already present in the incoming arguments array,
1106
-     *        and the correct classes can be loaded
1107
-     *
1108
-     * @param ReflectionClass $reflector
1109
-     * @param string          $class_name
1110
-     * @param array           $arguments
1111
-     * @return array
1112
-     * @throws EE_Error
1113
-     * @throws ReflectionException
1114
-     */
1115
-    protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1116
-    {
1117
-        // let's examine the constructor
1118
-        $constructor = $reflector->getConstructor();
1119
-        // whu? huh? nothing?
1120
-        if (! $constructor) {
1121
-            return $arguments;
1122
-        }
1123
-        // get constructor parameters
1124
-        $params = $constructor->getParameters();
1125
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1126
-        $argument_keys = array_keys($arguments);
1127
-        // now loop thru all of the constructors expected parameters
1128
-        foreach ($params as $index => $param) {
1129
-            // is this a dependency for a specific class ?
1130
-            $param_class = $param->getClass()
1131
-                ? $param->getClass()->name
1132
-                : null;
1133
-            // BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1134
-            $param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1135
-                ? $this->_dependency_map->get_alias($param_class, $class_name)
1136
-                : $param_class;
1137
-            if (
1138
-                // param is not even a class
1139
-                $param_class === null
1140
-                // and something already exists in the incoming arguments for this param
1141
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1142
-            ) {
1143
-                // so let's skip this argument and move on to the next
1144
-                continue;
1145
-            }
1146
-            if (
1147
-                // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1148
-                $param_class !== null
1149
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1150
-                && $arguments[$argument_keys[$index]] instanceof $param_class
1151
-            ) {
1152
-                // skip this argument and move on to the next
1153
-                continue;
1154
-            }
1155
-            if (
1156
-                // parameter is type hinted as a class, and should be injected
1157
-                $param_class !== null
1158
-                && $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1159
-            ) {
1160
-                $arguments = $this->_resolve_dependency(
1161
-                    $class_name,
1162
-                    $param_class,
1163
-                    $arguments,
1164
-                    $index,
1165
-                    $argument_keys
1166
-                );
1167
-            } else {
1168
-                try {
1169
-                    $arguments[$index] = $param->isDefaultValueAvailable()
1170
-                        ? $param->getDefaultValue()
1171
-                        : null;
1172
-                } catch (ReflectionException $e) {
1173
-                    throw new ReflectionException(
1174
-                        sprintf(
1175
-                            esc_html__('%1$s for parameter "$%2$s"', 'event_espresso'),
1176
-                            $e->getMessage(),
1177
-                            $param->getName()
1178
-                        )
1179
-                    );
1180
-                }
1181
-            }
1182
-        }
1183
-        return $arguments;
1184
-    }
1185
-
1186
-
1187
-
1188
-    /**
1189
-     * @param string $class_name
1190
-     * @param string $param_class
1191
-     * @param array  $arguments
1192
-     * @param mixed  $index
1193
-     * @param array  $argument_keys
1194
-     * @return array
1195
-     * @throws EE_Error
1196
-     * @throws ReflectionException
1197
-     * @throws InvalidArgumentException
1198
-     * @throws InvalidInterfaceException
1199
-     * @throws InvalidDataTypeException
1200
-     */
1201
-    protected function _resolve_dependency($class_name, $param_class, $arguments, $index, array $argument_keys)
1202
-    {
1203
-        $dependency = null;
1204
-        // should dependency be loaded from cache ?
1205
-        $cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1206
-            $class_name,
1207
-            $param_class
1208
-        );
1209
-        $cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1210
-        // we might have a dependency...
1211
-        // let's MAYBE try and find it in our cache if that's what's been requested
1212
-        $cached_class = $cache_on
1213
-            ? $this->_get_cached_class($param_class)
1214
-            : null;
1215
-        // and grab it if it exists
1216
-        if ($cached_class instanceof $param_class) {
1217
-            $dependency = $cached_class;
1218
-        } else if ($param_class !== $class_name) {
1219
-            // obtain the loader method from the dependency map
1220
-            $loader = $this->_dependency_map->class_loader($param_class);
1221
-            // is loader a custom closure ?
1222
-            if ($loader instanceof Closure) {
1223
-                $dependency = $loader($arguments);
1224
-            } else {
1225
-                // set the cache on property for the recursive loading call
1226
-                $this->_cache_on = $cache_on;
1227
-                // if not, then let's try and load it via the registry
1228
-                if ($loader && method_exists($this, $loader)) {
1229
-                    $dependency = $this->{$loader}($param_class);
1230
-                } else {
1231
-                    $dependency = LoaderFactory::getLoader()->load(
1232
-                        $param_class,
1233
-                        array(),
1234
-                        $cache_on
1235
-                    );
1236
-                }
1237
-            }
1238
-        }
1239
-        // did we successfully find the correct dependency ?
1240
-        if ($dependency instanceof $param_class) {
1241
-            // then let's inject it into the incoming array of arguments at the correct location
1242
-            $arguments[$index] = $dependency;
1243
-        }
1244
-        return $arguments;
1245
-    }
1246
-
1247
-
1248
-
1249
-    /**
1250
-     * _set_cached_class
1251
-     * attempts to cache the instantiated class locally
1252
-     * in one of the following places, in the following order:
1253
-     *        $this->{class_abbreviation}   ie:    $this->CART
1254
-     *        $this->{$class_name}          ie:    $this->Some_Class
1255
-     *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1256
-     *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1257
-     *
1258
-     * @param object $class_obj
1259
-     * @param string $class_name
1260
-     * @param string $class_prefix
1261
-     * @return void
1262
-     */
1263
-    protected function _set_cached_class($class_obj, $class_name, $class_prefix = '')
1264
-    {
1265
-        if ($class_name === 'EE_Registry' || empty($class_obj)) {
1266
-            return;
1267
-        }
1268
-        // return newly instantiated class
1269
-        $class_abbreviation = $this->get_class_abbreviation($class_name, '');
1270
-        if ($class_abbreviation) {
1271
-            $this->{$class_abbreviation} = $class_obj;
1272
-            return;
1273
-        }
1274
-        $class_name = str_replace('\\', '_', $class_name);
1275
-        if (property_exists($this, $class_name)) {
1276
-            $this->{$class_name} = $class_obj;
1277
-            return;
1278
-        }
1279
-        if ($class_prefix === 'addon') {
1280
-            $this->addons->{$class_name} = $class_obj;
1281
-            return;
1282
-        }
1283
-        $this->LIB->{$class_name} = $class_obj;
1284
-    }
1285
-
1286
-
1287
-
1288
-    /**
1289
-     * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1290
-     *
1291
-     * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1292
-     *                          in the EE_Dependency_Map::$_class_loaders array,
1293
-     *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1294
-     * @param array  $arguments
1295
-     * @return object
1296
-     */
1297
-    public static function factory($classname, $arguments = array())
1298
-    {
1299
-        $loader = self::instance()->_dependency_map->class_loader($classname);
1300
-        if ($loader instanceof Closure) {
1301
-            return $loader($arguments);
1302
-        }
1303
-        if (method_exists(self::instance(), $loader)) {
1304
-            return self::instance()->{$loader}($classname, $arguments);
1305
-        }
1306
-        return null;
1307
-    }
1308
-
1309
-
1310
-
1311
-    /**
1312
-     * Gets the addon by its name/slug (not classname. For that, just
1313
-     * use the classname as the property name on EE_Config::instance()->addons)
1314
-     *
1315
-     * @param string $name
1316
-     * @return EE_Addon
1317
-     */
1318
-    public function get_addon_by_name($name)
1319
-    {
1320
-        foreach ($this->addons as $addon) {
1321
-            if ($addon->name() === $name) {
1322
-                return $addon;
1323
-            }
1324
-        }
1325
-        return null;
1326
-    }
1327
-
1328
-
1329
-
1330
-    /**
1331
-     * Gets an array of all the registered addons, where the keys are their names. (ie, what each returns for their
1332
-     * name() function) They're already available on EE_Config::instance()->addons as properties, where each property's
1333
-     * name is the addon's classname. So if you just want to get the addon by classname, use
1334
-     * EE_Config::instance()->addons->{classname}
1335
-     *
1336
-     * @return EE_Addon[] where the KEYS are the addon's name()
1337
-     */
1338
-    public function get_addons_by_name()
1339
-    {
1340
-        $addons = array();
1341
-        foreach ($this->addons as $addon) {
1342
-            $addons[$addon->name()] = $addon;
1343
-        }
1344
-        return $addons;
1345
-    }
1346
-
1347
-
1348
-
1349
-    /**
1350
-     * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1351
-     * a stale copy of it around
1352
-     *
1353
-     * @param string $model_name
1354
-     * @return \EEM_Base
1355
-     * @throws \EE_Error
1356
-     */
1357
-    public function reset_model($model_name)
1358
-    {
1359
-        $model_class_name = strpos($model_name, 'EEM_') !== 0
1360
-            ? "EEM_{$model_name}"
1361
-            : $model_name;
1362
-        if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1363
-            return null;
1364
-        }
1365
-        //get that model reset it and make sure we nuke the old reference to it
1366
-        if ($this->LIB->{$model_class_name} instanceof $model_class_name
1367
-            && is_callable(
1368
-                array($model_class_name, 'reset')
1369
-            )) {
1370
-            $this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1371
-        } else {
1372
-            throw new EE_Error(sprintf(esc_html__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1373
-        }
1374
-        return $this->LIB->{$model_class_name};
1375
-    }
1376
-
1377
-
1378
-
1379
-    /**
1380
-     * Resets the registry.
1381
-     * The criteria for what gets reset is based on what can be shared between sites on the same request when
1382
-     * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1383
-     * - $_dependency_map
1384
-     * - $_class_abbreviations
1385
-     * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1386
-     * - $REQ:  Still on the same request so no need to change.
1387
-     * - $CAP: There is no site specific state in the EE_Capability class.
1388
-     * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1389
-     * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1390
-     * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1391
-     *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1392
-     *             switch or on the restore.
1393
-     * - $modules
1394
-     * - $shortcodes
1395
-     * - $widgets
1396
-     *
1397
-     * @param boolean $hard             [deprecated]
1398
-     * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1399
-     *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1400
-     *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1401
-     * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1402
-     *                                  client
1403
-     *                                  code instead can just change the model context to a different blog id if
1404
-     *                                  necessary
1405
-     * @return EE_Registry
1406
-     * @throws EE_Error
1407
-     * @throws ReflectionException
1408
-     */
1409
-    public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1410
-    {
1411
-        $instance = self::instance();
1412
-        $instance->_cache_on = true;
1413
-        // reset some "special" classes
1414
-        EEH_Activation::reset();
1415
-        $hard = apply_filters( 'FHEE__EE_Registry__reset__hard', $hard);
1416
-        $instance->CFG = EE_Config::reset($hard, $reinstantiate);
1417
-        $instance->CART = null;
1418
-        $instance->MRM = null;
1419
-        $instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1420
-        //messages reset
1421
-        EED_Messages::reset();
1422
-        //handle of objects cached on LIB
1423
-        foreach (array('LIB', 'modules') as $cache) {
1424
-            foreach ($instance->{$cache} as $class_name => $class) {
1425
-                if (self::_reset_and_unset_object($class, $reset_models)) {
1426
-                    unset($instance->{$cache}->{$class_name});
1427
-                }
1428
-            }
1429
-        }
1430
-        return $instance;
1431
-    }
1432
-
1433
-
1434
-
1435
-    /**
1436
-     * if passed object implements ResettableInterface, then call it's reset() method
1437
-     * if passed object implements InterminableInterface, then return false,
1438
-     * to indicate that it should NOT be cleared from the Registry cache
1439
-     *
1440
-     * @param      $object
1441
-     * @param bool $reset_models
1442
-     * @return bool returns true if cached object should be unset
1443
-     */
1444
-    private static function _reset_and_unset_object($object, $reset_models)
1445
-    {
1446
-        if (! is_object($object)) {
1447
-            // don't unset anything that's not an object
1448
-            return false;
1449
-        }
1450
-        if ($object instanceof EED_Module) {
1451
-            $object::reset();
1452
-            // don't unset modules
1453
-            return false;
1454
-        }
1455
-        if ($object instanceof ResettableInterface) {
1456
-            if ($object instanceof EEM_Base) {
1457
-                if ($reset_models) {
1458
-                    $object->reset();
1459
-                    return true;
1460
-                }
1461
-                return false;
1462
-            }
1463
-            $object->reset();
1464
-            return true;
1465
-        }
1466
-        if (! $object instanceof InterminableInterface) {
1467
-            return true;
1468
-        }
1469
-        return false;
1470
-    }
1471
-
1472
-
1473
-
1474
-    /**
1475
-     * Gets all the custom post type models defined
1476
-     *
1477
-     * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1478
-     */
1479
-    public function cpt_models()
1480
-    {
1481
-        $cpt_models = array();
1482
-        foreach ($this->non_abstract_db_models as $short_name => $classname) {
1483
-            if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1484
-                $cpt_models[$short_name] = $classname;
1485
-            }
1486
-        }
1487
-        return $cpt_models;
1488
-    }
1489
-
1490
-
1491
-
1492
-    /**
1493
-     * @return \EE_Config
1494
-     */
1495
-    public static function CFG()
1496
-    {
1497
-        return self::instance()->CFG;
1498
-    }
25
+	/**
26
+	 * @var EE_Registry $_instance
27
+	 */
28
+	private static $_instance;
29
+
30
+	/**
31
+	 * @var EE_Dependency_Map $_dependency_map
32
+	 */
33
+	protected $_dependency_map;
34
+
35
+	/**
36
+	 * @var array $_class_abbreviations
37
+	 */
38
+	protected $_class_abbreviations = array();
39
+
40
+	/**
41
+	 * @var CommandBusInterface $BUS
42
+	 */
43
+	public $BUS;
44
+
45
+	/**
46
+	 * @var EE_Cart $CART
47
+	 */
48
+	public $CART;
49
+
50
+	/**
51
+	 * @var EE_Config $CFG
52
+	 */
53
+	public $CFG;
54
+
55
+	/**
56
+	 * @var EE_Network_Config $NET_CFG
57
+	 */
58
+	public $NET_CFG;
59
+
60
+	/**
61
+	 * StdClass object for storing library classes in
62
+	 *
63
+	 * @var StdClass $LIB
64
+	 */
65
+	public $LIB;
66
+
67
+	/**
68
+	 * @var EE_Request_Handler $REQ
69
+	 */
70
+	public $REQ;
71
+
72
+	/**
73
+	 * @var EE_Session $SSN
74
+	 */
75
+	public $SSN;
76
+
77
+	/**
78
+	 * @since 4.5.0
79
+	 * @var EE_Capabilities $CAP
80
+	 */
81
+	public $CAP;
82
+
83
+	/**
84
+	 * @since 4.9.0
85
+	 * @var EE_Message_Resource_Manager $MRM
86
+	 */
87
+	public $MRM;
88
+
89
+
90
+	/**
91
+	 * @var Registry $AssetsRegistry
92
+	 */
93
+	public $AssetsRegistry;
94
+
95
+	/**
96
+	 * StdClass object for holding addons which have registered themselves to work with EE core
97
+	 *
98
+	 * @var EE_Addon[] $addons
99
+	 */
100
+	public $addons;
101
+
102
+	/**
103
+	 * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
104
+	 *
105
+	 * @var EEM_Base[] $models
106
+	 */
107
+	public $models = array();
108
+
109
+	/**
110
+	 * @var EED_Module[] $modules
111
+	 */
112
+	public $modules;
113
+
114
+	/**
115
+	 * @var EES_Shortcode[] $shortcodes
116
+	 */
117
+	public $shortcodes;
118
+
119
+	/**
120
+	 * @var WP_Widget[] $widgets
121
+	 */
122
+	public $widgets;
123
+
124
+	/**
125
+	 * this is an array of all implemented model names (i.e. not the parent abstract models, or models
126
+	 * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
127
+	 * Keys are model "short names" (eg "Event") as used in model relations, and values are
128
+	 * classnames (eg "EEM_Event")
129
+	 *
130
+	 * @var array $non_abstract_db_models
131
+	 */
132
+	public $non_abstract_db_models = array();
133
+
134
+
135
+	/**
136
+	 * internationalization for JS strings
137
+	 *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
138
+	 *    in js file:  var translatedString = eei18n.string_key;
139
+	 *
140
+	 * @var array $i18n_js_strings
141
+	 */
142
+	public static $i18n_js_strings = array();
143
+
144
+
145
+	/**
146
+	 * $main_file - path to espresso.php
147
+	 *
148
+	 * @var array $main_file
149
+	 */
150
+	public $main_file;
151
+
152
+	/**
153
+	 * array of ReflectionClass objects where the key is the class name
154
+	 *
155
+	 * @var ReflectionClass[] $_reflectors
156
+	 */
157
+	public $_reflectors;
158
+
159
+	/**
160
+	 * boolean flag to indicate whether or not to load/save dependencies from/to the cache
161
+	 *
162
+	 * @var boolean $_cache_on
163
+	 */
164
+	protected $_cache_on = true;
165
+
166
+
167
+
168
+	/**
169
+	 * @singleton method used to instantiate class object
170
+	 * @param  EE_Dependency_Map $dependency_map
171
+	 * @return EE_Registry instance
172
+	 * @throws InvalidArgumentException
173
+	 * @throws InvalidInterfaceException
174
+	 * @throws InvalidDataTypeException
175
+	 */
176
+	public static function instance(EE_Dependency_Map $dependency_map = null)
177
+	{
178
+		// check if class object is instantiated
179
+		if (! self::$_instance instanceof EE_Registry) {
180
+			self::$_instance = new self($dependency_map);
181
+		}
182
+		return self::$_instance;
183
+	}
184
+
185
+
186
+
187
+	/**
188
+	 * protected constructor to prevent direct creation
189
+	 *
190
+	 * @Constructor
191
+	 * @param  EE_Dependency_Map $dependency_map
192
+	 * @throws InvalidDataTypeException
193
+	 * @throws InvalidInterfaceException
194
+	 * @throws InvalidArgumentException
195
+	 */
196
+	protected function __construct(EE_Dependency_Map $dependency_map)
197
+	{
198
+		$this->_dependency_map = $dependency_map;
199
+		$this->LIB = new stdClass();
200
+		$this->addons = new stdClass();
201
+		$this->modules = new stdClass();
202
+		$this->shortcodes = new stdClass();
203
+		$this->widgets = new stdClass();
204
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
205
+	}
206
+
207
+
208
+
209
+	/**
210
+	 * initialize
211
+	 *
212
+	 * @throws EE_Error
213
+	 * @throws ReflectionException
214
+	 */
215
+	public function initialize()
216
+	{
217
+		$this->_class_abbreviations = apply_filters(
218
+			'FHEE__EE_Registry____construct___class_abbreviations',
219
+			array(
220
+				'EE_Config'                                       => 'CFG',
221
+				'EE_Session'                                      => 'SSN',
222
+				'EE_Capabilities'                                 => 'CAP',
223
+				'EE_Cart'                                         => 'CART',
224
+				'EE_Network_Config'                               => 'NET_CFG',
225
+				'EE_Request_Handler'                              => 'REQ',
226
+				'EE_Message_Resource_Manager'                     => 'MRM',
227
+				'EventEspresso\core\services\commands\CommandBus' => 'BUS',
228
+				'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
229
+			)
230
+		);
231
+		$this->load_core('Base', array(), true);
232
+		// add our request and response objects to the cache
233
+		$request_loader = $this->_dependency_map->class_loader('EE_Request');
234
+		$this->_set_cached_class(
235
+			$request_loader(),
236
+			'EE_Request'
237
+		);
238
+		$response_loader = $this->_dependency_map->class_loader('EE_Response');
239
+		$this->_set_cached_class(
240
+			$response_loader(),
241
+			'EE_Response'
242
+		);
243
+		add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
244
+	}
245
+
246
+
247
+
248
+	/**
249
+	 * @return void
250
+	 */
251
+	public function init()
252
+	{
253
+		// Get current page protocol
254
+		$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
255
+		// Output admin-ajax.php URL with same protocol as current page
256
+		self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
257
+		self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
258
+	}
259
+
260
+
261
+
262
+	/**
263
+	 * localize_i18n_js_strings
264
+	 *
265
+	 * @return string
266
+	 */
267
+	public static function localize_i18n_js_strings()
268
+	{
269
+		$i18n_js_strings = (array)self::$i18n_js_strings;
270
+		foreach ($i18n_js_strings as $key => $value) {
271
+			if (is_scalar($value)) {
272
+				$i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
273
+			}
274
+		}
275
+		return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
276
+	}
277
+
278
+
279
+
280
+	/**
281
+	 * @param mixed string | EED_Module $module
282
+	 * @throws EE_Error
283
+	 * @throws ReflectionException
284
+	 */
285
+	public function add_module($module)
286
+	{
287
+		if ($module instanceof EED_Module) {
288
+			$module_class = get_class($module);
289
+			$this->modules->{$module_class} = $module;
290
+		} else {
291
+			if (! class_exists('EE_Module_Request_Router')) {
292
+				$this->load_core('Module_Request_Router');
293
+			}
294
+			EE_Module_Request_Router::module_factory($module);
295
+		}
296
+	}
297
+
298
+
299
+
300
+	/**
301
+	 * @param string $module_name
302
+	 * @return mixed EED_Module | NULL
303
+	 */
304
+	public function get_module($module_name = '')
305
+	{
306
+		return isset($this->modules->{$module_name})
307
+			? $this->modules->{$module_name}
308
+			: null;
309
+	}
310
+
311
+
312
+
313
+	/**
314
+	 * loads core classes - must be singletons
315
+	 *
316
+	 * @param string $class_name - simple class name ie: session
317
+	 * @param mixed  $arguments
318
+	 * @param bool   $load_only
319
+	 * @return mixed
320
+	 * @throws EE_Error
321
+	 * @throws ReflectionException
322
+	 */
323
+	public function load_core($class_name, $arguments = array(), $load_only = false)
324
+	{
325
+		$core_paths = apply_filters(
326
+			'FHEE__EE_Registry__load_core__core_paths',
327
+			array(
328
+				EE_CORE,
329
+				EE_ADMIN,
330
+				EE_CPTS,
331
+				EE_CORE . 'data_migration_scripts' . DS,
332
+				EE_CORE . 'capabilities' . DS,
333
+				EE_CORE . 'request_stack' . DS,
334
+				EE_CORE . 'middleware' . DS,
335
+			)
336
+		);
337
+		// retrieve instantiated class
338
+		return $this->_load(
339
+			$core_paths,
340
+			'EE_',
341
+			$class_name,
342
+			'core',
343
+			$arguments,
344
+			true,
345
+			$load_only
346
+		);
347
+	}
348
+
349
+
350
+
351
+	/**
352
+	 * loads service classes
353
+	 *
354
+	 * @param string $class_name - simple class name ie: session
355
+	 * @param mixed  $arguments
356
+	 * @param bool   $load_only
357
+	 * @return mixed
358
+	 * @throws EE_Error
359
+	 * @throws ReflectionException
360
+	 */
361
+	public function load_service($class_name, $arguments = array(), $load_only = false)
362
+	{
363
+		$service_paths = apply_filters(
364
+			'FHEE__EE_Registry__load_service__service_paths',
365
+			array(
366
+				EE_CORE . 'services' . DS,
367
+			)
368
+		);
369
+		// retrieve instantiated class
370
+		return $this->_load(
371
+			$service_paths,
372
+			'EE_',
373
+			$class_name,
374
+			'class',
375
+			$arguments,
376
+			true,
377
+			$load_only
378
+		);
379
+	}
380
+
381
+
382
+
383
+	/**
384
+	 * loads data_migration_scripts
385
+	 *
386
+	 * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
387
+	 * @param mixed  $arguments
388
+	 * @return EE_Data_Migration_Script_Base|mixed
389
+	 * @throws EE_Error
390
+	 * @throws ReflectionException
391
+	 */
392
+	public function load_dms($class_name, $arguments = array())
393
+	{
394
+		// retrieve instantiated class
395
+		return $this->_load(
396
+			EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
397
+			'EE_DMS_',
398
+			$class_name,
399
+			'dms',
400
+			$arguments,
401
+			false
402
+		);
403
+	}
404
+
405
+
406
+
407
+	/**
408
+	 * loads object creating classes - must be singletons
409
+	 *
410
+	 * @param string $class_name - simple class name ie: attendee
411
+	 * @param mixed  $arguments  - an array of arguments to pass to the class
412
+	 * @param bool   $from_db    - deprecated
413
+	 * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
414
+	 *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
415
+	 * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
416
+	 *                           (default)
417
+	 * @return EE_Base_Class | bool
418
+	 * @throws EE_Error
419
+	 * @throws ReflectionException
420
+	 */
421
+	public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
422
+	{
423
+		$paths = apply_filters(
424
+			'FHEE__EE_Registry__load_class__paths', array(
425
+			EE_CORE,
426
+			EE_CLASSES,
427
+			EE_BUSINESS,
428
+		)
429
+		);
430
+		// retrieve instantiated class
431
+		return $this->_load(
432
+			$paths,
433
+			'EE_',
434
+			$class_name,
435
+			'class',
436
+			$arguments,
437
+			$cache,
438
+			$load_only
439
+		);
440
+	}
441
+
442
+
443
+
444
+	/**
445
+	 * loads helper classes - must be singletons
446
+	 *
447
+	 * @param string $class_name - simple class name ie: price
448
+	 * @param mixed  $arguments
449
+	 * @param bool   $load_only
450
+	 * @return EEH_Base | bool
451
+	 * @throws EE_Error
452
+	 * @throws ReflectionException
453
+	 */
454
+	public function load_helper($class_name, $arguments = array(), $load_only = true)
455
+	{
456
+		// todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
457
+		$helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
458
+		// retrieve instantiated class
459
+		return $this->_load(
460
+			$helper_paths,
461
+			'EEH_',
462
+			$class_name,
463
+			'helper',
464
+			$arguments,
465
+			true,
466
+			$load_only
467
+		);
468
+	}
469
+
470
+
471
+
472
+	/**
473
+	 * loads core classes - must be singletons
474
+	 *
475
+	 * @param string $class_name - simple class name ie: session
476
+	 * @param mixed  $arguments
477
+	 * @param bool   $load_only
478
+	 * @param bool   $cache      whether to cache the object or not.
479
+	 * @return mixed
480
+	 * @throws EE_Error
481
+	 * @throws ReflectionException
482
+	 */
483
+	public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
484
+	{
485
+		$paths = array(
486
+			EE_LIBRARIES,
487
+			EE_LIBRARIES . 'messages' . DS,
488
+			EE_LIBRARIES . 'shortcodes' . DS,
489
+			EE_LIBRARIES . 'qtips' . DS,
490
+			EE_LIBRARIES . 'payment_methods' . DS,
491
+		);
492
+		// retrieve instantiated class
493
+		return $this->_load(
494
+			$paths,
495
+			'EE_',
496
+			$class_name,
497
+			'lib',
498
+			$arguments,
499
+			$cache,
500
+			$load_only
501
+		);
502
+	}
503
+
504
+
505
+
506
+	/**
507
+	 * loads model classes - must be singletons
508
+	 *
509
+	 * @param string $class_name - simple class name ie: price
510
+	 * @param mixed  $arguments
511
+	 * @param bool   $load_only
512
+	 * @return EEM_Base | bool
513
+	 * @throws EE_Error
514
+	 * @throws ReflectionException
515
+	 */
516
+	public function load_model($class_name, $arguments = array(), $load_only = false)
517
+	{
518
+		$paths = apply_filters(
519
+			'FHEE__EE_Registry__load_model__paths', array(
520
+			EE_MODELS,
521
+			EE_CORE,
522
+		)
523
+		);
524
+		// retrieve instantiated class
525
+		return $this->_load(
526
+			$paths,
527
+			'EEM_',
528
+			$class_name,
529
+			'model',
530
+			$arguments,
531
+			true,
532
+			$load_only
533
+		);
534
+	}
535
+
536
+
537
+
538
+	/**
539
+	 * loads model classes - must be singletons
540
+	 *
541
+	 * @param string $class_name - simple class name ie: price
542
+	 * @param mixed  $arguments
543
+	 * @param bool   $load_only
544
+	 * @return mixed | bool
545
+	 * @throws EE_Error
546
+	 * @throws ReflectionException
547
+	 */
548
+	public function load_model_class($class_name, $arguments = array(), $load_only = true)
549
+	{
550
+		$paths = array(
551
+			EE_MODELS . 'fields' . DS,
552
+			EE_MODELS . 'helpers' . DS,
553
+			EE_MODELS . 'relations' . DS,
554
+			EE_MODELS . 'strategies' . DS,
555
+		);
556
+		// retrieve instantiated class
557
+		return $this->_load(
558
+			$paths,
559
+			'EE_',
560
+			$class_name,
561
+			'',
562
+			$arguments,
563
+			true,
564
+			$load_only
565
+		);
566
+	}
567
+
568
+
569
+
570
+	/**
571
+	 * Determines if $model_name is the name of an actual EE model.
572
+	 *
573
+	 * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
574
+	 * @return boolean
575
+	 */
576
+	public function is_model_name($model_name)
577
+	{
578
+		return isset($this->models[$model_name]);
579
+	}
580
+
581
+
582
+
583
+	/**
584
+	 * generic class loader
585
+	 *
586
+	 * @param string $path_to_file - directory path to file location, not including filename
587
+	 * @param string $file_name    - file name  ie:  my_file.php, including extension
588
+	 * @param string $type         - file type - core? class? helper? model?
589
+	 * @param mixed  $arguments
590
+	 * @param bool   $load_only
591
+	 * @return mixed
592
+	 * @throws EE_Error
593
+	 * @throws ReflectionException
594
+	 */
595
+	public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
596
+	{
597
+		// retrieve instantiated class
598
+		return $this->_load(
599
+			$path_to_file,
600
+			'',
601
+			$file_name,
602
+			$type,
603
+			$arguments,
604
+			true,
605
+			$load_only
606
+		);
607
+	}
608
+
609
+
610
+
611
+	/**
612
+	 * @param string $path_to_file - directory path to file location, not including filename
613
+	 * @param string $class_name   - full class name  ie:  My_Class
614
+	 * @param string $type         - file type - core? class? helper? model?
615
+	 * @param mixed  $arguments
616
+	 * @param bool   $load_only
617
+	 * @return bool|EE_Addon|object
618
+	 * @throws EE_Error
619
+	 * @throws ReflectionException
620
+	 */
621
+	public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
622
+	{
623
+		// retrieve instantiated class
624
+		return $this->_load(
625
+			$path_to_file,
626
+			'addon',
627
+			$class_name,
628
+			$type,
629
+			$arguments,
630
+			true,
631
+			$load_only
632
+		);
633
+	}
634
+
635
+
636
+
637
+	/**
638
+	 * instantiates, caches, and automatically resolves dependencies
639
+	 * for classes that use a Fully Qualified Class Name.
640
+	 * if the class is not capable of being loaded using PSR-4 autoloading,
641
+	 * then you need to use one of the existing load_*() methods
642
+	 * which can resolve the classname and filepath from the passed arguments
643
+	 *
644
+	 * @param bool|string $class_name   Fully Qualified Class Name
645
+	 * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
646
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
647
+	 * @param bool        $from_db      some classes are instantiated from the db
648
+	 *                                  and thus call a different method to instantiate
649
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
650
+	 * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
651
+	 * @return bool|null|mixed          null = failure to load or instantiate class object.
652
+	 *                                  object = class loaded and instantiated successfully.
653
+	 *                                  bool = fail or success when $load_only is true
654
+	 * @throws EE_Error
655
+	 * @throws ReflectionException
656
+	 */
657
+	public function create(
658
+		$class_name = false,
659
+		$arguments = array(),
660
+		$cache = true,
661
+		$load_only = false,
662
+		$addon = false
663
+	) {
664
+		$class_name = ltrim($class_name, '\\');
665
+		$class_name = $this->_dependency_map->get_alias($class_name);
666
+		if (! class_exists($class_name)) {
667
+			// maybe the class is registered with a preceding \
668
+			$class_name = strpos($class_name, '\\') !== 0
669
+				? '\\' . $class_name
670
+				: $class_name;
671
+			// still doesn't exist ?
672
+			if (! class_exists($class_name)) {
673
+				return null;
674
+			}
675
+		}
676
+		// if we're only loading the class and it already exists, then let's just return true immediately
677
+		if ($load_only) {
678
+			return true;
679
+		}
680
+		$addon = $addon
681
+			? 'addon'
682
+			: '';
683
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
684
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
685
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
686
+		if ($this->_cache_on && $cache && ! $load_only) {
687
+			// return object if it's already cached
688
+			$cached_class = $this->_get_cached_class($class_name, $addon);
689
+			if ($cached_class !== null) {
690
+				return $cached_class;
691
+			}
692
+		}
693
+		// obtain the loader method from the dependency map
694
+		$loader = $this->_dependency_map->class_loader($class_name);
695
+		// instantiate the requested object
696
+		if ($loader instanceof Closure) {
697
+			$class_obj = $loader($arguments);
698
+		} else if ($loader && method_exists($this, $loader)) {
699
+			$class_obj = $this->{$loader}($class_name, $arguments);
700
+		} else {
701
+			$class_obj = $this->_create_object($class_name, $arguments, $addon);
702
+		}
703
+		if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
704
+			// save it for later... kinda like gum  { : $
705
+			$this->_set_cached_class($class_obj, $class_name, $addon);
706
+		}
707
+		$this->_cache_on = true;
708
+		return $class_obj;
709
+	}
710
+
711
+
712
+
713
+	/**
714
+	 * instantiates, caches, and injects dependencies for classes
715
+	 *
716
+	 * @param array       $file_paths   an array of paths to folders to look in
717
+	 * @param string      $class_prefix EE  or EEM or... ???
718
+	 * @param bool|string $class_name   $class name
719
+	 * @param string      $type         file type - core? class? helper? model?
720
+	 * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
721
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
722
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
723
+	 * @return bool|null|object null = failure to load or instantiate class object.
724
+	 *                                  object = class loaded and instantiated successfully.
725
+	 *                                  bool = fail or success when $load_only is true
726
+	 * @throws EE_Error
727
+	 * @throws ReflectionException
728
+	 */
729
+	protected function _load(
730
+		$file_paths = array(),
731
+		$class_prefix = 'EE_',
732
+		$class_name = false,
733
+		$type = 'class',
734
+		$arguments = array(),
735
+		$cache = true,
736
+		$load_only = false
737
+	) {
738
+		$class_name = ltrim($class_name, '\\');
739
+		// strip php file extension
740
+		$class_name = str_replace('.php', '', trim($class_name));
741
+		// does the class have a prefix ?
742
+		if (! empty($class_prefix) && $class_prefix !== 'addon') {
743
+			// make sure $class_prefix is uppercase
744
+			$class_prefix = strtoupper(trim($class_prefix));
745
+			// add class prefix ONCE!!!
746
+			$class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
747
+		}
748
+		$class_name = $this->_dependency_map->get_alias($class_name);
749
+		$class_exists = class_exists($class_name);
750
+		// if we're only loading the class and it already exists, then let's just return true immediately
751
+		if ($load_only && $class_exists) {
752
+			return true;
753
+		}
754
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
755
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
756
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
757
+		if ($this->_cache_on && $cache && ! $load_only) {
758
+			// return object if it's already cached
759
+			$cached_class = $this->_get_cached_class($class_name, $class_prefix);
760
+			if ($cached_class !== null) {
761
+				return $cached_class;
762
+			}
763
+		}
764
+		// if the class doesn't already exist.. then we need to try and find the file and load it
765
+		if (! $class_exists) {
766
+			// get full path to file
767
+			$path = $this->_resolve_path($class_name, $type, $file_paths);
768
+			// load the file
769
+			$loaded = $this->_require_file($path, $class_name, $type, $file_paths);
770
+			// if loading failed, or we are only loading a file but NOT instantiating an object
771
+			if (! $loaded || $load_only) {
772
+				// return boolean if only loading, or null if an object was expected
773
+				return $load_only
774
+					? $loaded
775
+					: null;
776
+			}
777
+		}
778
+		// instantiate the requested object
779
+		$class_obj = $this->_create_object($class_name, $arguments, $type);
780
+		if ($this->_cache_on && $cache) {
781
+			// save it for later... kinda like gum  { : $
782
+			$this->_set_cached_class($class_obj, $class_name, $class_prefix);
783
+		}
784
+		$this->_cache_on = true;
785
+		return $class_obj;
786
+	}
787
+
788
+
789
+
790
+	/**
791
+	 * @param string $class_name
792
+	 * @param string $default have to specify something, but not anything that will conflict
793
+	 * @return mixed|string
794
+	 */
795
+	protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
796
+	{
797
+		return isset($this->_class_abbreviations[$class_name])
798
+			? $this->_class_abbreviations[$class_name]
799
+			: $default;
800
+	}
801
+
802
+	/**
803
+	 * attempts to find a cached version of the requested class
804
+	 * by looking in the following places:
805
+	 *        $this->{$class_abbreviation}            ie:    $this->CART
806
+	 *        $this->{$class_name}                        ie:    $this->Some_Class
807
+	 *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
808
+	 *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
809
+	 *
810
+	 * @param string $class_name
811
+	 * @param string $class_prefix
812
+	 * @return mixed
813
+	 */
814
+	protected function _get_cached_class($class_name, $class_prefix = '')
815
+	{
816
+		if ($class_name === 'EE_Registry') {
817
+			return $this;
818
+		}
819
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
820
+		$class_name = str_replace('\\', '_', $class_name);
821
+		// check if class has already been loaded, and return it if it has been
822
+		if (isset($this->{$class_abbreviation})) {
823
+			return $this->{$class_abbreviation};
824
+		}
825
+		if (isset ($this->{$class_name})) {
826
+			return $this->{$class_name};
827
+		}
828
+		if (isset ($this->LIB->{$class_name})) {
829
+			return $this->LIB->{$class_name};
830
+		}
831
+		if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
832
+			return $this->addons->{$class_name};
833
+		}
834
+		return null;
835
+	}
836
+
837
+
838
+
839
+	/**
840
+	 * removes a cached version of the requested class
841
+	 *
842
+	 * @param string  $class_name
843
+	 * @param boolean $addon
844
+	 * @return boolean
845
+	 */
846
+	public function clear_cached_class($class_name, $addon = false)
847
+	{
848
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
849
+		$class_name = str_replace('\\', '_', $class_name);
850
+		// check if class has already been loaded, and return it if it has been
851
+		if (isset($this->{$class_abbreviation})) {
852
+			$this->{$class_abbreviation} = null;
853
+			return true;
854
+		}
855
+		if (isset($this->{$class_name})) {
856
+			$this->{$class_name} = null;
857
+			return true;
858
+		}
859
+		if (isset($this->LIB->{$class_name})) {
860
+			unset($this->LIB->{$class_name});
861
+			return true;
862
+		}
863
+		if ($addon && isset($this->addons->{$class_name})) {
864
+			unset($this->addons->{$class_name});
865
+			return true;
866
+		}
867
+		return false;
868
+	}
869
+
870
+
871
+
872
+	/**
873
+	 * attempts to find a full valid filepath for the requested class.
874
+	 * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
875
+	 * then returns that path if the target file has been found and is readable
876
+	 *
877
+	 * @param string $class_name
878
+	 * @param string $type
879
+	 * @param array  $file_paths
880
+	 * @return string | bool
881
+	 */
882
+	protected function _resolve_path($class_name, $type = '', $file_paths = array())
883
+	{
884
+		// make sure $file_paths is an array
885
+		$file_paths = is_array($file_paths)
886
+			? $file_paths
887
+			: array($file_paths);
888
+		// cycle thru paths
889
+		foreach ($file_paths as $key => $file_path) {
890
+			// convert all separators to proper DS, if no filepath, then use EE_CLASSES
891
+			$file_path = $file_path
892
+				? str_replace(array('/', '\\'), DS, $file_path)
893
+				: EE_CLASSES;
894
+			// prep file type
895
+			$type = ! empty($type)
896
+				? trim($type, '.') . '.'
897
+				: '';
898
+			// build full file path
899
+			$file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
900
+			//does the file exist and can be read ?
901
+			if (is_readable($file_paths[$key])) {
902
+				return $file_paths[$key];
903
+			}
904
+		}
905
+		return false;
906
+	}
907
+
908
+
909
+
910
+	/**
911
+	 * basically just performs a require_once()
912
+	 * but with some error handling
913
+	 *
914
+	 * @param  string $path
915
+	 * @param  string $class_name
916
+	 * @param  string $type
917
+	 * @param  array  $file_paths
918
+	 * @return bool
919
+	 * @throws EE_Error
920
+	 * @throws ReflectionException
921
+	 */
922
+	protected function _require_file($path, $class_name, $type = '', $file_paths = array())
923
+	{
924
+		// don't give up! you gotta...
925
+		try {
926
+			//does the file exist and can it be read ?
927
+			if (! $path) {
928
+				// so sorry, can't find the file
929
+				throw new EE_Error (
930
+					sprintf(
931
+						esc_html__(
932
+							'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
933
+							'event_espresso'
934
+						),
935
+						trim($type, '.'),
936
+						$class_name,
937
+						'<br />' . implode(',<br />', $file_paths)
938
+					)
939
+				);
940
+			}
941
+			// get the file
942
+			require_once($path);
943
+			// if the class isn't already declared somewhere
944
+			if (class_exists($class_name, false) === false) {
945
+				// so sorry, not a class
946
+				throw new EE_Error(
947
+					sprintf(
948
+						esc_html__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
949
+						$type,
950
+						$path,
951
+						$class_name
952
+					)
953
+				);
954
+			}
955
+		} catch (EE_Error $e) {
956
+			$e->get_error();
957
+			return false;
958
+		}
959
+		return true;
960
+	}
961
+
962
+
963
+
964
+	/**
965
+	 * _create_object
966
+	 * Attempts to instantiate the requested class via any of the
967
+	 * commonly used instantiation methods employed throughout EE.
968
+	 * The priority for instantiation is as follows:
969
+	 *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
970
+	 *        - model objects via their 'new_instance_from_db' method
971
+	 *        - model objects via their 'new_instance' method
972
+	 *        - "singleton" classes" via their 'instance' method
973
+	 *    - standard instantiable classes via their __constructor
974
+	 * Prior to instantiation, if the classname exists in the dependency_map,
975
+	 * then the constructor for the requested class will be examined to determine
976
+	 * if any dependencies exist, and if they can be injected.
977
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
978
+	 *
979
+	 * @param string $class_name
980
+	 * @param array  $arguments
981
+	 * @param string $type
982
+	 * @param bool   $from_db
983
+	 * @return null|object
984
+	 * @throws EE_Error
985
+	 * @throws ReflectionException
986
+	 */
987
+	protected function _create_object($class_name, $arguments = array(), $type = '')
988
+	{
989
+		$class_obj = null;
990
+		$instantiation_mode = '0) none';
991
+		// don't give up! you gotta...
992
+		try {
993
+			// create reflection
994
+			$reflector = $this->get_ReflectionClass($class_name);
995
+			// make sure arguments are an array
996
+			$arguments = is_array($arguments)
997
+				? $arguments
998
+				: array($arguments);
999
+			// and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1000
+			// else wrap it in an additional array so that it doesn't get split into multiple parameters
1001
+			$arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1002
+				? $arguments
1003
+				: array($arguments);
1004
+			// attempt to inject dependencies ?
1005
+			if ($this->_dependency_map->has($class_name)) {
1006
+				$arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1007
+			}
1008
+			// instantiate the class if possible
1009
+			if ($reflector->isAbstract()) {
1010
+				// nothing to instantiate, loading file was enough
1011
+				// does not throw an exception so $instantiation_mode is unused
1012
+				// $instantiation_mode = "1) no constructor abstract class";
1013
+				$class_obj = true;
1014
+			} else if (empty($arguments) && $reflector->getConstructor() === null && $reflector->isInstantiable()) {
1015
+				// no constructor = static methods only... nothing to instantiate, loading file was enough
1016
+				$instantiation_mode = '2) no constructor but instantiable';
1017
+				$class_obj = $reflector->newInstance();
1018
+			} else if (method_exists($class_name, 'new_instance')) {
1019
+				$instantiation_mode = '4) new_instance()';
1020
+				$class_obj = call_user_func_array(array($class_name, 'new_instance'), $arguments);
1021
+			} else if (method_exists($class_name, 'instance')) {
1022
+				$instantiation_mode = '5) instance()';
1023
+				$class_obj = call_user_func_array(array($class_name, 'instance'), $arguments);
1024
+			} else if ($reflector->isInstantiable()) {
1025
+				$instantiation_mode = '6) constructor';
1026
+				$class_obj = $reflector->newInstanceArgs($arguments);
1027
+			} else {
1028
+				// heh ? something's not right !
1029
+				throw new EE_Error(
1030
+					sprintf(
1031
+						esc_html__('The %s file %s could not be instantiated.', 'event_espresso'),
1032
+						$type,
1033
+						$class_name
1034
+					)
1035
+				);
1036
+			}
1037
+		} catch (Exception $e) {
1038
+			if (! $e instanceof EE_Error) {
1039
+				$e = new EE_Error(
1040
+					sprintf(
1041
+						esc_html__(
1042
+							'The following error occurred while attempting to instantiate "%1$s": %2$s %3$s %2$s instantiation mode : %4$s',
1043
+							'event_espresso'
1044
+						),
1045
+						$class_name,
1046
+						'<br />',
1047
+						$e->getMessage(),
1048
+						$instantiation_mode
1049
+					)
1050
+				);
1051
+			}
1052
+			$e->get_error();
1053
+		}
1054
+		return $class_obj;
1055
+	}
1056
+
1057
+
1058
+
1059
+	/**
1060
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1061
+	 * @param array $array
1062
+	 * @return bool
1063
+	 */
1064
+	protected function _array_is_numerically_and_sequentially_indexed(array $array)
1065
+	{
1066
+		return ! empty($array)
1067
+			? array_keys($array) === range(0, count($array) - 1)
1068
+			: true;
1069
+	}
1070
+
1071
+
1072
+
1073
+	/**
1074
+	 * getReflectionClass
1075
+	 * checks if a ReflectionClass object has already been generated for a class
1076
+	 * and returns that instead of creating a new one
1077
+	 *
1078
+	 * @param string $class_name
1079
+	 * @return ReflectionClass
1080
+	 * @throws ReflectionException
1081
+	 */
1082
+	public function get_ReflectionClass($class_name)
1083
+	{
1084
+		if (
1085
+			! isset($this->_reflectors[$class_name])
1086
+			|| ! $this->_reflectors[$class_name] instanceof ReflectionClass
1087
+		) {
1088
+			$this->_reflectors[$class_name] = new ReflectionClass($class_name);
1089
+		}
1090
+		return $this->_reflectors[$class_name];
1091
+	}
1092
+
1093
+
1094
+
1095
+	/**
1096
+	 * _resolve_dependencies
1097
+	 * examines the constructor for the requested class to determine
1098
+	 * if any dependencies exist, and if they can be injected.
1099
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1100
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
1101
+	 * For example:
1102
+	 *        if attempting to load a class "Foo" with the following constructor:
1103
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
1104
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
1105
+	 *        but only IF they are NOT already present in the incoming arguments array,
1106
+	 *        and the correct classes can be loaded
1107
+	 *
1108
+	 * @param ReflectionClass $reflector
1109
+	 * @param string          $class_name
1110
+	 * @param array           $arguments
1111
+	 * @return array
1112
+	 * @throws EE_Error
1113
+	 * @throws ReflectionException
1114
+	 */
1115
+	protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1116
+	{
1117
+		// let's examine the constructor
1118
+		$constructor = $reflector->getConstructor();
1119
+		// whu? huh? nothing?
1120
+		if (! $constructor) {
1121
+			return $arguments;
1122
+		}
1123
+		// get constructor parameters
1124
+		$params = $constructor->getParameters();
1125
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1126
+		$argument_keys = array_keys($arguments);
1127
+		// now loop thru all of the constructors expected parameters
1128
+		foreach ($params as $index => $param) {
1129
+			// is this a dependency for a specific class ?
1130
+			$param_class = $param->getClass()
1131
+				? $param->getClass()->name
1132
+				: null;
1133
+			// BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1134
+			$param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1135
+				? $this->_dependency_map->get_alias($param_class, $class_name)
1136
+				: $param_class;
1137
+			if (
1138
+				// param is not even a class
1139
+				$param_class === null
1140
+				// and something already exists in the incoming arguments for this param
1141
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1142
+			) {
1143
+				// so let's skip this argument and move on to the next
1144
+				continue;
1145
+			}
1146
+			if (
1147
+				// parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1148
+				$param_class !== null
1149
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1150
+				&& $arguments[$argument_keys[$index]] instanceof $param_class
1151
+			) {
1152
+				// skip this argument and move on to the next
1153
+				continue;
1154
+			}
1155
+			if (
1156
+				// parameter is type hinted as a class, and should be injected
1157
+				$param_class !== null
1158
+				&& $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1159
+			) {
1160
+				$arguments = $this->_resolve_dependency(
1161
+					$class_name,
1162
+					$param_class,
1163
+					$arguments,
1164
+					$index,
1165
+					$argument_keys
1166
+				);
1167
+			} else {
1168
+				try {
1169
+					$arguments[$index] = $param->isDefaultValueAvailable()
1170
+						? $param->getDefaultValue()
1171
+						: null;
1172
+				} catch (ReflectionException $e) {
1173
+					throw new ReflectionException(
1174
+						sprintf(
1175
+							esc_html__('%1$s for parameter "$%2$s"', 'event_espresso'),
1176
+							$e->getMessage(),
1177
+							$param->getName()
1178
+						)
1179
+					);
1180
+				}
1181
+			}
1182
+		}
1183
+		return $arguments;
1184
+	}
1185
+
1186
+
1187
+
1188
+	/**
1189
+	 * @param string $class_name
1190
+	 * @param string $param_class
1191
+	 * @param array  $arguments
1192
+	 * @param mixed  $index
1193
+	 * @param array  $argument_keys
1194
+	 * @return array
1195
+	 * @throws EE_Error
1196
+	 * @throws ReflectionException
1197
+	 * @throws InvalidArgumentException
1198
+	 * @throws InvalidInterfaceException
1199
+	 * @throws InvalidDataTypeException
1200
+	 */
1201
+	protected function _resolve_dependency($class_name, $param_class, $arguments, $index, array $argument_keys)
1202
+	{
1203
+		$dependency = null;
1204
+		// should dependency be loaded from cache ?
1205
+		$cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1206
+			$class_name,
1207
+			$param_class
1208
+		);
1209
+		$cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1210
+		// we might have a dependency...
1211
+		// let's MAYBE try and find it in our cache if that's what's been requested
1212
+		$cached_class = $cache_on
1213
+			? $this->_get_cached_class($param_class)
1214
+			: null;
1215
+		// and grab it if it exists
1216
+		if ($cached_class instanceof $param_class) {
1217
+			$dependency = $cached_class;
1218
+		} else if ($param_class !== $class_name) {
1219
+			// obtain the loader method from the dependency map
1220
+			$loader = $this->_dependency_map->class_loader($param_class);
1221
+			// is loader a custom closure ?
1222
+			if ($loader instanceof Closure) {
1223
+				$dependency = $loader($arguments);
1224
+			} else {
1225
+				// set the cache on property for the recursive loading call
1226
+				$this->_cache_on = $cache_on;
1227
+				// if not, then let's try and load it via the registry
1228
+				if ($loader && method_exists($this, $loader)) {
1229
+					$dependency = $this->{$loader}($param_class);
1230
+				} else {
1231
+					$dependency = LoaderFactory::getLoader()->load(
1232
+						$param_class,
1233
+						array(),
1234
+						$cache_on
1235
+					);
1236
+				}
1237
+			}
1238
+		}
1239
+		// did we successfully find the correct dependency ?
1240
+		if ($dependency instanceof $param_class) {
1241
+			// then let's inject it into the incoming array of arguments at the correct location
1242
+			$arguments[$index] = $dependency;
1243
+		}
1244
+		return $arguments;
1245
+	}
1246
+
1247
+
1248
+
1249
+	/**
1250
+	 * _set_cached_class
1251
+	 * attempts to cache the instantiated class locally
1252
+	 * in one of the following places, in the following order:
1253
+	 *        $this->{class_abbreviation}   ie:    $this->CART
1254
+	 *        $this->{$class_name}          ie:    $this->Some_Class
1255
+	 *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1256
+	 *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1257
+	 *
1258
+	 * @param object $class_obj
1259
+	 * @param string $class_name
1260
+	 * @param string $class_prefix
1261
+	 * @return void
1262
+	 */
1263
+	protected function _set_cached_class($class_obj, $class_name, $class_prefix = '')
1264
+	{
1265
+		if ($class_name === 'EE_Registry' || empty($class_obj)) {
1266
+			return;
1267
+		}
1268
+		// return newly instantiated class
1269
+		$class_abbreviation = $this->get_class_abbreviation($class_name, '');
1270
+		if ($class_abbreviation) {
1271
+			$this->{$class_abbreviation} = $class_obj;
1272
+			return;
1273
+		}
1274
+		$class_name = str_replace('\\', '_', $class_name);
1275
+		if (property_exists($this, $class_name)) {
1276
+			$this->{$class_name} = $class_obj;
1277
+			return;
1278
+		}
1279
+		if ($class_prefix === 'addon') {
1280
+			$this->addons->{$class_name} = $class_obj;
1281
+			return;
1282
+		}
1283
+		$this->LIB->{$class_name} = $class_obj;
1284
+	}
1285
+
1286
+
1287
+
1288
+	/**
1289
+	 * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1290
+	 *
1291
+	 * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1292
+	 *                          in the EE_Dependency_Map::$_class_loaders array,
1293
+	 *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1294
+	 * @param array  $arguments
1295
+	 * @return object
1296
+	 */
1297
+	public static function factory($classname, $arguments = array())
1298
+	{
1299
+		$loader = self::instance()->_dependency_map->class_loader($classname);
1300
+		if ($loader instanceof Closure) {
1301
+			return $loader($arguments);
1302
+		}
1303
+		if (method_exists(self::instance(), $loader)) {
1304
+			return self::instance()->{$loader}($classname, $arguments);
1305
+		}
1306
+		return null;
1307
+	}
1308
+
1309
+
1310
+
1311
+	/**
1312
+	 * Gets the addon by its name/slug (not classname. For that, just
1313
+	 * use the classname as the property name on EE_Config::instance()->addons)
1314
+	 *
1315
+	 * @param string $name
1316
+	 * @return EE_Addon
1317
+	 */
1318
+	public function get_addon_by_name($name)
1319
+	{
1320
+		foreach ($this->addons as $addon) {
1321
+			if ($addon->name() === $name) {
1322
+				return $addon;
1323
+			}
1324
+		}
1325
+		return null;
1326
+	}
1327
+
1328
+
1329
+
1330
+	/**
1331
+	 * Gets an array of all the registered addons, where the keys are their names. (ie, what each returns for their
1332
+	 * name() function) They're already available on EE_Config::instance()->addons as properties, where each property's
1333
+	 * name is the addon's classname. So if you just want to get the addon by classname, use
1334
+	 * EE_Config::instance()->addons->{classname}
1335
+	 *
1336
+	 * @return EE_Addon[] where the KEYS are the addon's name()
1337
+	 */
1338
+	public function get_addons_by_name()
1339
+	{
1340
+		$addons = array();
1341
+		foreach ($this->addons as $addon) {
1342
+			$addons[$addon->name()] = $addon;
1343
+		}
1344
+		return $addons;
1345
+	}
1346
+
1347
+
1348
+
1349
+	/**
1350
+	 * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1351
+	 * a stale copy of it around
1352
+	 *
1353
+	 * @param string $model_name
1354
+	 * @return \EEM_Base
1355
+	 * @throws \EE_Error
1356
+	 */
1357
+	public function reset_model($model_name)
1358
+	{
1359
+		$model_class_name = strpos($model_name, 'EEM_') !== 0
1360
+			? "EEM_{$model_name}"
1361
+			: $model_name;
1362
+		if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1363
+			return null;
1364
+		}
1365
+		//get that model reset it and make sure we nuke the old reference to it
1366
+		if ($this->LIB->{$model_class_name} instanceof $model_class_name
1367
+			&& is_callable(
1368
+				array($model_class_name, 'reset')
1369
+			)) {
1370
+			$this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1371
+		} else {
1372
+			throw new EE_Error(sprintf(esc_html__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1373
+		}
1374
+		return $this->LIB->{$model_class_name};
1375
+	}
1376
+
1377
+
1378
+
1379
+	/**
1380
+	 * Resets the registry.
1381
+	 * The criteria for what gets reset is based on what can be shared between sites on the same request when
1382
+	 * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1383
+	 * - $_dependency_map
1384
+	 * - $_class_abbreviations
1385
+	 * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1386
+	 * - $REQ:  Still on the same request so no need to change.
1387
+	 * - $CAP: There is no site specific state in the EE_Capability class.
1388
+	 * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1389
+	 * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1390
+	 * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1391
+	 *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1392
+	 *             switch or on the restore.
1393
+	 * - $modules
1394
+	 * - $shortcodes
1395
+	 * - $widgets
1396
+	 *
1397
+	 * @param boolean $hard             [deprecated]
1398
+	 * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1399
+	 *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1400
+	 *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1401
+	 * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1402
+	 *                                  client
1403
+	 *                                  code instead can just change the model context to a different blog id if
1404
+	 *                                  necessary
1405
+	 * @return EE_Registry
1406
+	 * @throws EE_Error
1407
+	 * @throws ReflectionException
1408
+	 */
1409
+	public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1410
+	{
1411
+		$instance = self::instance();
1412
+		$instance->_cache_on = true;
1413
+		// reset some "special" classes
1414
+		EEH_Activation::reset();
1415
+		$hard = apply_filters( 'FHEE__EE_Registry__reset__hard', $hard);
1416
+		$instance->CFG = EE_Config::reset($hard, $reinstantiate);
1417
+		$instance->CART = null;
1418
+		$instance->MRM = null;
1419
+		$instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1420
+		//messages reset
1421
+		EED_Messages::reset();
1422
+		//handle of objects cached on LIB
1423
+		foreach (array('LIB', 'modules') as $cache) {
1424
+			foreach ($instance->{$cache} as $class_name => $class) {
1425
+				if (self::_reset_and_unset_object($class, $reset_models)) {
1426
+					unset($instance->{$cache}->{$class_name});
1427
+				}
1428
+			}
1429
+		}
1430
+		return $instance;
1431
+	}
1432
+
1433
+
1434
+
1435
+	/**
1436
+	 * if passed object implements ResettableInterface, then call it's reset() method
1437
+	 * if passed object implements InterminableInterface, then return false,
1438
+	 * to indicate that it should NOT be cleared from the Registry cache
1439
+	 *
1440
+	 * @param      $object
1441
+	 * @param bool $reset_models
1442
+	 * @return bool returns true if cached object should be unset
1443
+	 */
1444
+	private static function _reset_and_unset_object($object, $reset_models)
1445
+	{
1446
+		if (! is_object($object)) {
1447
+			// don't unset anything that's not an object
1448
+			return false;
1449
+		}
1450
+		if ($object instanceof EED_Module) {
1451
+			$object::reset();
1452
+			// don't unset modules
1453
+			return false;
1454
+		}
1455
+		if ($object instanceof ResettableInterface) {
1456
+			if ($object instanceof EEM_Base) {
1457
+				if ($reset_models) {
1458
+					$object->reset();
1459
+					return true;
1460
+				}
1461
+				return false;
1462
+			}
1463
+			$object->reset();
1464
+			return true;
1465
+		}
1466
+		if (! $object instanceof InterminableInterface) {
1467
+			return true;
1468
+		}
1469
+		return false;
1470
+	}
1471
+
1472
+
1473
+
1474
+	/**
1475
+	 * Gets all the custom post type models defined
1476
+	 *
1477
+	 * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1478
+	 */
1479
+	public function cpt_models()
1480
+	{
1481
+		$cpt_models = array();
1482
+		foreach ($this->non_abstract_db_models as $short_name => $classname) {
1483
+			if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1484
+				$cpt_models[$short_name] = $classname;
1485
+			}
1486
+		}
1487
+		return $cpt_models;
1488
+	}
1489
+
1490
+
1491
+
1492
+	/**
1493
+	 * @return \EE_Config
1494
+	 */
1495
+	public static function CFG()
1496
+	{
1497
+		return self::instance()->CFG;
1498
+	}
1499 1499
 
1500 1500
 
1501 1501
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
     public static function instance(EE_Dependency_Map $dependency_map = null)
177 177
     {
178 178
         // check if class object is instantiated
179
-        if (! self::$_instance instanceof EE_Registry) {
179
+        if ( ! self::$_instance instanceof EE_Registry) {
180 180
             self::$_instance = new self($dependency_map);
181 181
         }
182 182
         return self::$_instance;
@@ -266,13 +266,13 @@  discard block
 block discarded – undo
266 266
      */
267 267
     public static function localize_i18n_js_strings()
268 268
     {
269
-        $i18n_js_strings = (array)self::$i18n_js_strings;
269
+        $i18n_js_strings = (array) self::$i18n_js_strings;
270 270
         foreach ($i18n_js_strings as $key => $value) {
271 271
             if (is_scalar($value)) {
272
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
272
+                $i18n_js_strings[$key] = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
273 273
             }
274 274
         }
275
-        return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
275
+        return '/* <![CDATA[ */ var eei18n = '.wp_json_encode($i18n_js_strings).'; /* ]]> */';
276 276
     }
277 277
 
278 278
 
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
             $module_class = get_class($module);
289 289
             $this->modules->{$module_class} = $module;
290 290
         } else {
291
-            if (! class_exists('EE_Module_Request_Router')) {
291
+            if ( ! class_exists('EE_Module_Request_Router')) {
292 292
                 $this->load_core('Module_Request_Router');
293 293
             }
294 294
             EE_Module_Request_Router::module_factory($module);
@@ -328,10 +328,10 @@  discard block
 block discarded – undo
328 328
                 EE_CORE,
329 329
                 EE_ADMIN,
330 330
                 EE_CPTS,
331
-                EE_CORE . 'data_migration_scripts' . DS,
332
-                EE_CORE . 'capabilities' . DS,
333
-                EE_CORE . 'request_stack' . DS,
334
-                EE_CORE . 'middleware' . DS,
331
+                EE_CORE.'data_migration_scripts'.DS,
332
+                EE_CORE.'capabilities'.DS,
333
+                EE_CORE.'request_stack'.DS,
334
+                EE_CORE.'middleware'.DS,
335 335
             )
336 336
         );
337 337
         // retrieve instantiated class
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
         $service_paths = apply_filters(
364 364
             'FHEE__EE_Registry__load_service__service_paths',
365 365
             array(
366
-                EE_CORE . 'services' . DS,
366
+                EE_CORE.'services'.DS,
367 367
             )
368 368
         );
369 369
         // retrieve instantiated class
@@ -484,10 +484,10 @@  discard block
 block discarded – undo
484 484
     {
485 485
         $paths = array(
486 486
             EE_LIBRARIES,
487
-            EE_LIBRARIES . 'messages' . DS,
488
-            EE_LIBRARIES . 'shortcodes' . DS,
489
-            EE_LIBRARIES . 'qtips' . DS,
490
-            EE_LIBRARIES . 'payment_methods' . DS,
487
+            EE_LIBRARIES.'messages'.DS,
488
+            EE_LIBRARIES.'shortcodes'.DS,
489
+            EE_LIBRARIES.'qtips'.DS,
490
+            EE_LIBRARIES.'payment_methods'.DS,
491 491
         );
492 492
         // retrieve instantiated class
493 493
         return $this->_load(
@@ -548,10 +548,10 @@  discard block
 block discarded – undo
548 548
     public function load_model_class($class_name, $arguments = array(), $load_only = true)
549 549
     {
550 550
         $paths = array(
551
-            EE_MODELS . 'fields' . DS,
552
-            EE_MODELS . 'helpers' . DS,
553
-            EE_MODELS . 'relations' . DS,
554
-            EE_MODELS . 'strategies' . DS,
551
+            EE_MODELS.'fields'.DS,
552
+            EE_MODELS.'helpers'.DS,
553
+            EE_MODELS.'relations'.DS,
554
+            EE_MODELS.'strategies'.DS,
555 555
         );
556 556
         // retrieve instantiated class
557 557
         return $this->_load(
@@ -663,13 +663,13 @@  discard block
 block discarded – undo
663 663
     ) {
664 664
         $class_name = ltrim($class_name, '\\');
665 665
         $class_name = $this->_dependency_map->get_alias($class_name);
666
-        if (! class_exists($class_name)) {
666
+        if ( ! class_exists($class_name)) {
667 667
             // maybe the class is registered with a preceding \
668 668
             $class_name = strpos($class_name, '\\') !== 0
669
-                ? '\\' . $class_name
669
+                ? '\\'.$class_name
670 670
                 : $class_name;
671 671
             // still doesn't exist ?
672
-            if (! class_exists($class_name)) {
672
+            if ( ! class_exists($class_name)) {
673 673
                 return null;
674 674
             }
675 675
         }
@@ -739,11 +739,11 @@  discard block
 block discarded – undo
739 739
         // strip php file extension
740 740
         $class_name = str_replace('.php', '', trim($class_name));
741 741
         // does the class have a prefix ?
742
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
742
+        if ( ! empty($class_prefix) && $class_prefix !== 'addon') {
743 743
             // make sure $class_prefix is uppercase
744 744
             $class_prefix = strtoupper(trim($class_prefix));
745 745
             // add class prefix ONCE!!!
746
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
746
+            $class_name = $class_prefix.str_replace($class_prefix, '', $class_name);
747 747
         }
748 748
         $class_name = $this->_dependency_map->get_alias($class_name);
749 749
         $class_exists = class_exists($class_name);
@@ -762,13 +762,13 @@  discard block
 block discarded – undo
762 762
             }
763 763
         }
764 764
         // if the class doesn't already exist.. then we need to try and find the file and load it
765
-        if (! $class_exists) {
765
+        if ( ! $class_exists) {
766 766
             // get full path to file
767 767
             $path = $this->_resolve_path($class_name, $type, $file_paths);
768 768
             // load the file
769 769
             $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
770 770
             // if loading failed, or we are only loading a file but NOT instantiating an object
771
-            if (! $loaded || $load_only) {
771
+            if ( ! $loaded || $load_only) {
772 772
                 // return boolean if only loading, or null if an object was expected
773 773
                 return $load_only
774 774
                     ? $loaded
@@ -893,10 +893,10 @@  discard block
 block discarded – undo
893 893
                 : EE_CLASSES;
894 894
             // prep file type
895 895
             $type = ! empty($type)
896
-                ? trim($type, '.') . '.'
896
+                ? trim($type, '.').'.'
897 897
                 : '';
898 898
             // build full file path
899
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
899
+            $file_paths[$key] = rtrim($file_path, DS).DS.$class_name.'.'.$type.'php';
900 900
             //does the file exist and can be read ?
901 901
             if (is_readable($file_paths[$key])) {
902 902
                 return $file_paths[$key];
@@ -924,9 +924,9 @@  discard block
 block discarded – undo
924 924
         // don't give up! you gotta...
925 925
         try {
926 926
             //does the file exist and can it be read ?
927
-            if (! $path) {
927
+            if ( ! $path) {
928 928
                 // so sorry, can't find the file
929
-                throw new EE_Error (
929
+                throw new EE_Error(
930 930
                     sprintf(
931 931
                         esc_html__(
932 932
                             'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
@@ -934,7 +934,7 @@  discard block
 block discarded – undo
934 934
                         ),
935 935
                         trim($type, '.'),
936 936
                         $class_name,
937
-                        '<br />' . implode(',<br />', $file_paths)
937
+                        '<br />'.implode(',<br />', $file_paths)
938 938
                     )
939 939
                 );
940 940
             }
@@ -1035,7 +1035,7 @@  discard block
 block discarded – undo
1035 1035
                 );
1036 1036
             }
1037 1037
         } catch (Exception $e) {
1038
-            if (! $e instanceof EE_Error) {
1038
+            if ( ! $e instanceof EE_Error) {
1039 1039
                 $e = new EE_Error(
1040 1040
                     sprintf(
1041 1041
                         esc_html__(
@@ -1117,7 +1117,7 @@  discard block
 block discarded – undo
1117 1117
         // let's examine the constructor
1118 1118
         $constructor = $reflector->getConstructor();
1119 1119
         // whu? huh? nothing?
1120
-        if (! $constructor) {
1120
+        if ( ! $constructor) {
1121 1121
             return $arguments;
1122 1122
         }
1123 1123
         // get constructor parameters
@@ -1359,7 +1359,7 @@  discard block
 block discarded – undo
1359 1359
         $model_class_name = strpos($model_name, 'EEM_') !== 0
1360 1360
             ? "EEM_{$model_name}"
1361 1361
             : $model_name;
1362
-        if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1362
+        if ( ! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1363 1363
             return null;
1364 1364
         }
1365 1365
         //get that model reset it and make sure we nuke the old reference to it
@@ -1412,7 +1412,7 @@  discard block
 block discarded – undo
1412 1412
         $instance->_cache_on = true;
1413 1413
         // reset some "special" classes
1414 1414
         EEH_Activation::reset();
1415
-        $hard = apply_filters( 'FHEE__EE_Registry__reset__hard', $hard);
1415
+        $hard = apply_filters('FHEE__EE_Registry__reset__hard', $hard);
1416 1416
         $instance->CFG = EE_Config::reset($hard, $reinstantiate);
1417 1417
         $instance->CART = null;
1418 1418
         $instance->MRM = null;
@@ -1443,7 +1443,7 @@  discard block
 block discarded – undo
1443 1443
      */
1444 1444
     private static function _reset_and_unset_object($object, $reset_models)
1445 1445
     {
1446
-        if (! is_object($object)) {
1446
+        if ( ! is_object($object)) {
1447 1447
             // don't unset anything that's not an object
1448 1448
             return false;
1449 1449
         }
@@ -1463,7 +1463,7 @@  discard block
 block discarded – undo
1463 1463
             $object->reset();
1464 1464
             return true;
1465 1465
         }
1466
-        if (! $object instanceof InterminableInterface) {
1466
+        if ( ! $object instanceof InterminableInterface) {
1467 1467
             return true;
1468 1468
         }
1469 1469
         return false;
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +5994 added lines, -5994 removed lines patch added patch discarded remove patch
@@ -32,6002 +32,6002 @@
 block discarded – undo
32 32
 abstract class EEM_Base extends EE_Base implements ResettableInterface
33 33
 {
34 34
 
35
-    //admin posty
36
-    //basic -> grants access to mine -> if they don't have it, select none
37
-    //*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
38
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
39
-    //*_published -> grants access to published -> if they dont have it, select non-published
40
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
41
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
42
-    //frontend posty
43
-    //by default has access to published
44
-    //basic -> grants access to mine that aren't published, and all published
45
-    //*_others ->grants access to others that aren't private, all mine
46
-    //*_private -> grants full access
47
-    //frontend non-posty
48
-    //like admin posty
49
-    //category-y
50
-    //assign -> grants access to join-table
51
-    //(delete, edit)
52
-    //payment-method-y
53
-    //for each registered payment method,
54
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
55
-    /**
56
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
57
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
58
-     * They almost always WILL NOT, but it's not necessarily a requirement.
59
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
60
-     *
61
-     * @var boolean
62
-     */
63
-    private $_values_already_prepared_by_model_object = 0;
64
-
65
-    /**
66
-     * when $_values_already_prepared_by_model_object equals this, we assume
67
-     * the data is just like form input that needs to have the model fields'
68
-     * prepare_for_set and prepare_for_use_in_db called on it
69
-     */
70
-    const not_prepared_by_model_object = 0;
71
-
72
-    /**
73
-     * when $_values_already_prepared_by_model_object equals this, we
74
-     * assume this value is coming from a model object and doesn't need to have
75
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
76
-     */
77
-    const prepared_by_model_object = 1;
78
-
79
-    /**
80
-     * when $_values_already_prepared_by_model_object equals this, we assume
81
-     * the values are already to be used in the database (ie no processing is done
82
-     * on them by the model's fields)
83
-     */
84
-    const prepared_for_use_in_db = 2;
85
-
86
-
87
-    protected $singular_item = 'Item';
88
-
89
-    protected $plural_item   = 'Items';
90
-
91
-    /**
92
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
93
-     */
94
-    protected $_tables;
95
-
96
-    /**
97
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
98
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
99
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
100
-     *
101
-     * @var \EE_Model_Field_Base[] $_fields
102
-     */
103
-    protected $_fields;
104
-
105
-    /**
106
-     * array of different kinds of relations
107
-     *
108
-     * @var \EE_Model_Relation_Base[] $_model_relations
109
-     */
110
-    protected $_model_relations;
111
-
112
-    /**
113
-     * @var \EE_Index[] $_indexes
114
-     */
115
-    protected $_indexes = array();
116
-
117
-    /**
118
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
119
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
120
-     * by setting the same columns as used in these queries in the query yourself.
121
-     *
122
-     * @var EE_Default_Where_Conditions
123
-     */
124
-    protected $_default_where_conditions_strategy;
125
-
126
-    /**
127
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
128
-     * This is particularly useful when you want something between 'none' and 'default'
129
-     *
130
-     * @var EE_Default_Where_Conditions
131
-     */
132
-    protected $_minimum_where_conditions_strategy;
133
-
134
-    /**
135
-     * String describing how to find the "owner" of this model's objects.
136
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
137
-     * But when there isn't, this indicates which related model, or transiently-related model,
138
-     * has the foreign key to the wp_users table.
139
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
140
-     * related to events, and events have a foreign key to wp_users.
141
-     * On EEM_Transaction, this would be 'Transaction.Event'
142
-     *
143
-     * @var string
144
-     */
145
-    protected $_model_chain_to_wp_user = '';
146
-
147
-    /**
148
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
149
-     * don't need it (particularly CPT models)
150
-     *
151
-     * @var bool
152
-     */
153
-    protected $_ignore_where_strategy = false;
154
-
155
-    /**
156
-     * String used in caps relating to this model. Eg, if the caps relating to this
157
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
158
-     *
159
-     * @var string. If null it hasn't been initialized yet. If false then we
160
-     * have indicated capabilities don't apply to this
161
-     */
162
-    protected $_caps_slug = null;
163
-
164
-    /**
165
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
166
-     * and next-level keys are capability names, and each's value is a
167
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
168
-     * they specify which context to use (ie, frontend, backend, edit or delete)
169
-     * and then each capability in the corresponding sub-array that they're missing
170
-     * adds the where conditions onto the query.
171
-     *
172
-     * @var array
173
-     */
174
-    protected $_cap_restrictions = array(
175
-        self::caps_read       => array(),
176
-        self::caps_read_admin => array(),
177
-        self::caps_edit       => array(),
178
-        self::caps_delete     => array(),
179
-    );
180
-
181
-    /**
182
-     * Array defining which cap restriction generators to use to create default
183
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
184
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
185
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
186
-     * automatically set this to false (not just null).
187
-     *
188
-     * @var EE_Restriction_Generator_Base[]
189
-     */
190
-    protected $_cap_restriction_generators = array();
191
-
192
-    /**
193
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
194
-     */
195
-    const caps_read       = 'read';
196
-
197
-    const caps_read_admin = 'read_admin';
198
-
199
-    const caps_edit       = 'edit';
200
-
201
-    const caps_delete     = 'delete';
202
-
203
-    /**
204
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
205
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
206
-     * maps to 'read' because when looking for relevant permissions we're going to use
207
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
208
-     *
209
-     * @var array
210
-     */
211
-    protected $_cap_contexts_to_cap_action_map = array(
212
-        self::caps_read       => 'read',
213
-        self::caps_read_admin => 'read',
214
-        self::caps_edit       => 'edit',
215
-        self::caps_delete     => 'delete',
216
-    );
217
-
218
-    /**
219
-     * Timezone
220
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
221
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
222
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
223
-     * EE_Datetime_Field data type will have access to it.
224
-     *
225
-     * @var string
226
-     */
227
-    protected $_timezone;
228
-
229
-
230
-    /**
231
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
232
-     * multisite.
233
-     *
234
-     * @var int
235
-     */
236
-    protected static $_model_query_blog_id;
237
-
238
-    /**
239
-     * A copy of _fields, except the array keys are the model names pointed to by
240
-     * the field
241
-     *
242
-     * @var EE_Model_Field_Base[]
243
-     */
244
-    private $_cache_foreign_key_to_fields = array();
245
-
246
-    /**
247
-     * Cached list of all the fields on the model, indexed by their name
248
-     *
249
-     * @var EE_Model_Field_Base[]
250
-     */
251
-    private $_cached_fields = null;
252
-
253
-    /**
254
-     * Cached list of all the fields on the model, except those that are
255
-     * marked as only pertinent to the database
256
-     *
257
-     * @var EE_Model_Field_Base[]
258
-     */
259
-    private $_cached_fields_non_db_only = null;
260
-
261
-    /**
262
-     * A cached reference to the primary key for quick lookup
263
-     *
264
-     * @var EE_Model_Field_Base
265
-     */
266
-    private $_primary_key_field = null;
267
-
268
-    /**
269
-     * Flag indicating whether this model has a primary key or not
270
-     *
271
-     * @var boolean
272
-     */
273
-    protected $_has_primary_key_field = null;
274
-
275
-    /**
276
-     * Whether or not this model is based off a table in WP core only (CPTs should set
277
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
278
-     *
279
-     * @var boolean
280
-     */
281
-    protected $_wp_core_model = false;
282
-
283
-    /**
284
-     *    List of valid operators that can be used for querying.
285
-     * The keys are all operators we'll accept, the values are the real SQL
286
-     * operators used
287
-     *
288
-     * @var array
289
-     */
290
-    protected $_valid_operators = array(
291
-        '='           => '=',
292
-        '<='          => '<=',
293
-        '<'           => '<',
294
-        '>='          => '>=',
295
-        '>'           => '>',
296
-        '!='          => '!=',
297
-        'LIKE'        => 'LIKE',
298
-        'like'        => 'LIKE',
299
-        'NOT_LIKE'    => 'NOT LIKE',
300
-        'not_like'    => 'NOT LIKE',
301
-        'NOT LIKE'    => 'NOT LIKE',
302
-        'not like'    => 'NOT LIKE',
303
-        'IN'          => 'IN',
304
-        'in'          => 'IN',
305
-        'NOT_IN'      => 'NOT IN',
306
-        'not_in'      => 'NOT IN',
307
-        'NOT IN'      => 'NOT IN',
308
-        'not in'      => 'NOT IN',
309
-        'between'     => 'BETWEEN',
310
-        'BETWEEN'     => 'BETWEEN',
311
-        'IS_NOT_NULL' => 'IS NOT NULL',
312
-        'is_not_null' => 'IS NOT NULL',
313
-        'IS NOT NULL' => 'IS NOT NULL',
314
-        'is not null' => 'IS NOT NULL',
315
-        'IS_NULL'     => 'IS NULL',
316
-        'is_null'     => 'IS NULL',
317
-        'IS NULL'     => 'IS NULL',
318
-        'is null'     => 'IS NULL',
319
-        'REGEXP'      => 'REGEXP',
320
-        'regexp'      => 'REGEXP',
321
-        'NOT_REGEXP'  => 'NOT REGEXP',
322
-        'not_regexp'  => 'NOT REGEXP',
323
-        'NOT REGEXP'  => 'NOT REGEXP',
324
-        'not regexp'  => 'NOT REGEXP',
325
-    );
326
-
327
-    /**
328
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
329
-     *
330
-     * @var array
331
-     */
332
-    protected $_in_style_operators = array('IN', 'NOT IN');
333
-
334
-    /**
335
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
336
-     * '12-31-2012'"
337
-     *
338
-     * @var array
339
-     */
340
-    protected $_between_style_operators = array('BETWEEN');
341
-
342
-    /**
343
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
344
-     * on a join table.
345
-     *
346
-     * @var array
347
-     */
348
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
349
-
350
-    /**
351
-     * Allowed values for $query_params['order'] for ordering in queries
352
-     *
353
-     * @var array
354
-     */
355
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
356
-
357
-    /**
358
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
359
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
360
-     *
361
-     * @var array
362
-     */
363
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
364
-
365
-    /**
366
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
367
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
368
-     *
369
-     * @var array
370
-     */
371
-    private $_allowed_query_params = array(
372
-        0,
373
-        'limit',
374
-        'order_by',
375
-        'group_by',
376
-        'having',
377
-        'force_join',
378
-        'order',
379
-        'on_join_limit',
380
-        'default_where_conditions',
381
-        'caps',
382
-    );
383
-
384
-    /**
385
-     * All the data types that can be used in $wpdb->prepare statements.
386
-     *
387
-     * @var array
388
-     */
389
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
390
-
391
-    /**
392
-     *    EE_Registry Object
393
-     *
394
-     * @var    object
395
-     * @access    protected
396
-     */
397
-    protected $EE = null;
398
-
399
-
400
-    /**
401
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
402
-     *
403
-     * @var int
404
-     */
405
-    protected $_show_next_x_db_queries = 0;
406
-
407
-    /**
408
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
409
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
410
-     *
411
-     * @var array
412
-     */
413
-    protected $_custom_selections = array();
414
-
415
-    /**
416
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
417
-     * caches every model object we've fetched from the DB on this request
418
-     *
419
-     * @var array
420
-     */
421
-    protected $_entity_map;
422
-
423
-    /**
424
-     * constant used to show EEM_Base has not yet verified the db on this http request
425
-     */
426
-    const db_verified_none = 0;
427
-
428
-    /**
429
-     * constant used to show EEM_Base has verified the EE core db on this http request,
430
-     * but not the addons' dbs
431
-     */
432
-    const db_verified_core = 1;
433
-
434
-    /**
435
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
436
-     * the EE core db too)
437
-     */
438
-    const db_verified_addons = 2;
439
-
440
-    /**
441
-     * indicates whether an EEM_Base child has already re-verified the DB
442
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
443
-     * looking like EEM_Base::db_verified_*
444
-     *
445
-     * @var int - 0 = none, 1 = core, 2 = addons
446
-     */
447
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
448
-
449
-    /**
450
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
451
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
452
-     *        registrations for non-trashed tickets for non-trashed datetimes)
453
-     */
454
-    const default_where_conditions_all = 'all';
455
-
456
-    /**
457
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
458
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
459
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
460
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
461
-     *        models which share tables with other models, this can return data for the wrong model.
462
-     */
463
-    const default_where_conditions_this_only = 'this_model_only';
464
-
465
-    /**
466
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
467
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
468
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
469
-     */
470
-    const default_where_conditions_others_only = 'other_models_only';
471
-
472
-    /**
473
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
474
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
475
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
476
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
477
-     *        (regardless of whether those events and venues are trashed)
478
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
479
-     *        events.
480
-     */
481
-    const default_where_conditions_minimum_all = 'minimum';
482
-
483
-    /**
484
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
485
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
486
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
487
-     *        not)
488
-     */
489
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
490
-
491
-    /**
492
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
493
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
494
-     *        it's possible it will return table entries for other models. You should use
495
-     *        EEM_Base::default_where_conditions_minimum_all instead.
496
-     */
497
-    const default_where_conditions_none = 'none';
498
-
499
-
500
-
501
-    /**
502
-     * About all child constructors:
503
-     * they should define the _tables, _fields and _model_relations arrays.
504
-     * Should ALWAYS be called after child constructor.
505
-     * In order to make the child constructors to be as simple as possible, this parent constructor
506
-     * finalizes constructing all the object's attributes.
507
-     * Generally, rather than requiring a child to code
508
-     * $this->_tables = array(
509
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
510
-     *        ...);
511
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
512
-     * each EE_Table has a function to set the table's alias after the constructor, using
513
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
514
-     * do something similar.
515
-     *
516
-     * @param null $timezone
517
-     * @throws EE_Error
518
-     */
519
-    protected function __construct($timezone = null)
520
-    {
521
-        // check that the model has not been loaded too soon
522
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
523
-            throw new EE_Error (
524
-                sprintf(
525
-                    __('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.',
526
-                        'event_espresso'),
527
-                    get_class($this)
528
-                )
529
-            );
530
-        }
531
-        /**
532
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
533
-         */
534
-        if (empty(EEM_Base::$_model_query_blog_id)) {
535
-            EEM_Base::set_model_query_blog_id();
536
-        }
537
-        /**
538
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
539
-         * just use EE_Register_Model_Extension
540
-         *
541
-         * @var EE_Table_Base[] $_tables
542
-         */
543
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
544
-        foreach ($this->_tables as $table_alias => $table_obj) {
545
-            /** @var $table_obj EE_Table_Base */
546
-            $table_obj->_construct_finalize_with_alias($table_alias);
547
-            if ($table_obj instanceof EE_Secondary_Table) {
548
-                /** @var $table_obj EE_Secondary_Table */
549
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
550
-            }
551
-        }
552
-        /**
553
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
554
-         * EE_Register_Model_Extension
555
-         *
556
-         * @param EE_Model_Field_Base[] $_fields
557
-         */
558
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
559
-        $this->_invalidate_field_caches();
560
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
561
-            if (! array_key_exists($table_alias, $this->_tables)) {
562
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
563
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
564
-            }
565
-            foreach ($fields_for_table as $field_name => $field_obj) {
566
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
-                //primary key field base has a slightly different _construct_finalize
568
-                /** @var $field_obj EE_Model_Field_Base */
569
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
-            }
571
-        }
572
-        // everything is related to Extra_Meta
573
-        if (get_class($this) !== 'EEM_Extra_Meta') {
574
-            //make extra meta related to everything, but don't block deleting things just
575
-            //because they have related extra meta info. For now just orphan those extra meta
576
-            //in the future we should automatically delete them
577
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        //and change logs
580
-        if (get_class($this) !== 'EEM_Change_Log') {
581
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
-        }
583
-        /**
584
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
-         * EE_Register_Model_Extension
586
-         *
587
-         * @param EE_Model_Relation_Base[] $_model_relations
588
-         */
589
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
590
-            $this->_model_relations);
591
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
592
-            /** @var $relation_obj EE_Model_Relation_Base */
593
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
594
-        }
595
-        foreach ($this->_indexes as $index_name => $index_obj) {
596
-            /** @var $index_obj EE_Index */
597
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
598
-        }
599
-        $this->set_timezone($timezone);
600
-        //finalize default where condition strategy, or set default
601
-        if (! $this->_default_where_conditions_strategy) {
602
-            //nothing was set during child constructor, so set default
603
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
604
-        }
605
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
606
-        if (! $this->_minimum_where_conditions_strategy) {
607
-            //nothing was set during child constructor, so set default
608
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
609
-        }
610
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
611
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
612
-        //to indicate to NOT set it, set it to the logical default
613
-        if ($this->_caps_slug === null) {
614
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
615
-        }
616
-        //initialize the standard cap restriction generators if none were specified by the child constructor
617
-        if ($this->_cap_restriction_generators !== false) {
618
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
619
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
620
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
621
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
622
-                        new EE_Restriction_Generator_Protected(),
623
-                        $cap_context,
624
-                        $this
625
-                    );
626
-                }
627
-            }
628
-        }
629
-        //if there are cap restriction generators, use them to make the default cap restrictions
630
-        if ($this->_cap_restriction_generators !== false) {
631
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
632
-                if (! $generator_object) {
633
-                    continue;
634
-                }
635
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
636
-                    throw new EE_Error(
637
-                        sprintf(
638
-                            __('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.',
639
-                                'event_espresso'),
640
-                            $context,
641
-                            $this->get_this_model_name()
642
-                        )
643
-                    );
644
-                }
645
-                $action = $this->cap_action_for_context($context);
646
-                if (! $generator_object->construction_finalized()) {
647
-                    $generator_object->_construct_finalize($this, $action);
648
-                }
649
-            }
650
-        }
651
-        do_action('AHEE__' . get_class($this) . '__construct__end');
652
-    }
653
-
654
-
655
-
656
-    /**
657
-     * Generates the cap restrictions for the given context, or if they were
658
-     * already generated just gets what's cached
659
-     *
660
-     * @param string $context one of EEM_Base::valid_cap_contexts()
661
-     * @return EE_Default_Where_Conditions[]
662
-     */
663
-    protected function _generate_cap_restrictions($context)
664
-    {
665
-        if (isset($this->_cap_restriction_generators[$context])
666
-            && $this->_cap_restriction_generators[$context]
667
-               instanceof
668
-               EE_Restriction_Generator_Base
669
-        ) {
670
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
671
-        } else {
672
-            return array();
673
-        }
674
-    }
675
-
676
-
677
-
678
-    /**
679
-     * Used to set the $_model_query_blog_id static property.
680
-     *
681
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
682
-     *                      value for get_current_blog_id() will be used.
683
-     */
684
-    public static function set_model_query_blog_id($blog_id = 0)
685
-    {
686
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
687
-    }
688
-
689
-
690
-
691
-    /**
692
-     * Returns whatever is set as the internal $model_query_blog_id.
693
-     *
694
-     * @return int
695
-     */
696
-    public static function get_model_query_blog_id()
697
-    {
698
-        return EEM_Base::$_model_query_blog_id;
699
-    }
700
-
701
-
702
-
703
-    /**
704
-     * This function is a singleton method used to instantiate the Espresso_model object
705
-     *
706
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
707
-     *                                (and any incoming timezone data that gets saved).
708
-     *                                Note this just sends the timezone info to the date time model field objects.
709
-     *                                Default is NULL
710
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
711
-     * @return static (as in the concrete child class)
712
-     * @throws InvalidArgumentException
713
-     * @throws InvalidInterfaceException
714
-     * @throws InvalidDataTypeException
715
-     * @throws EE_Error
716
-     */
717
-    public static function instance($timezone = null)
718
-    {
719
-        // check if instance of Espresso_model already exists
720
-        if (! static::$_instance instanceof static) {
721
-            // instantiate Espresso_model
722
-            static::$_instance = new static(
723
-                $timezone,
724
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
725
-            );
726
-        }
727
-        //we might have a timezone set, let set_timezone decide what to do with it
728
-        static::$_instance->set_timezone($timezone);
729
-        // Espresso_model object
730
-        return static::$_instance;
731
-    }
732
-
733
-
734
-
735
-    /**
736
-     * resets the model and returns it
737
-     *
738
-     * @param null | string $timezone
739
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
740
-     * @throws ReflectionException
741
-     * all its properties reset; if it wasn't instantiated, returns null)
742
-     * @throws EE_Error
743
-     * @throws InvalidArgumentException
744
-     * @throws InvalidDataTypeException
745
-     * @throws InvalidInterfaceException
746
-     */
747
-    public static function reset($timezone = null)
748
-    {
749
-        if (static::$_instance instanceof EEM_Base) {
750
-            //let's try to NOT swap out the current instance for a new one
751
-            //because if someone has a reference to it, we can't remove their reference
752
-            //so it's best to keep using the same reference, but change the original object
753
-            //reset all its properties to their original values as defined in the class
754
-            $r = new ReflectionClass(get_class(static::$_instance));
755
-            $static_properties = $r->getStaticProperties();
756
-            foreach ($r->getDefaultProperties() as $property => $value) {
757
-                //don't set instance to null like it was originally,
758
-                //but it's static anyways, and we're ignoring static properties (for now at least)
759
-                if (! isset($static_properties[$property])) {
760
-                    static::$_instance->{$property} = $value;
761
-                }
762
-            }
763
-            //and then directly call its constructor again, like we would if we were creating a new one
764
-            static::$_instance->__construct(
765
-                $timezone,
766
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
767
-            );
768
-            return self::instance();
769
-        }
770
-        return null;
771
-    }
772
-
773
-
774
-
775
-    /**
776
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
777
-     *
778
-     * @param  boolean $translated return localized strings or JUST the array.
779
-     * @return array
780
-     * @throws EE_Error
781
-     */
782
-    public function status_array($translated = false)
783
-    {
784
-        if (! array_key_exists('Status', $this->_model_relations)) {
785
-            return array();
786
-        }
787
-        $model_name = $this->get_this_model_name();
788
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
789
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
790
-        $status_array = array();
791
-        foreach ($stati as $status) {
792
-            $status_array[$status->ID()] = $status->get('STS_code');
793
-        }
794
-        return $translated
795
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
796
-            : $status_array;
797
-    }
798
-
799
-
800
-
801
-    /**
802
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
803
-     *
804
-     * @param array $query_params             {
805
-     * @var array $0 (where) array {
806
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
807
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
808
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
809
-     *                                        conditions based on related models (and even
810
-     *                                        models-related-to-related-models) prepend the model's name onto the field
811
-     *                                        name. Eg,
812
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
813
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
814
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
815
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
816
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
817
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
818
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
819
-     *                                        to Venues (even when each of those models actually consisted of two
820
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
821
-     *                                        just having
822
-     *                                        "Venue.VNU_ID", you could have
823
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
824
-     *                                        events are related to Registrations, which are related to Attendees). You
825
-     *                                        can take it even further with
826
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
827
-     *                                        (from the default of '='), change the value to an numerically-indexed
828
-     *                                        array, where the first item in the list is the operator. eg: array(
829
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
830
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
831
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
832
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
833
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
834
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
835
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
836
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
837
-     *                                        the value is a field, simply provide a third array item (true) to the
838
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
839
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
840
-     *                                        Note: you can also use related model field names like you would any other
841
-     *                                        field name. eg:
842
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
843
-     *                                        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__>' =>
844
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
845
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
846
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
847
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
848
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
849
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
850
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
851
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
852
-     *                                        "stick" until you specify an AND. eg
853
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
854
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
855
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
856
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
857
-     *                                        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 >>
858
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
859
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
860
-     *                                        too, eg:
861
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
862
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
863
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
864
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
865
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
866
-     *                                        the OFFSET, the 2nd is the LIMIT
867
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
868
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
869
-     *                                        following format array('on_join_limit'
870
-     *                                        => array( 'table_alias', array(1,2) ) ).
871
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
872
-     *                                        values are either 'ASC' or 'DESC'.
873
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
874
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
875
-     *                                        DESC..." respectively. Like the
876
-     *                                        'where' conditions, these fields can be on related models. Eg
877
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
878
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
879
-     *                                        Attendee, Price, Datetime, etc.)
880
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
881
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
882
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
883
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
884
-     *                                        order by the primary key. Eg,
885
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
886
-     *                                        //(will join with the Datetime model's table(s) and order by its field
887
-     *                                        DTT_EVT_start) or
888
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
889
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
890
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
891
-     *                                        'group_by'=>'VNU_ID', or
892
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
893
-     *                                        if no
894
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
895
-     *                                        model's primary key (or combined primary keys). This avoids some
896
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
897
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
898
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
899
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
900
-     *                                        results)
901
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
902
-     *                                        array where values are models to be joined in the query.Eg
903
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
904
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
905
-     *                                        probably only want to do this in hopes of increasing efficiency, as
906
-     *                                        related models which belongs to the current model
907
-     *                                        (ie, the current model has a foreign key to them, like how Registration
908
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
909
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
910
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
911
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
912
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
913
-     *                                        default where conditions set it to 'other_models_only'. If you only want
914
-     *                                        this model's default where conditions added to the query, use
915
-     *                                        'this_model_only'. If you want to use all default where conditions
916
-     *                                        (default), set to 'all'.
917
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
918
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
919
-     *                                        everything? Or should we only show the current user items they should be
920
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
921
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
922
-     *                                        }
923
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
924
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
925
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
926
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
927
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
928
-     *                                        array( array(
929
-     *                                        'OR'=>array(
930
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
931
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
932
-     *                                        )
933
-     *                                        ),
934
-     *                                        'limit'=>10,
935
-     *                                        'group_by'=>'TXN_ID'
936
-     *                                        ));
937
-     *                                        get all the answers to the question titled "shirt size" for event with id
938
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
939
-     *                                        'Question.QST_display_text'=>'shirt size',
940
-     *                                        'Registration.Event.EVT_ID'=>12
941
-     *                                        ),
942
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
943
-     *                                        ));
944
-     * @throws EE_Error
945
-     */
946
-    public function get_all($query_params = array())
947
-    {
948
-        if (isset($query_params['limit'])
949
-            && ! isset($query_params['group_by'])
950
-        ) {
951
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
952
-        }
953
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * Modifies the query parameters so we only get back model objects
960
-     * that "belong" to the current user
961
-     *
962
-     * @param array $query_params @see EEM_Base::get_all()
963
-     * @return array like EEM_Base::get_all
964
-     */
965
-    public function alter_query_params_to_only_include_mine($query_params = array())
966
-    {
967
-        $wp_user_field_name = $this->wp_user_field_name();
968
-        if ($wp_user_field_name) {
969
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
970
-        }
971
-        return $query_params;
972
-    }
973
-
974
-
975
-
976
-    /**
977
-     * Returns the name of the field's name that points to the WP_User table
978
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
979
-     * foreign key to the WP_User table)
980
-     *
981
-     * @return string|boolean string on success, boolean false when there is no
982
-     * foreign key to the WP_User table
983
-     */
984
-    public function wp_user_field_name()
985
-    {
986
-        try {
987
-            if (! empty($this->_model_chain_to_wp_user)) {
988
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
989
-                $last_model_name = end($models_to_follow_to_wp_users);
990
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
991
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
992
-            } else {
993
-                $model_with_fk_to_wp_users = $this;
994
-                $model_chain_to_wp_user = '';
995
-            }
996
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
997
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
998
-        } catch (EE_Error $e) {
999
-            return false;
1000
-        }
1001
-    }
1002
-
1003
-
1004
-
1005
-    /**
1006
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
1007
-     * (or transiently-related model) has a foreign key to the wp_users table;
1008
-     * useful for finding if model objects of this type are 'owned' by the current user.
1009
-     * This is an empty string when the foreign key is on this model and when it isn't,
1010
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
1011
-     * (or transiently-related model)
1012
-     *
1013
-     * @return string
1014
-     */
1015
-    public function model_chain_to_wp_user()
1016
-    {
1017
-        return $this->_model_chain_to_wp_user;
1018
-    }
1019
-
1020
-
1021
-
1022
-    /**
1023
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1024
-     * like how registrations don't have a foreign key to wp_users, but the
1025
-     * events they are for are), or is unrelated to wp users.
1026
-     * generally available
1027
-     *
1028
-     * @return boolean
1029
-     */
1030
-    public function is_owned()
1031
-    {
1032
-        if ($this->model_chain_to_wp_user()) {
1033
-            return true;
1034
-        }
1035
-        try {
1036
-            $this->get_foreign_key_to('WP_User');
1037
-            return true;
1038
-        } catch (EE_Error $e) {
1039
-            return false;
1040
-        }
1041
-    }
1042
-
1043
-
1044
-
1045
-    /**
1046
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1047
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1048
-     * the model)
1049
-     *
1050
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1051
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1052
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1053
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1054
-     *                                  override this and set the select to "*", or a specific column name, like
1055
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1056
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1057
-     *                                  the aliases used to refer to this selection, and values are to be
1058
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1059
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1060
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1061
-     * @throws EE_Error
1062
-     */
1063
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1064
-    {
1065
-        // remember the custom selections, if any, and type cast as array
1066
-        // (unless $columns_to_select is an object, then just set as an empty array)
1067
-        // Note: (array) 'some string' === array( 'some string' )
1068
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1069
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1070
-        $select_expressions = $columns_to_select !== null
1071
-            ? $this->_construct_select_from_input($columns_to_select)
1072
-            : $this->_construct_default_select_sql($model_query_info);
1073
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1074
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1075
-    }
1076
-
1077
-
1078
-
1079
-    /**
1080
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1081
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1082
-     * take care of joins, field preparation etc.
1083
-     *
1084
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1085
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1086
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1087
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1088
-     *                                  override this and set the select to "*", or a specific column name, like
1089
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1090
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1091
-     *                                  the aliases used to refer to this selection, and values are to be
1092
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1093
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1094
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1095
-     * @throws EE_Error
1096
-     */
1097
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1098
-    {
1099
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1100
-    }
1101
-
1102
-
1103
-
1104
-    /**
1105
-     * For creating a custom select statement
1106
-     *
1107
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1108
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1109
-     *                                 SQL, and 1=>is the datatype
1110
-     * @throws EE_Error
1111
-     * @return string
1112
-     */
1113
-    private function _construct_select_from_input($columns_to_select)
1114
-    {
1115
-        if (is_array($columns_to_select)) {
1116
-            $select_sql_array = array();
1117
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1118
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1119
-                    throw new EE_Error(
1120
-                        sprintf(
1121
-                            __(
1122
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1123
-                                "event_espresso"
1124
-                            ),
1125
-                            $selection_and_datatype,
1126
-                            $alias
1127
-                        )
1128
-                    );
1129
-                }
1130
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1131
-                    throw new EE_Error(
1132
-                        sprintf(
1133
-                            __(
1134
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1135
-                                "event_espresso"
1136
-                            ),
1137
-                            $selection_and_datatype[1],
1138
-                            $selection_and_datatype[0],
1139
-                            $alias,
1140
-                            implode(",", $this->_valid_wpdb_data_types)
1141
-                        )
1142
-                    );
1143
-                }
1144
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1145
-            }
1146
-            $columns_to_select_string = implode(", ", $select_sql_array);
1147
-        } else {
1148
-            $columns_to_select_string = $columns_to_select;
1149
-        }
1150
-        return $columns_to_select_string;
1151
-    }
1152
-
1153
-
1154
-
1155
-    /**
1156
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1157
-     *
1158
-     * @return string
1159
-     * @throws EE_Error
1160
-     */
1161
-    public function primary_key_name()
1162
-    {
1163
-        return $this->get_primary_key_field()->get_name();
1164
-    }
1165
-
1166
-
1167
-
1168
-    /**
1169
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1170
-     * If there is no primary key on this model, $id is treated as primary key string
1171
-     *
1172
-     * @param mixed $id int or string, depending on the type of the model's primary key
1173
-     * @return EE_Base_Class
1174
-     */
1175
-    public function get_one_by_ID($id)
1176
-    {
1177
-        if ($this->get_from_entity_map($id)) {
1178
-            return $this->get_from_entity_map($id);
1179
-        }
1180
-        return $this->get_one(
1181
-            $this->alter_query_params_to_restrict_by_ID(
1182
-                $id,
1183
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1184
-            )
1185
-        );
1186
-    }
1187
-
1188
-
1189
-
1190
-    /**
1191
-     * Alters query parameters to only get items with this ID are returned.
1192
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1193
-     * or could just be a simple primary key ID
1194
-     *
1195
-     * @param int   $id
1196
-     * @param array $query_params
1197
-     * @return array of normal query params, @see EEM_Base::get_all
1198
-     * @throws EE_Error
1199
-     */
1200
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1201
-    {
1202
-        if (! isset($query_params[0])) {
1203
-            $query_params[0] = array();
1204
-        }
1205
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1206
-        if ($conditions_from_id === null) {
1207
-            $query_params[0][$this->primary_key_name()] = $id;
1208
-        } else {
1209
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1210
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1211
-        }
1212
-        return $query_params;
1213
-    }
1214
-
1215
-
1216
-
1217
-    /**
1218
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1219
-     * array. If no item is found, null is returned.
1220
-     *
1221
-     * @param array $query_params like EEM_Base's $query_params variable.
1222
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1223
-     * @throws EE_Error
1224
-     */
1225
-    public function get_one($query_params = array())
1226
-    {
1227
-        if (! is_array($query_params)) {
1228
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1229
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1230
-                    gettype($query_params)), '4.6.0');
1231
-            $query_params = array();
1232
-        }
1233
-        $query_params['limit'] = 1;
1234
-        $items = $this->get_all($query_params);
1235
-        if (empty($items)) {
1236
-            return null;
1237
-        }
1238
-        return array_shift($items);
1239
-    }
1240
-
1241
-
1242
-
1243
-    /**
1244
-     * Returns the next x number of items in sequence from the given value as
1245
-     * found in the database matching the given query conditions.
1246
-     *
1247
-     * @param mixed $current_field_value    Value used for the reference point.
1248
-     * @param null  $field_to_order_by      What field is used for the
1249
-     *                                      reference point.
1250
-     * @param int   $limit                  How many to return.
1251
-     * @param array $query_params           Extra conditions on the query.
1252
-     * @param null  $columns_to_select      If left null, then an array of
1253
-     *                                      EE_Base_Class objects is returned,
1254
-     *                                      otherwise you can indicate just the
1255
-     *                                      columns you want returned.
1256
-     * @return EE_Base_Class[]|array
1257
-     * @throws EE_Error
1258
-     */
1259
-    public function next_x(
1260
-        $current_field_value,
1261
-        $field_to_order_by = null,
1262
-        $limit = 1,
1263
-        $query_params = array(),
1264
-        $columns_to_select = null
1265
-    ) {
1266
-        return $this->_get_consecutive(
1267
-            $current_field_value,
1268
-            '>',
1269
-            $field_to_order_by,
1270
-            $limit,
1271
-            $query_params,
1272
-            $columns_to_select
1273
-        );
1274
-    }
1275
-
1276
-
1277
-
1278
-    /**
1279
-     * Returns the previous x number of items in sequence from the given value
1280
-     * as found in the database matching the given query conditions.
1281
-     *
1282
-     * @param mixed $current_field_value    Value used for the reference point.
1283
-     * @param null  $field_to_order_by      What field is used for the
1284
-     *                                      reference point.
1285
-     * @param int   $limit                  How many to return.
1286
-     * @param array $query_params           Extra conditions on the query.
1287
-     * @param null  $columns_to_select      If left null, then an array of
1288
-     *                                      EE_Base_Class objects is returned,
1289
-     *                                      otherwise you can indicate just the
1290
-     *                                      columns you want returned.
1291
-     * @return EE_Base_Class[]|array
1292
-     * @throws EE_Error
1293
-     */
1294
-    public function previous_x(
1295
-        $current_field_value,
1296
-        $field_to_order_by = null,
1297
-        $limit = 1,
1298
-        $query_params = array(),
1299
-        $columns_to_select = null
1300
-    ) {
1301
-        return $this->_get_consecutive(
1302
-            $current_field_value,
1303
-            '<',
1304
-            $field_to_order_by,
1305
-            $limit,
1306
-            $query_params,
1307
-            $columns_to_select
1308
-        );
1309
-    }
1310
-
1311
-
1312
-
1313
-    /**
1314
-     * Returns the next item in sequence from the given value as found in the
1315
-     * database matching the given query conditions.
1316
-     *
1317
-     * @param mixed $current_field_value    Value used for the reference point.
1318
-     * @param null  $field_to_order_by      What field is used for the
1319
-     *                                      reference point.
1320
-     * @param array $query_params           Extra conditions on the query.
1321
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1322
-     *                                      object is returned, otherwise you
1323
-     *                                      can indicate just the columns you
1324
-     *                                      want and a single array indexed by
1325
-     *                                      the columns will be returned.
1326
-     * @return EE_Base_Class|null|array()
1327
-     * @throws EE_Error
1328
-     */
1329
-    public function next(
1330
-        $current_field_value,
1331
-        $field_to_order_by = null,
1332
-        $query_params = array(),
1333
-        $columns_to_select = null
1334
-    ) {
1335
-        $results = $this->_get_consecutive(
1336
-            $current_field_value,
1337
-            '>',
1338
-            $field_to_order_by,
1339
-            1,
1340
-            $query_params,
1341
-            $columns_to_select
1342
-        );
1343
-        return empty($results) ? null : reset($results);
1344
-    }
1345
-
1346
-
1347
-
1348
-    /**
1349
-     * Returns the previous item in sequence from the given value as found in
1350
-     * the database matching the given query conditions.
1351
-     *
1352
-     * @param mixed $current_field_value    Value used for the reference point.
1353
-     * @param null  $field_to_order_by      What field is used for the
1354
-     *                                      reference point.
1355
-     * @param array $query_params           Extra conditions on the query.
1356
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1357
-     *                                      object is returned, otherwise you
1358
-     *                                      can indicate just the columns you
1359
-     *                                      want and a single array indexed by
1360
-     *                                      the columns will be returned.
1361
-     * @return EE_Base_Class|null|array()
1362
-     * @throws EE_Error
1363
-     */
1364
-    public function previous(
1365
-        $current_field_value,
1366
-        $field_to_order_by = null,
1367
-        $query_params = array(),
1368
-        $columns_to_select = null
1369
-    ) {
1370
-        $results = $this->_get_consecutive(
1371
-            $current_field_value,
1372
-            '<',
1373
-            $field_to_order_by,
1374
-            1,
1375
-            $query_params,
1376
-            $columns_to_select
1377
-        );
1378
-        return empty($results) ? null : reset($results);
1379
-    }
1380
-
1381
-
1382
-
1383
-    /**
1384
-     * Returns the a consecutive number of items in sequence from the given
1385
-     * value as found in the database matching the given query conditions.
1386
-     *
1387
-     * @param mixed  $current_field_value   Value used for the reference point.
1388
-     * @param string $operand               What operand is used for the sequence.
1389
-     * @param string $field_to_order_by     What field is used for the reference point.
1390
-     * @param int    $limit                 How many to return.
1391
-     * @param array  $query_params          Extra conditions on the query.
1392
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1393
-     *                                      otherwise you can indicate just the columns you want returned.
1394
-     * @return EE_Base_Class[]|array
1395
-     * @throws EE_Error
1396
-     */
1397
-    protected function _get_consecutive(
1398
-        $current_field_value,
1399
-        $operand = '>',
1400
-        $field_to_order_by = null,
1401
-        $limit = 1,
1402
-        $query_params = array(),
1403
-        $columns_to_select = null
1404
-    ) {
1405
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1406
-        if (empty($field_to_order_by)) {
1407
-            if ($this->has_primary_key_field()) {
1408
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1409
-            } else {
1410
-                if (WP_DEBUG) {
1411
-                    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).',
1412
-                        'event_espresso'));
1413
-                }
1414
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1415
-                return array();
1416
-            }
1417
-        }
1418
-        if (! is_array($query_params)) {
1419
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1420
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1421
-                    gettype($query_params)), '4.6.0');
1422
-            $query_params = array();
1423
-        }
1424
-        //let's add the where query param for consecutive look up.
1425
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1426
-        $query_params['limit'] = $limit;
1427
-        //set direction
1428
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1429
-        $query_params['order_by'] = $operand === '>'
1430
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1431
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1432
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1433
-        if (empty($columns_to_select)) {
1434
-            return $this->get_all($query_params);
1435
-        }
1436
-        //getting just the fields
1437
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1438
-    }
1439
-
1440
-
1441
-
1442
-    /**
1443
-     * This sets the _timezone property after model object has been instantiated.
1444
-     *
1445
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1446
-     */
1447
-    public function set_timezone($timezone)
1448
-    {
1449
-        if ($timezone !== null) {
1450
-            $this->_timezone = $timezone;
1451
-        }
1452
-        //note we need to loop through relations and set the timezone on those objects as well.
1453
-        foreach ($this->_model_relations as $relation) {
1454
-            $relation->set_timezone($timezone);
1455
-        }
1456
-        //and finally we do the same for any datetime fields
1457
-        foreach ($this->_fields as $field) {
1458
-            if ($field instanceof EE_Datetime_Field) {
1459
-                $field->set_timezone($timezone);
1460
-            }
1461
-        }
1462
-    }
1463
-
1464
-
1465
-
1466
-    /**
1467
-     * This just returns whatever is set for the current timezone.
1468
-     *
1469
-     * @access public
1470
-     * @return string
1471
-     */
1472
-    public function get_timezone()
1473
-    {
1474
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1475
-        if (empty($this->_timezone)) {
1476
-            foreach ($this->_fields as $field) {
1477
-                if ($field instanceof EE_Datetime_Field) {
1478
-                    $this->set_timezone($field->get_timezone());
1479
-                    break;
1480
-                }
1481
-            }
1482
-        }
1483
-        //if timezone STILL empty then return the default timezone for the site.
1484
-        if (empty($this->_timezone)) {
1485
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1486
-        }
1487
-        return $this->_timezone;
1488
-    }
1489
-
1490
-
1491
-
1492
-    /**
1493
-     * This returns the date formats set for the given field name and also ensures that
1494
-     * $this->_timezone property is set correctly.
1495
-     *
1496
-     * @since 4.6.x
1497
-     * @param string $field_name The name of the field the formats are being retrieved for.
1498
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1499
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1500
-     * @return array formats in an array with the date format first, and the time format last.
1501
-     */
1502
-    public function get_formats_for($field_name, $pretty = false)
1503
-    {
1504
-        $field_settings = $this->field_settings_for($field_name);
1505
-        //if not a valid EE_Datetime_Field then throw error
1506
-        if (! $field_settings instanceof EE_Datetime_Field) {
1507
-            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.',
1508
-                'event_espresso'), $field_name));
1509
-        }
1510
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1511
-        //the field.
1512
-        $this->_timezone = $field_settings->get_timezone();
1513
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1514
-    }
1515
-
1516
-
1517
-
1518
-    /**
1519
-     * This returns the current time in a format setup for a query on this model.
1520
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1521
-     * it will return:
1522
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1523
-     *  NOW
1524
-     *  - or a unix timestamp (equivalent to time())
1525
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1526
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1527
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1528
-     * @since 4.6.x
1529
-     * @param string $field_name       The field the current time is needed for.
1530
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1531
-     *                                 formatted string matching the set format for the field in the set timezone will
1532
-     *                                 be returned.
1533
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1534
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1535
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1536
-     *                                 exception is triggered.
1537
-     */
1538
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1539
-    {
1540
-        $formats = $this->get_formats_for($field_name);
1541
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1542
-        if ($timestamp) {
1543
-            return $DateTime->format('U');
1544
-        }
1545
-        //not returning timestamp, so return formatted string in timezone.
1546
-        switch ($what) {
1547
-            case 'time' :
1548
-                return $DateTime->format($formats[1]);
1549
-                break;
1550
-            case 'date' :
1551
-                return $DateTime->format($formats[0]);
1552
-                break;
1553
-            default :
1554
-                return $DateTime->format(implode(' ', $formats));
1555
-                break;
1556
-        }
1557
-    }
1558
-
1559
-
1560
-
1561
-    /**
1562
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1563
-     * for the model are.  Returns a DateTime object.
1564
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1565
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1566
-     * ignored.
1567
-     *
1568
-     * @param string $field_name      The field being setup.
1569
-     * @param string $timestring      The date time string being used.
1570
-     * @param string $incoming_format The format for the time string.
1571
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1572
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1573
-     *                                format is
1574
-     *                                'U', this is ignored.
1575
-     * @return DateTime
1576
-     * @throws EE_Error
1577
-     */
1578
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1579
-    {
1580
-        //just using this to ensure the timezone is set correctly internally
1581
-        $this->get_formats_for($field_name);
1582
-        //load EEH_DTT_Helper
1583
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1584
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1585
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1586
-    }
1587
-
1588
-
1589
-
1590
-    /**
1591
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1592
-     *
1593
-     * @return EE_Table_Base[]
1594
-     */
1595
-    public function get_tables()
1596
-    {
1597
-        return $this->_tables;
1598
-    }
1599
-
1600
-
1601
-
1602
-    /**
1603
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1604
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1605
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1606
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1607
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1608
-     * model object with EVT_ID = 1
1609
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1610
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1611
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1612
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1613
-     * are not specified)
1614
-     *
1615
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1616
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1617
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1618
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1619
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1620
-     *                                         ID=34, we'd use this method as follows:
1621
-     *                                         EEM_Transaction::instance()->update(
1622
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1623
-     *                                         array(array('TXN_ID'=>34)));
1624
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1625
-     *                                         in client code into what's expected to be stored on each field. Eg,
1626
-     *                                         consider updating Question's QST_admin_label field is of type
1627
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1628
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1629
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1630
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1631
-     *                                         TRUE, it is assumed that you've already called
1632
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1633
-     *                                         malicious javascript. However, if
1634
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1635
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1636
-     *                                         and every other field, before insertion. We provide this parameter
1637
-     *                                         because model objects perform their prepare_for_set function on all
1638
-     *                                         their values, and so don't need to be called again (and in many cases,
1639
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1640
-     *                                         prepare_for_set method...)
1641
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1642
-     *                                         in this model's entity map according to $fields_n_values that match
1643
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1644
-     *                                         by setting this to FALSE, but be aware that model objects being used
1645
-     *                                         could get out-of-sync with the database
1646
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1647
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1648
-     *                                         bad)
1649
-     * @throws EE_Error
1650
-     */
1651
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1652
-    {
1653
-        if (! is_array($query_params)) {
1654
-            EE_Error::doing_it_wrong('EEM_Base::update',
1655
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1656
-                    gettype($query_params)), '4.6.0');
1657
-            $query_params = array();
1658
-        }
1659
-        /**
1660
-         * Action called before a model update call has been made.
1661
-         *
1662
-         * @param EEM_Base $model
1663
-         * @param array    $fields_n_values the updated fields and their new values
1664
-         * @param array    $query_params    @see EEM_Base::get_all()
1665
-         */
1666
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1667
-        /**
1668
-         * Filters the fields about to be updated given the query parameters. You can provide the
1669
-         * $query_params to $this->get_all() to find exactly which records will be updated
1670
-         *
1671
-         * @param array    $fields_n_values fields and their new values
1672
-         * @param EEM_Base $model           the model being queried
1673
-         * @param array    $query_params    see EEM_Base::get_all()
1674
-         */
1675
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1676
-            $query_params);
1677
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1678
-        //to do that, for each table, verify that it's PK isn't null.
1679
-        $tables = $this->get_tables();
1680
-        //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
1681
-        //NOTE: we should make this code more efficient by NOT querying twice
1682
-        //before the real update, but that needs to first go through ALPHA testing
1683
-        //as it's dangerous. says Mike August 8 2014
1684
-        //we want to make sure the default_where strategy is ignored
1685
-        $this->_ignore_where_strategy = true;
1686
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1687
-        foreach ($wpdb_select_results as $wpdb_result) {
1688
-            // type cast stdClass as array
1689
-            $wpdb_result = (array)$wpdb_result;
1690
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1691
-            if ($this->has_primary_key_field()) {
1692
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1693
-            } else {
1694
-                //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)
1695
-                $main_table_pk_value = null;
1696
-            }
1697
-            //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
1698
-            //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
1699
-            if (count($tables) > 1) {
1700
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1701
-                //in that table, and so we'll want to insert one
1702
-                foreach ($tables as $table_obj) {
1703
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1704
-                    //if there is no private key for this table on the results, it means there's no entry
1705
-                    //in this table, right? so insert a row in the current table, using any fields available
1706
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1707
-                           && $wpdb_result[$this_table_pk_column])
1708
-                    ) {
1709
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1710
-                            $main_table_pk_value);
1711
-                        //if we died here, report the error
1712
-                        if (! $success) {
1713
-                            return false;
1714
-                        }
1715
-                    }
1716
-                }
1717
-            }
1718
-            //				//and now check that if we have cached any models by that ID on the model, that
1719
-            //				//they also get updated properly
1720
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1721
-            //				if( $model_object ){
1722
-            //					foreach( $fields_n_values as $field => $value ){
1723
-            //						$model_object->set($field, $value);
1724
-            //let's make sure default_where strategy is followed now
1725
-            $this->_ignore_where_strategy = false;
1726
-        }
1727
-        //if we want to keep model objects in sync, AND
1728
-        //if this wasn't called from a model object (to update itself)
1729
-        //then we want to make sure we keep all the existing
1730
-        //model objects in sync with the db
1731
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1732
-            if ($this->has_primary_key_field()) {
1733
-                $model_objs_affected_ids = $this->get_col($query_params);
1734
-            } else {
1735
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1736
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1737
-                $model_objs_affected_ids = array();
1738
-                foreach ($models_affected_key_columns as $row) {
1739
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1740
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1741
-                }
1742
-            }
1743
-            if (! $model_objs_affected_ids) {
1744
-                //wait wait wait- if nothing was affected let's stop here
1745
-                return 0;
1746
-            }
1747
-            foreach ($model_objs_affected_ids as $id) {
1748
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1749
-                if ($model_obj_in_entity_map) {
1750
-                    foreach ($fields_n_values as $field => $new_value) {
1751
-                        $model_obj_in_entity_map->set($field, $new_value);
1752
-                    }
1753
-                }
1754
-            }
1755
-            //if there is a primary key on this model, we can now do a slight optimization
1756
-            if ($this->has_primary_key_field()) {
1757
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1758
-                $query_params = array(
1759
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1760
-                    'limit'                    => count($model_objs_affected_ids),
1761
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1762
-                );
1763
-            }
1764
-        }
1765
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1766
-        $SQL = "UPDATE "
1767
-               . $model_query_info->get_full_join_sql()
1768
-               . " SET "
1769
-               . $this->_construct_update_sql($fields_n_values)
1770
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1771
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1772
-        /**
1773
-         * Action called after a model update call has been made.
1774
-         *
1775
-         * @param EEM_Base $model
1776
-         * @param array    $fields_n_values the updated fields and their new values
1777
-         * @param array    $query_params    @see EEM_Base::get_all()
1778
-         * @param int      $rows_affected
1779
-         */
1780
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1781
-        return $rows_affected;//how many supposedly got updated
1782
-    }
1783
-
1784
-
1785
-
1786
-    /**
1787
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1788
-     * are teh values of the field specified (or by default the primary key field)
1789
-     * that matched the query params. Note that you should pass the name of the
1790
-     * model FIELD, not the database table's column name.
1791
-     *
1792
-     * @param array  $query_params @see EEM_Base::get_all()
1793
-     * @param string $field_to_select
1794
-     * @return array just like $wpdb->get_col()
1795
-     * @throws EE_Error
1796
-     */
1797
-    public function get_col($query_params = array(), $field_to_select = null)
1798
-    {
1799
-        if ($field_to_select) {
1800
-            $field = $this->field_settings_for($field_to_select);
1801
-        } elseif ($this->has_primary_key_field()) {
1802
-            $field = $this->get_primary_key_field();
1803
-        } else {
1804
-            //no primary key, just grab the first column
1805
-            $field = reset($this->field_settings());
1806
-        }
1807
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1808
-        $select_expressions = $field->get_qualified_column();
1809
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1810
-        return $this->_do_wpdb_query('get_col', array($SQL));
1811
-    }
1812
-
1813
-
1814
-
1815
-    /**
1816
-     * Returns a single column value for a single row from the database
1817
-     *
1818
-     * @param array  $query_params    @see EEM_Base::get_all()
1819
-     * @param string $field_to_select @see EEM_Base::get_col()
1820
-     * @return string
1821
-     * @throws EE_Error
1822
-     */
1823
-    public function get_var($query_params = array(), $field_to_select = null)
1824
-    {
1825
-        $query_params['limit'] = 1;
1826
-        $col = $this->get_col($query_params, $field_to_select);
1827
-        if (! empty($col)) {
1828
-            return reset($col);
1829
-        }
1830
-        return null;
1831
-    }
1832
-
1833
-
1834
-
1835
-    /**
1836
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1837
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1838
-     * injection, but currently no further filtering is done
1839
-     *
1840
-     * @global      $wpdb
1841
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1842
-     *                               be updated to in the DB
1843
-     * @return string of SQL
1844
-     * @throws EE_Error
1845
-     */
1846
-    public function _construct_update_sql($fields_n_values)
1847
-    {
1848
-        /** @type WPDB $wpdb */
1849
-        global $wpdb;
1850
-        $cols_n_values = array();
1851
-        foreach ($fields_n_values as $field_name => $value) {
1852
-            $field_obj = $this->field_settings_for($field_name);
1853
-            //if the value is NULL, we want to assign the value to that.
1854
-            //wpdb->prepare doesn't really handle that properly
1855
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1856
-            $value_sql = $prepared_value === null ? 'NULL'
1857
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1858
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1859
-        }
1860
-        return implode(",", $cols_n_values);
1861
-    }
1862
-
1863
-
1864
-
1865
-    /**
1866
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1867
-     * Performs a HARD delete, meaning the database row should always be removed,
1868
-     * not just have a flag field on it switched
1869
-     * Wrapper for EEM_Base::delete_permanently()
1870
-     *
1871
-     * @param mixed $id
1872
-     * @return boolean whether the row got deleted or not
1873
-     * @throws EE_Error
1874
-     */
1875
-    public function delete_permanently_by_ID($id)
1876
-    {
1877
-        return $this->delete_permanently(
1878
-            array(
1879
-                array($this->get_primary_key_field()->get_name() => $id),
1880
-                'limit' => 1,
1881
-            )
1882
-        );
1883
-    }
1884
-
1885
-
1886
-
1887
-    /**
1888
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1889
-     * Wrapper for EEM_Base::delete()
1890
-     *
1891
-     * @param mixed $id
1892
-     * @return boolean whether the row got deleted or not
1893
-     * @throws EE_Error
1894
-     */
1895
-    public function delete_by_ID($id)
1896
-    {
1897
-        return $this->delete(
1898
-            array(
1899
-                array($this->get_primary_key_field()->get_name() => $id),
1900
-                'limit' => 1,
1901
-            )
1902
-        );
1903
-    }
1904
-
1905
-
1906
-
1907
-    /**
1908
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1909
-     * meaning if the model has a field that indicates its been "trashed" or
1910
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1911
-     *
1912
-     * @see EEM_Base::delete_permanently
1913
-     * @param array   $query_params
1914
-     * @param boolean $allow_blocking
1915
-     * @return int how many rows got deleted
1916
-     * @throws EE_Error
1917
-     */
1918
-    public function delete($query_params, $allow_blocking = true)
1919
-    {
1920
-        return $this->delete_permanently($query_params, $allow_blocking);
1921
-    }
1922
-
1923
-
1924
-
1925
-    /**
1926
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1927
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1928
-     * as archived, not actually deleted
1929
-     *
1930
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1931
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1932
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1933
-     *                                deletes regardless of other objects which may depend on it. Its generally
1934
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1935
-     *                                DB
1936
-     * @return int how many rows got deleted
1937
-     * @throws EE_Error
1938
-     */
1939
-    public function delete_permanently($query_params, $allow_blocking = true)
1940
-    {
1941
-        /**
1942
-         * Action called just before performing a real deletion query. You can use the
1943
-         * model and its $query_params to find exactly which items will be deleted
1944
-         *
1945
-         * @param EEM_Base $model
1946
-         * @param array    $query_params   @see EEM_Base::get_all()
1947
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1948
-         *                                 to block (prevent) this deletion
1949
-         */
1950
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1951
-        //some MySQL databases may be running safe mode, which may restrict
1952
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1953
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1954
-        //to delete them
1955
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1956
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1957
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1958
-            $columns_and_ids_for_deleting
1959
-        );
1960
-        /**
1961
-         * Allows client code to act on the items being deleted before the query is actually executed.
1962
-         *
1963
-         * @param EEM_Base $this  The model instance being acted on.
1964
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1965
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1966
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1967
-         *                                                  derived from the incoming query parameters.
1968
-         *                                                  @see details on the structure of this array in the phpdocs
1969
-         *                                                  for the `_get_ids_for_delete_method`
1970
-         *
1971
-         */
1972
-        do_action('AHEE__EEM_Base__delete__before_query',
1973
-            $this,
1974
-            $query_params,
1975
-            $allow_blocking,
1976
-            $columns_and_ids_for_deleting
1977
-        );
1978
-        if ($deletion_where_query_part) {
1979
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1980
-            $table_aliases = array_keys($this->_tables);
1981
-            $SQL = "DELETE "
1982
-                   . implode(", ", $table_aliases)
1983
-                   . " FROM "
1984
-                   . $model_query_info->get_full_join_sql()
1985
-                   . " WHERE "
1986
-                   . $deletion_where_query_part;
1987
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1988
-        } else {
1989
-            $rows_deleted = 0;
1990
-        }
1991
-
1992
-        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1993
-        //there was no error with the delete query.
1994
-        if ($this->has_primary_key_field()
1995
-            && $rows_deleted !== false
1996
-            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1997
-        ) {
1998
-            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1999
-            foreach ($ids_for_removal as $id) {
2000
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2001
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2002
-                }
2003
-            }
2004
-
2005
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2006
-            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2007
-            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2008
-            // (although it is possible).
2009
-            //Note this can be skipped by using the provided filter and returning false.
2010
-            if (apply_filters(
2011
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2012
-                ! $this instanceof EEM_Extra_Meta,
2013
-                $this
2014
-            )) {
2015
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2016
-                    0 => array(
2017
-                        'EXM_type' => $this->get_this_model_name(),
2018
-                        'OBJ_ID'   => array(
2019
-                            'IN',
2020
-                            $ids_for_removal
2021
-                        )
2022
-                    )
2023
-                ));
2024
-            }
2025
-        }
2026
-
2027
-        /**
2028
-         * Action called just after performing a real deletion query. Although at this point the
2029
-         * items should have been deleted
2030
-         *
2031
-         * @param EEM_Base $model
2032
-         * @param array    $query_params @see EEM_Base::get_all()
2033
-         * @param int      $rows_deleted
2034
-         */
2035
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2036
-        return $rows_deleted;//how many supposedly got deleted
2037
-    }
2038
-
2039
-
2040
-
2041
-    /**
2042
-     * Checks all the relations that throw error messages when there are blocking related objects
2043
-     * for related model objects. If there are any related model objects on those relations,
2044
-     * adds an EE_Error, and return true
2045
-     *
2046
-     * @param EE_Base_Class|int $this_model_obj_or_id
2047
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2048
-     *                                                 should be ignored when determining whether there are related
2049
-     *                                                 model objects which block this model object's deletion. Useful
2050
-     *                                                 if you know A is related to B and are considering deleting A,
2051
-     *                                                 but want to see if A has any other objects blocking its deletion
2052
-     *                                                 before removing the relation between A and B
2053
-     * @return boolean
2054
-     * @throws EE_Error
2055
-     */
2056
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2057
-    {
2058
-        //first, if $ignore_this_model_obj was supplied, get its model
2059
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2060
-            $ignored_model = $ignore_this_model_obj->get_model();
2061
-        } else {
2062
-            $ignored_model = null;
2063
-        }
2064
-        //now check all the relations of $this_model_obj_or_id and see if there
2065
-        //are any related model objects blocking it?
2066
-        $is_blocked = false;
2067
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2068
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2069
-                //if $ignore_this_model_obj was supplied, then for the query
2070
-                //on that model needs to be told to ignore $ignore_this_model_obj
2071
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2072
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2073
-                        array(
2074
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2075
-                                '!=',
2076
-                                $ignore_this_model_obj->ID(),
2077
-                            ),
2078
-                        ),
2079
-                    ));
2080
-                } else {
2081
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2082
-                }
2083
-                if ($related_model_objects) {
2084
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2085
-                    $is_blocked = true;
2086
-                }
2087
-            }
2088
-        }
2089
-        return $is_blocked;
2090
-    }
2091
-
2092
-
2093
-    /**
2094
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2095
-     * @param array $row_results_for_deleting
2096
-     * @param bool  $allow_blocking
2097
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2098
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2099
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2100
-     *                 deleted. Example:
2101
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2102
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2103
-     *                 where each element is a group of columns and values that get deleted. Example:
2104
-     *                      array(
2105
-     *                          0 => array(
2106
-     *                              'Term_Relationship.object_id' => 1
2107
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2108
-     *                          ),
2109
-     *                          1 => array(
2110
-     *                              'Term_Relationship.object_id' => 1
2111
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2112
-     *                          )
2113
-     *                      )
2114
-     * @throws EE_Error
2115
-     */
2116
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2117
-    {
2118
-        $ids_to_delete_indexed_by_column = array();
2119
-        if ($this->has_primary_key_field()) {
2120
-            $primary_table = $this->_get_main_table();
2121
-            $other_tables = $this->_get_other_tables();
2122
-            $ids_to_delete_indexed_by_column = $query = array();
2123
-            foreach ($row_results_for_deleting as $item_to_delete) {
2124
-                //before we mark this item for deletion,
2125
-                //make sure there's no related entities blocking its deletion (if we're checking)
2126
-                if (
2127
-                    $allow_blocking
2128
-                    && $this->delete_is_blocked_by_related_models(
2129
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2130
-                    )
2131
-                ) {
2132
-                    continue;
2133
-                }
2134
-                //primary table deletes
2135
-                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2136
-                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2137
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2138
-                }
2139
-            }
2140
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2141
-            $fields = $this->get_combined_primary_key_fields();
2142
-            foreach ($row_results_for_deleting as $item_to_delete) {
2143
-                $ids_to_delete_indexed_by_column_for_row = array();
2144
-                foreach ($fields as $cpk_field) {
2145
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2146
-                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2147
-                            $item_to_delete[$cpk_field->get_qualified_column()];
2148
-                    }
2149
-                }
2150
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2151
-            }
2152
-        } else {
2153
-            //so there's no primary key and no combined key...
2154
-            //sorry, can't help you
2155
-            throw new EE_Error(
2156
-                sprintf(
2157
-                    __(
2158
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2159
-                        "event_espresso"
2160
-                    ), get_class($this)
2161
-                )
2162
-            );
2163
-        }
2164
-        return $ids_to_delete_indexed_by_column;
2165
-    }
2166
-
2167
-
2168
-    /**
2169
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2170
-     * the corresponding query_part for the query performing the delete.
2171
-     *
2172
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2173
-     * @return string
2174
-     * @throws EE_Error
2175
-     */
2176
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2177
-        $query_part = '';
2178
-        if (empty($ids_to_delete_indexed_by_column)) {
2179
-            return $query_part;
2180
-        } elseif ($this->has_primary_key_field()) {
2181
-            $query = array();
2182
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2183
-                //make sure we have unique $ids
2184
-                $ids = array_unique($ids);
2185
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2186
-            }
2187
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2188
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2189
-            $ways_to_identify_a_row = array();
2190
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2191
-                $values_for_each_combined_primary_key_for_a_row = array();
2192
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2193
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2194
-                }
2195
-                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2196
-            }
2197
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2198
-        }
2199
-        return $query_part;
2200
-    }
2201
-
2202
-
2203
-
2204
-
2205
-    /**
2206
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2207
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2208
-     * column
2209
-     *
2210
-     * @param array  $query_params   like EEM_Base::get_all's
2211
-     * @param string $field_to_count field on model to count by (not column name)
2212
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2213
-     *                               that by the setting $distinct to TRUE;
2214
-     * @return int
2215
-     * @throws EE_Error
2216
-     */
2217
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2218
-    {
2219
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2220
-        if ($field_to_count) {
2221
-            $field_obj = $this->field_settings_for($field_to_count);
2222
-            $column_to_count = $field_obj->get_qualified_column();
2223
-        } elseif ($this->has_primary_key_field()) {
2224
-            $pk_field_obj = $this->get_primary_key_field();
2225
-            $column_to_count = $pk_field_obj->get_qualified_column();
2226
-        } else {
2227
-            //there's no primary key
2228
-            //if we're counting distinct items, and there's no primary key,
2229
-            //we need to list out the columns for distinction;
2230
-            //otherwise we can just use star
2231
-            if ($distinct) {
2232
-                $columns_to_use = array();
2233
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2234
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2235
-                }
2236
-                $column_to_count = implode(',', $columns_to_use);
2237
-            } else {
2238
-                $column_to_count = '*';
2239
-            }
2240
-        }
2241
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2242
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2243
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2244
-    }
2245
-
2246
-
2247
-
2248
-    /**
2249
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2250
-     *
2251
-     * @param array  $query_params like EEM_Base::get_all
2252
-     * @param string $field_to_sum name of field (array key in $_fields array)
2253
-     * @return float
2254
-     * @throws EE_Error
2255
-     */
2256
-    public function sum($query_params, $field_to_sum = null)
2257
-    {
2258
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2259
-        if ($field_to_sum) {
2260
-            $field_obj = $this->field_settings_for($field_to_sum);
2261
-        } else {
2262
-            $field_obj = $this->get_primary_key_field();
2263
-        }
2264
-        $column_to_count = $field_obj->get_qualified_column();
2265
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2266
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2267
-        $data_type = $field_obj->get_wpdb_data_type();
2268
-        if ($data_type === '%d' || $data_type === '%s') {
2269
-            return (float)$return_value;
2270
-        }
2271
-        //must be %f
2272
-        return (float)$return_value;
2273
-    }
2274
-
2275
-
2276
-
2277
-    /**
2278
-     * Just calls the specified method on $wpdb with the given arguments
2279
-     * Consolidates a little extra error handling code
2280
-     *
2281
-     * @param string $wpdb_method
2282
-     * @param array  $arguments_to_provide
2283
-     * @throws EE_Error
2284
-     * @global wpdb  $wpdb
2285
-     * @return mixed
2286
-     */
2287
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2288
-    {
2289
-        //if we're in maintenance mode level 2, DON'T run any queries
2290
-        //because level 2 indicates the database needs updating and
2291
-        //is probably out of sync with the code
2292
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2293
-            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.",
2294
-                "event_espresso")));
2295
-        }
2296
-        /** @type WPDB $wpdb */
2297
-        global $wpdb;
2298
-        if (! method_exists($wpdb, $wpdb_method)) {
2299
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2300
-                'event_espresso'), $wpdb_method));
2301
-        }
2302
-        if (WP_DEBUG) {
2303
-            $old_show_errors_value = $wpdb->show_errors;
2304
-            $wpdb->show_errors(false);
2305
-        }
2306
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2307
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2308
-        if (WP_DEBUG) {
2309
-            $wpdb->show_errors($old_show_errors_value);
2310
-            if (! empty($wpdb->last_error)) {
2311
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2312
-            }
2313
-            if ($result === false) {
2314
-                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"',
2315
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2316
-            }
2317
-        } elseif ($result === false) {
2318
-            EE_Error::add_error(
2319
-                sprintf(
2320
-                    __('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"',
2321
-                        'event_espresso'),
2322
-                    $wpdb_method,
2323
-                    var_export($arguments_to_provide, true),
2324
-                    $wpdb->last_error
2325
-                ),
2326
-                __FILE__,
2327
-                __FUNCTION__,
2328
-                __LINE__
2329
-            );
2330
-        }
2331
-        return $result;
2332
-    }
2333
-
2334
-
2335
-
2336
-    /**
2337
-     * Attempts to run the indicated WPDB method with the provided arguments,
2338
-     * and if there's an error tries to verify the DB is correct. Uses
2339
-     * the static property EEM_Base::$_db_verification_level to determine whether
2340
-     * we should try to fix the EE core db, the addons, or just give up
2341
-     *
2342
-     * @param string $wpdb_method
2343
-     * @param array  $arguments_to_provide
2344
-     * @return mixed
2345
-     */
2346
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2347
-    {
2348
-        /** @type WPDB $wpdb */
2349
-        global $wpdb;
2350
-        $wpdb->last_error = null;
2351
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2352
-        // was there an error running the query? but we don't care on new activations
2353
-        // (we're going to setup the DB anyway on new activations)
2354
-        if (($result === false || ! empty($wpdb->last_error))
2355
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2356
-        ) {
2357
-            switch (EEM_Base::$_db_verification_level) {
2358
-                case EEM_Base::db_verified_none :
2359
-                    // let's double-check core's DB
2360
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2361
-                    break;
2362
-                case EEM_Base::db_verified_core :
2363
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2364
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2365
-                    break;
2366
-                case EEM_Base::db_verified_addons :
2367
-                    // ummmm... you in trouble
2368
-                    return $result;
2369
-                    break;
2370
-            }
2371
-            if (! empty($error_message)) {
2372
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2373
-                trigger_error($error_message);
2374
-            }
2375
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2376
-        }
2377
-        return $result;
2378
-    }
2379
-
2380
-
2381
-
2382
-    /**
2383
-     * Verifies the EE core database is up-to-date and records that we've done it on
2384
-     * EEM_Base::$_db_verification_level
2385
-     *
2386
-     * @param string $wpdb_method
2387
-     * @param array  $arguments_to_provide
2388
-     * @return string
2389
-     */
2390
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2391
-    {
2392
-        /** @type WPDB $wpdb */
2393
-        global $wpdb;
2394
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2395
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2396
-        $error_message = sprintf(
2397
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2398
-                'event_espresso'),
2399
-            $wpdb->last_error,
2400
-            $wpdb_method,
2401
-            wp_json_encode($arguments_to_provide)
2402
-        );
2403
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2404
-        return $error_message;
2405
-    }
2406
-
2407
-
2408
-
2409
-    /**
2410
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2411
-     * EEM_Base::$_db_verification_level
2412
-     *
2413
-     * @param $wpdb_method
2414
-     * @param $arguments_to_provide
2415
-     * @return string
2416
-     */
2417
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2418
-    {
2419
-        /** @type WPDB $wpdb */
2420
-        global $wpdb;
2421
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2422
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2423
-        $error_message = sprintf(
2424
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2425
-                'event_espresso'),
2426
-            $wpdb->last_error,
2427
-            $wpdb_method,
2428
-            wp_json_encode($arguments_to_provide)
2429
-        );
2430
-        EE_System::instance()->initialize_addons();
2431
-        return $error_message;
2432
-    }
2433
-
2434
-
2435
-
2436
-    /**
2437
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2438
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2439
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2440
-     * ..."
2441
-     *
2442
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2443
-     * @return string
2444
-     */
2445
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2446
-    {
2447
-        return " FROM " . $model_query_info->get_full_join_sql() .
2448
-               $model_query_info->get_where_sql() .
2449
-               $model_query_info->get_group_by_sql() .
2450
-               $model_query_info->get_having_sql() .
2451
-               $model_query_info->get_order_by_sql() .
2452
-               $model_query_info->get_limit_sql();
2453
-    }
2454
-
2455
-
2456
-
2457
-    /**
2458
-     * Set to easily debug the next X queries ran from this model.
2459
-     *
2460
-     * @param int $count
2461
-     */
2462
-    public function show_next_x_db_queries($count = 1)
2463
-    {
2464
-        $this->_show_next_x_db_queries = $count;
2465
-    }
2466
-
2467
-
2468
-
2469
-    /**
2470
-     * @param $sql_query
2471
-     */
2472
-    public function show_db_query_if_previously_requested($sql_query)
2473
-    {
2474
-        if ($this->_show_next_x_db_queries > 0) {
2475
-            echo $sql_query;
2476
-            $this->_show_next_x_db_queries--;
2477
-        }
2478
-    }
2479
-
2480
-
2481
-
2482
-    /**
2483
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2484
-     * There are the 3 cases:
2485
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2486
-     * $otherModelObject has no ID, it is first saved.
2487
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2488
-     * has no ID, it is first saved.
2489
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2490
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2491
-     * join table
2492
-     *
2493
-     * @param        EE_Base_Class                     /int $thisModelObject
2494
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2495
-     * @param string $relationName                     , key in EEM_Base::_relations
2496
-     *                                                 an attendee to a group, you also want to specify which role they
2497
-     *                                                 will have in that group. So you would use this parameter to
2498
-     *                                                 specify array('role-column-name'=>'role-id')
2499
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2500
-     *                                                 to for relation to methods that allow you to further specify
2501
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2502
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2503
-     *                                                 because these will be inserted in any new rows created as well.
2504
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2505
-     * @throws EE_Error
2506
-     */
2507
-    public function add_relationship_to(
2508
-        $id_or_obj,
2509
-        $other_model_id_or_obj,
2510
-        $relationName,
2511
-        $extra_join_model_fields_n_values = array()
2512
-    ) {
2513
-        $relation_obj = $this->related_settings_for($relationName);
2514
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2515
-    }
2516
-
2517
-
2518
-
2519
-    /**
2520
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2521
-     * There are the 3 cases:
2522
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2523
-     * error
2524
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2525
-     * an error
2526
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2527
-     *
2528
-     * @param        EE_Base_Class /int $id_or_obj
2529
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2530
-     * @param string $relationName key in EEM_Base::_relations
2531
-     * @return boolean of success
2532
-     * @throws EE_Error
2533
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2534
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2535
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2536
-     *                             because these will be inserted in any new rows created as well.
2537
-     */
2538
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2539
-    {
2540
-        $relation_obj = $this->related_settings_for($relationName);
2541
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2542
-    }
2543
-
2544
-
2545
-
2546
-    /**
2547
-     * @param mixed           $id_or_obj
2548
-     * @param string          $relationName
2549
-     * @param array           $where_query_params
2550
-     * @param EE_Base_Class[] objects to which relations were removed
2551
-     * @return \EE_Base_Class[]
2552
-     * @throws EE_Error
2553
-     */
2554
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2555
-    {
2556
-        $relation_obj = $this->related_settings_for($relationName);
2557
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2558
-    }
2559
-
2560
-
2561
-
2562
-    /**
2563
-     * Gets all the related items of the specified $model_name, using $query_params.
2564
-     * Note: by default, we remove the "default query params"
2565
-     * because we want to get even deleted items etc.
2566
-     *
2567
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2568
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2569
-     * @param array  $query_params like EEM_Base::get_all
2570
-     * @return EE_Base_Class[]
2571
-     * @throws EE_Error
2572
-     */
2573
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2574
-    {
2575
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2576
-        $relation_settings = $this->related_settings_for($model_name);
2577
-        return $relation_settings->get_all_related($model_obj, $query_params);
2578
-    }
2579
-
2580
-
2581
-
2582
-    /**
2583
-     * Deletes all the model objects across the relation indicated by $model_name
2584
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2585
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2586
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2587
-     *
2588
-     * @param EE_Base_Class|int|string $id_or_obj
2589
-     * @param string                   $model_name
2590
-     * @param array                    $query_params
2591
-     * @return int how many deleted
2592
-     * @throws EE_Error
2593
-     */
2594
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2595
-    {
2596
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2597
-        $relation_settings = $this->related_settings_for($model_name);
2598
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2599
-    }
2600
-
2601
-
2602
-
2603
-    /**
2604
-     * Hard deletes all the model objects across the relation indicated by $model_name
2605
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2606
-     * the model objects can't be hard deleted because of blocking related model objects,
2607
-     * just does a soft-delete on them instead.
2608
-     *
2609
-     * @param EE_Base_Class|int|string $id_or_obj
2610
-     * @param string                   $model_name
2611
-     * @param array                    $query_params
2612
-     * @return int how many deleted
2613
-     * @throws EE_Error
2614
-     */
2615
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2616
-    {
2617
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2618
-        $relation_settings = $this->related_settings_for($model_name);
2619
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2620
-    }
2621
-
2622
-
2623
-
2624
-    /**
2625
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2626
-     * unless otherwise specified in the $query_params
2627
-     *
2628
-     * @param        int             /EE_Base_Class $id_or_obj
2629
-     * @param string $model_name     like 'Event', or 'Registration'
2630
-     * @param array  $query_params   like EEM_Base::get_all's
2631
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2632
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2633
-     *                               that by the setting $distinct to TRUE;
2634
-     * @return int
2635
-     * @throws EE_Error
2636
-     */
2637
-    public function count_related(
2638
-        $id_or_obj,
2639
-        $model_name,
2640
-        $query_params = array(),
2641
-        $field_to_count = null,
2642
-        $distinct = false
2643
-    ) {
2644
-        $related_model = $this->get_related_model_obj($model_name);
2645
-        //we're just going to use the query params on the related model's normal get_all query,
2646
-        //except add a condition to say to match the current mod
2647
-        if (! isset($query_params['default_where_conditions'])) {
2648
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2649
-        }
2650
-        $this_model_name = $this->get_this_model_name();
2651
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2652
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2653
-        return $related_model->count($query_params, $field_to_count, $distinct);
2654
-    }
2655
-
2656
-
2657
-
2658
-    /**
2659
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2660
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2661
-     *
2662
-     * @param        int           /EE_Base_Class $id_or_obj
2663
-     * @param string $model_name   like 'Event', or 'Registration'
2664
-     * @param array  $query_params like EEM_Base::get_all's
2665
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2666
-     * @return float
2667
-     * @throws EE_Error
2668
-     */
2669
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2670
-    {
2671
-        $related_model = $this->get_related_model_obj($model_name);
2672
-        if (! is_array($query_params)) {
2673
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2674
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2675
-                    gettype($query_params)), '4.6.0');
2676
-            $query_params = array();
2677
-        }
2678
-        //we're just going to use the query params on the related model's normal get_all query,
2679
-        //except add a condition to say to match the current mod
2680
-        if (! isset($query_params['default_where_conditions'])) {
2681
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682
-        }
2683
-        $this_model_name = $this->get_this_model_name();
2684
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2686
-        return $related_model->sum($query_params, $field_to_sum);
2687
-    }
2688
-
2689
-
2690
-
2691
-    /**
2692
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2693
-     * $modelObject
2694
-     *
2695
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2696
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2697
-     * @param array               $query_params     like EEM_Base::get_all's
2698
-     * @return EE_Base_Class
2699
-     * @throws EE_Error
2700
-     */
2701
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2702
-    {
2703
-        $query_params['limit'] = 1;
2704
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2705
-        if ($results) {
2706
-            return array_shift($results);
2707
-        }
2708
-        return null;
2709
-    }
2710
-
2711
-
2712
-
2713
-    /**
2714
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2715
-     *
2716
-     * @return string
2717
-     */
2718
-    public function get_this_model_name()
2719
-    {
2720
-        return str_replace("EEM_", "", get_class($this));
2721
-    }
2722
-
2723
-
2724
-
2725
-    /**
2726
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2727
-     *
2728
-     * @return EE_Any_Foreign_Model_Name_Field
2729
-     * @throws EE_Error
2730
-     */
2731
-    public function get_field_containing_related_model_name()
2732
-    {
2733
-        foreach ($this->field_settings(true) as $field) {
2734
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2735
-                $field_with_model_name = $field;
2736
-            }
2737
-        }
2738
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2739
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2740
-                $this->get_this_model_name()));
2741
-        }
2742
-        return $field_with_model_name;
2743
-    }
2744
-
2745
-
2746
-
2747
-    /**
2748
-     * Inserts a new entry into the database, for each table.
2749
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2750
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2751
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2752
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2753
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2754
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2755
-     *
2756
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2757
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2758
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2759
-     *                              of EEM_Base)
2760
-     * @return int new primary key on main table that got inserted
2761
-     * @throws EE_Error
2762
-     */
2763
-    public function insert($field_n_values)
2764
-    {
2765
-        /**
2766
-         * Filters the fields and their values before inserting an item using the models
2767
-         *
2768
-         * @param array    $fields_n_values keys are the fields and values are their new values
2769
-         * @param EEM_Base $model           the model used
2770
-         */
2771
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2772
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2773
-            $main_table = $this->_get_main_table();
2774
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2775
-            if ($new_id !== false) {
2776
-                foreach ($this->_get_other_tables() as $other_table) {
2777
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2778
-                }
2779
-            }
2780
-            /**
2781
-             * Done just after attempting to insert a new model object
2782
-             *
2783
-             * @param EEM_Base   $model           used
2784
-             * @param array      $fields_n_values fields and their values
2785
-             * @param int|string the              ID of the newly-inserted model object
2786
-             */
2787
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2788
-            return $new_id;
2789
-        }
2790
-        return false;
2791
-    }
2792
-
2793
-
2794
-
2795
-    /**
2796
-     * Checks that the result would satisfy the unique indexes on this model
2797
-     *
2798
-     * @param array  $field_n_values
2799
-     * @param string $action
2800
-     * @return boolean
2801
-     * @throws EE_Error
2802
-     */
2803
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2804
-    {
2805
-        foreach ($this->unique_indexes() as $index_name => $index) {
2806
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2807
-            if ($this->exists(array($uniqueness_where_params))) {
2808
-                EE_Error::add_error(
2809
-                    sprintf(
2810
-                        __(
2811
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2812
-                            "event_espresso"
2813
-                        ),
2814
-                        $action,
2815
-                        $this->_get_class_name(),
2816
-                        $index_name,
2817
-                        implode(",", $index->field_names()),
2818
-                        http_build_query($uniqueness_where_params)
2819
-                    ),
2820
-                    __FILE__,
2821
-                    __FUNCTION__,
2822
-                    __LINE__
2823
-                );
2824
-                return false;
2825
-            }
2826
-        }
2827
-        return true;
2828
-    }
2829
-
2830
-
2831
-
2832
-    /**
2833
-     * Checks the database for an item that conflicts (ie, if this item were
2834
-     * saved to the DB would break some uniqueness requirement, like a primary key
2835
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2836
-     * can be either an EE_Base_Class or an array of fields n values
2837
-     *
2838
-     * @param EE_Base_Class|array $obj_or_fields_array
2839
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2840
-     *                                                 when looking for conflicts
2841
-     *                                                 (ie, if false, we ignore the model object's primary key
2842
-     *                                                 when finding "conflicts". If true, it's also considered).
2843
-     *                                                 Only works for INT primary key,
2844
-     *                                                 STRING primary keys cannot be ignored
2845
-     * @throws EE_Error
2846
-     * @return EE_Base_Class|array
2847
-     */
2848
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2849
-    {
2850
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2851
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2852
-        } elseif (is_array($obj_or_fields_array)) {
2853
-            $fields_n_values = $obj_or_fields_array;
2854
-        } else {
2855
-            throw new EE_Error(
2856
-                sprintf(
2857
-                    __(
2858
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2859
-                        "event_espresso"
2860
-                    ),
2861
-                    get_class($this),
2862
-                    $obj_or_fields_array
2863
-                )
2864
-            );
2865
-        }
2866
-        $query_params = array();
2867
-        if ($this->has_primary_key_field()
2868
-            && ($include_primary_key
2869
-                || $this->get_primary_key_field()
2870
-                   instanceof
2871
-                   EE_Primary_Key_String_Field)
2872
-            && isset($fields_n_values[$this->primary_key_name()])
2873
-        ) {
2874
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2875
-        }
2876
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2877
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2878
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2879
-        }
2880
-        //if there is nothing to base this search on, then we shouldn't find anything
2881
-        if (empty($query_params)) {
2882
-            return array();
2883
-        }
2884
-        return $this->get_one($query_params);
2885
-    }
2886
-
2887
-
2888
-
2889
-    /**
2890
-     * Like count, but is optimized and returns a boolean instead of an int
2891
-     *
2892
-     * @param array $query_params
2893
-     * @return boolean
2894
-     * @throws EE_Error
2895
-     */
2896
-    public function exists($query_params)
2897
-    {
2898
-        $query_params['limit'] = 1;
2899
-        return $this->count($query_params) > 0;
2900
-    }
2901
-
2902
-
2903
-
2904
-    /**
2905
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2906
-     *
2907
-     * @param int|string $id
2908
-     * @return boolean
2909
-     * @throws EE_Error
2910
-     */
2911
-    public function exists_by_ID($id)
2912
-    {
2913
-        return $this->exists(
2914
-            array(
2915
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2916
-                array(
2917
-                    $this->primary_key_name() => $id,
2918
-                ),
2919
-            )
2920
-        );
2921
-    }
2922
-
2923
-
2924
-
2925
-    /**
2926
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2927
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2928
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2929
-     * on the main table)
2930
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2931
-     * cases where we want to call it directly rather than via insert().
2932
-     *
2933
-     * @access   protected
2934
-     * @param EE_Table_Base $table
2935
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2936
-     *                                       float
2937
-     * @param int           $new_id          for now we assume only int keys
2938
-     * @throws EE_Error
2939
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2940
-     * @return int ID of new row inserted, or FALSE on failure
2941
-     */
2942
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2943
-    {
2944
-        global $wpdb;
2945
-        $insertion_col_n_values = array();
2946
-        $format_for_insertion = array();
2947
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2948
-        foreach ($fields_on_table as $field_name => $field_obj) {
2949
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2950
-            if ($field_obj->is_auto_increment()) {
2951
-                continue;
2952
-            }
2953
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2954
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2955
-            if ($prepared_value !== null) {
2956
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2957
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2958
-            }
2959
-        }
2960
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2961
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2962
-            //so add the fk to the main table as a column
2963
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2964
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2965
-        }
2966
-        //insert the new entry
2967
-        $result = $this->_do_wpdb_query('insert',
2968
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2969
-        if ($result === false) {
2970
-            return false;
2971
-        }
2972
-        //ok, now what do we return for the ID of the newly-inserted thing?
2973
-        if ($this->has_primary_key_field()) {
2974
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2975
-                return $wpdb->insert_id;
2976
-            }
2977
-            //it's not an auto-increment primary key, so
2978
-            //it must have been supplied
2979
-            return $fields_n_values[$this->get_primary_key_field()->get_name()];
2980
-        }
2981
-        //we can't return a  primary key because there is none. instead return
2982
-        //a unique string indicating this model
2983
-        return $this->get_index_primary_key_string($fields_n_values);
2984
-    }
2985
-
2986
-
2987
-
2988
-    /**
2989
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2990
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2991
-     * and there is no default, we pass it along. WPDB will take care of it)
2992
-     *
2993
-     * @param EE_Model_Field_Base $field_obj
2994
-     * @param array               $fields_n_values
2995
-     * @return mixed string|int|float depending on what the table column will be expecting
2996
-     * @throws EE_Error
2997
-     */
2998
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2999
-    {
3000
-        //if this field doesn't allow nullable, don't allow it
3001
-        if (
3002
-            ! $field_obj->is_nullable()
3003
-            && (
3004
-                ! isset($fields_n_values[$field_obj->get_name()])
3005
-                || $fields_n_values[$field_obj->get_name()] === null
3006
-            )
3007
-        ) {
3008
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3009
-        }
3010
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3011
-            ? $fields_n_values[$field_obj->get_name()]
3012
-            : null;
3013
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3014
-    }
3015
-
3016
-
3017
-
3018
-    /**
3019
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3020
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3021
-     * the field's prepare_for_set() method.
3022
-     *
3023
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3024
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3025
-     *                                   top of file)
3026
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3027
-     *                                   $value is a custom selection
3028
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3029
-     */
3030
-    private function _prepare_value_for_use_in_db($value, $field)
3031
-    {
3032
-        if ($field && $field instanceof EE_Model_Field_Base) {
3033
-            switch ($this->_values_already_prepared_by_model_object) {
3034
-                /** @noinspection PhpMissingBreakStatementInspection */
3035
-                case self::not_prepared_by_model_object:
3036
-                    $value = $field->prepare_for_set($value);
3037
-                //purposefully left out "return"
3038
-                case self::prepared_by_model_object:
3039
-                    /** @noinspection SuspiciousAssignmentsInspection */
3040
-                    $value = $field->prepare_for_use_in_db($value);
3041
-                case self::prepared_for_use_in_db:
3042
-                    //leave the value alone
3043
-            }
3044
-            return $value;
3045
-        }
3046
-        return $value;
3047
-    }
3048
-
3049
-
3050
-
3051
-    /**
3052
-     * Returns the main table on this model
3053
-     *
3054
-     * @return EE_Primary_Table
3055
-     * @throws EE_Error
3056
-     */
3057
-    protected function _get_main_table()
3058
-    {
3059
-        foreach ($this->_tables as $table) {
3060
-            if ($table instanceof EE_Primary_Table) {
3061
-                return $table;
3062
-            }
3063
-        }
3064
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3065
-            'event_espresso'), get_class($this)));
3066
-    }
3067
-
3068
-
3069
-
3070
-    /**
3071
-     * table
3072
-     * returns EE_Primary_Table table name
3073
-     *
3074
-     * @return string
3075
-     * @throws EE_Error
3076
-     */
3077
-    public function table()
3078
-    {
3079
-        return $this->_get_main_table()->get_table_name();
3080
-    }
3081
-
3082
-
3083
-
3084
-    /**
3085
-     * table
3086
-     * returns first EE_Secondary_Table table name
3087
-     *
3088
-     * @return string
3089
-     */
3090
-    public function second_table()
3091
-    {
3092
-        // grab second table from tables array
3093
-        $second_table = end($this->_tables);
3094
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3095
-    }
3096
-
3097
-
3098
-
3099
-    /**
3100
-     * get_table_obj_by_alias
3101
-     * returns table name given it's alias
3102
-     *
3103
-     * @param string $table_alias
3104
-     * @return EE_Primary_Table | EE_Secondary_Table
3105
-     */
3106
-    public function get_table_obj_by_alias($table_alias = '')
3107
-    {
3108
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3109
-    }
3110
-
3111
-
3112
-
3113
-    /**
3114
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3115
-     *
3116
-     * @return EE_Secondary_Table[]
3117
-     */
3118
-    protected function _get_other_tables()
3119
-    {
3120
-        $other_tables = array();
3121
-        foreach ($this->_tables as $table_alias => $table) {
3122
-            if ($table instanceof EE_Secondary_Table) {
3123
-                $other_tables[$table_alias] = $table;
3124
-            }
3125
-        }
3126
-        return $other_tables;
3127
-    }
3128
-
3129
-
3130
-
3131
-    /**
3132
-     * Finds all the fields that correspond to the given table
3133
-     *
3134
-     * @param string $table_alias , array key in EEM_Base::_tables
3135
-     * @return EE_Model_Field_Base[]
3136
-     */
3137
-    public function _get_fields_for_table($table_alias)
3138
-    {
3139
-        return $this->_fields[$table_alias];
3140
-    }
3141
-
3142
-
3143
-
3144
-    /**
3145
-     * Recurses through all the where parameters, and finds all the related models we'll need
3146
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3147
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3148
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3149
-     * related Registration, Transaction, and Payment models.
3150
-     *
3151
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3152
-     * @return EE_Model_Query_Info_Carrier
3153
-     * @throws EE_Error
3154
-     */
3155
-    public function _extract_related_models_from_query($query_params)
3156
-    {
3157
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3158
-        if (array_key_exists(0, $query_params)) {
3159
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3160
-        }
3161
-        if (array_key_exists('group_by', $query_params)) {
3162
-            if (is_array($query_params['group_by'])) {
3163
-                $this->_extract_related_models_from_sub_params_array_values(
3164
-                    $query_params['group_by'],
3165
-                    $query_info_carrier,
3166
-                    'group_by'
3167
-                );
3168
-            } elseif (! empty ($query_params['group_by'])) {
3169
-                $this->_extract_related_model_info_from_query_param(
3170
-                    $query_params['group_by'],
3171
-                    $query_info_carrier,
3172
-                    'group_by'
3173
-                );
3174
-            }
3175
-        }
3176
-        if (array_key_exists('having', $query_params)) {
3177
-            $this->_extract_related_models_from_sub_params_array_keys(
3178
-                $query_params[0],
3179
-                $query_info_carrier,
3180
-                'having'
3181
-            );
3182
-        }
3183
-        if (array_key_exists('order_by', $query_params)) {
3184
-            if (is_array($query_params['order_by'])) {
3185
-                $this->_extract_related_models_from_sub_params_array_keys(
3186
-                    $query_params['order_by'],
3187
-                    $query_info_carrier,
3188
-                    'order_by'
3189
-                );
3190
-            } elseif (! empty($query_params['order_by'])) {
3191
-                $this->_extract_related_model_info_from_query_param(
3192
-                    $query_params['order_by'],
3193
-                    $query_info_carrier,
3194
-                    'order_by'
3195
-                );
3196
-            }
3197
-        }
3198
-        if (array_key_exists('force_join', $query_params)) {
3199
-            $this->_extract_related_models_from_sub_params_array_values(
3200
-                $query_params['force_join'],
3201
-                $query_info_carrier,
3202
-                'force_join'
3203
-            );
3204
-        }
3205
-        return $query_info_carrier;
3206
-    }
3207
-
3208
-
3209
-
3210
-    /**
3211
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3212
-     *
3213
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3214
-     *                                                      $query_params['having']
3215
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3216
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3217
-     * @throws EE_Error
3218
-     * @return \EE_Model_Query_Info_Carrier
3219
-     */
3220
-    private function _extract_related_models_from_sub_params_array_keys(
3221
-        $sub_query_params,
3222
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3223
-        $query_param_type
3224
-    ) {
3225
-        if (! empty($sub_query_params)) {
3226
-            $sub_query_params = (array)$sub_query_params;
3227
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3228
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3229
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3230
-                    $query_param_type);
3231
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3232
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3233
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3234
-                //of array('Registration.TXN_ID'=>23)
3235
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3236
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3237
-                    if (! is_array($possibly_array_of_params)) {
3238
-                        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'))",
3239
-                            "event_espresso"),
3240
-                            $param, $possibly_array_of_params));
3241
-                    }
3242
-                    $this->_extract_related_models_from_sub_params_array_keys(
3243
-                        $possibly_array_of_params,
3244
-                        $model_query_info_carrier, $query_param_type
3245
-                    );
3246
-                } elseif ($query_param_type === 0 //ie WHERE
3247
-                          && is_array($possibly_array_of_params)
3248
-                          && isset($possibly_array_of_params[2])
3249
-                          && $possibly_array_of_params[2] == true
3250
-                ) {
3251
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3252
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3253
-                    //from which we should extract query parameters!
3254
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3255
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3256
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3257
-                    }
3258
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3259
-                        $model_query_info_carrier, $query_param_type);
3260
-                }
3261
-            }
3262
-        }
3263
-        return $model_query_info_carrier;
3264
-    }
3265
-
3266
-
3267
-
3268
-    /**
3269
-     * For extracting related models from forced_joins, where the array values contain the info about what
3270
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3271
-     *
3272
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3273
-     *                                                      $query_params['having']
3274
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3275
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3276
-     * @throws EE_Error
3277
-     * @return \EE_Model_Query_Info_Carrier
3278
-     */
3279
-    private function _extract_related_models_from_sub_params_array_values(
3280
-        $sub_query_params,
3281
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3282
-        $query_param_type
3283
-    ) {
3284
-        if (! empty($sub_query_params)) {
3285
-            if (! is_array($sub_query_params)) {
3286
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3287
-                    $sub_query_params));
3288
-            }
3289
-            foreach ($sub_query_params as $param) {
3290
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3291
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3292
-                    $query_param_type);
3293
-            }
3294
-        }
3295
-        return $model_query_info_carrier;
3296
-    }
3297
-
3298
-
3299
-
3300
-    /**
3301
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3302
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3303
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3304
-     * but use them in a different order. Eg, we need to know what models we are querying
3305
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3306
-     * other models before we can finalize the where clause SQL.
3307
-     *
3308
-     * @param array $query_params
3309
-     * @throws EE_Error
3310
-     * @return EE_Model_Query_Info_Carrier
3311
-     */
3312
-    public function _create_model_query_info_carrier($query_params)
3313
-    {
3314
-        if (! is_array($query_params)) {
3315
-            EE_Error::doing_it_wrong(
3316
-                'EEM_Base::_create_model_query_info_carrier',
3317
-                sprintf(
3318
-                    __(
3319
-                        '$query_params should be an array, you passed a variable of type %s',
3320
-                        'event_espresso'
3321
-                    ),
3322
-                    gettype($query_params)
3323
-                ),
3324
-                '4.6.0'
3325
-            );
3326
-            $query_params = array();
3327
-        }
3328
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3329
-        //first check if we should alter the query to account for caps or not
3330
-        //because the caps might require us to do extra joins
3331
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3332
-            $query_params[0] = $where_query_params = array_replace_recursive(
3333
-                $where_query_params,
3334
-                $this->caps_where_conditions(
3335
-                    $query_params['caps']
3336
-                )
3337
-            );
3338
-        }
3339
-        $query_object = $this->_extract_related_models_from_query($query_params);
3340
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3341
-        foreach ($where_query_params as $key => $value) {
3342
-            if (is_int($key)) {
3343
-                throw new EE_Error(
3344
-                    sprintf(
3345
-                        __(
3346
-                            "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.",
3347
-                            "event_espresso"
3348
-                        ),
3349
-                        $key,
3350
-                        var_export($value, true),
3351
-                        var_export($query_params, true),
3352
-                        get_class($this)
3353
-                    )
3354
-                );
3355
-            }
3356
-        }
3357
-        if (
3358
-            array_key_exists('default_where_conditions', $query_params)
3359
-            && ! empty($query_params['default_where_conditions'])
3360
-        ) {
3361
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3362
-        } else {
3363
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3364
-        }
3365
-        $where_query_params = array_merge(
3366
-            $this->_get_default_where_conditions_for_models_in_query(
3367
-                $query_object,
3368
-                $use_default_where_conditions,
3369
-                $where_query_params
3370
-            ),
3371
-            $where_query_params
3372
-        );
3373
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3374
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3375
-        // So we need to setup a subquery and use that for the main join.
3376
-        // Note for now this only works on the primary table for the model.
3377
-        // So for instance, you could set the limit array like this:
3378
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3379
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3380
-            $query_object->set_main_model_join_sql(
3381
-                $this->_construct_limit_join_select(
3382
-                    $query_params['on_join_limit'][0],
3383
-                    $query_params['on_join_limit'][1]
3384
-                )
3385
-            );
3386
-        }
3387
-        //set limit
3388
-        if (array_key_exists('limit', $query_params)) {
3389
-            if (is_array($query_params['limit'])) {
3390
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3391
-                    $e = sprintf(
3392
-                        __(
3393
-                            "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)",
3394
-                            "event_espresso"
3395
-                        ),
3396
-                        http_build_query($query_params['limit'])
3397
-                    );
3398
-                    throw new EE_Error($e . "|" . $e);
3399
-                }
3400
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3401
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3402
-            } elseif (! empty ($query_params['limit'])) {
3403
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3404
-            }
3405
-        }
3406
-        //set order by
3407
-        if (array_key_exists('order_by', $query_params)) {
3408
-            if (is_array($query_params['order_by'])) {
3409
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3410
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3411
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3412
-                if (array_key_exists('order', $query_params)) {
3413
-                    throw new EE_Error(
3414
-                        sprintf(
3415
-                            __(
3416
-                                "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 ",
3417
-                                "event_espresso"
3418
-                            ),
3419
-                            get_class($this),
3420
-                            implode(", ", array_keys($query_params['order_by'])),
3421
-                            implode(", ", $query_params['order_by']),
3422
-                            $query_params['order']
3423
-                        )
3424
-                    );
3425
-                }
3426
-                $this->_extract_related_models_from_sub_params_array_keys(
3427
-                    $query_params['order_by'],
3428
-                    $query_object,
3429
-                    'order_by'
3430
-                );
3431
-                //assume it's an array of fields to order by
3432
-                $order_array = array();
3433
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3434
-                    $order = $this->_extract_order($order);
3435
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3436
-                }
3437
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3438
-            } elseif (! empty ($query_params['order_by'])) {
3439
-                $this->_extract_related_model_info_from_query_param(
3440
-                    $query_params['order_by'],
3441
-                    $query_object,
3442
-                    'order',
3443
-                    $query_params['order_by']
3444
-                );
3445
-                $order = isset($query_params['order'])
3446
-                    ? $this->_extract_order($query_params['order'])
3447
-                    : 'DESC';
3448
-                $query_object->set_order_by_sql(
3449
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3450
-                );
3451
-            }
3452
-        }
3453
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3454
-        if (! array_key_exists('order_by', $query_params)
3455
-            && array_key_exists('order', $query_params)
3456
-            && ! empty($query_params['order'])
3457
-        ) {
3458
-            $pk_field = $this->get_primary_key_field();
3459
-            $order = $this->_extract_order($query_params['order']);
3460
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3461
-        }
3462
-        //set group by
3463
-        if (array_key_exists('group_by', $query_params)) {
3464
-            if (is_array($query_params['group_by'])) {
3465
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3466
-                $group_by_array = array();
3467
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3468
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3469
-                }
3470
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3471
-            } elseif (! empty ($query_params['group_by'])) {
3472
-                $query_object->set_group_by_sql(
3473
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3474
-                );
3475
-            }
3476
-        }
3477
-        //set having
3478
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3479
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3480
-        }
3481
-        //now, just verify they didn't pass anything wack
3482
-        foreach ($query_params as $query_key => $query_value) {
3483
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3484
-                throw new EE_Error(
3485
-                    sprintf(
3486
-                        __(
3487
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3488
-                            'event_espresso'
3489
-                        ),
3490
-                        $query_key,
3491
-                        get_class($this),
3492
-                        //						print_r( $this->_allowed_query_params, TRUE )
3493
-                        implode(',', $this->_allowed_query_params)
3494
-                    )
3495
-                );
3496
-            }
3497
-        }
3498
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3499
-        if (empty($main_model_join_sql)) {
3500
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3501
-        }
3502
-        return $query_object;
3503
-    }
3504
-
3505
-
3506
-
3507
-    /**
3508
-     * Gets the where conditions that should be imposed on the query based on the
3509
-     * context (eg reading frontend, backend, edit or delete).
3510
-     *
3511
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3512
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3513
-     * @throws EE_Error
3514
-     */
3515
-    public function caps_where_conditions($context = self::caps_read)
3516
-    {
3517
-        EEM_Base::verify_is_valid_cap_context($context);
3518
-        $cap_where_conditions = array();
3519
-        $cap_restrictions = $this->caps_missing($context);
3520
-        /**
3521
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3522
-         */
3523
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3524
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3525
-                $restriction_if_no_cap->get_default_where_conditions());
3526
-        }
3527
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3528
-            $cap_restrictions);
3529
-    }
3530
-
3531
-
3532
-
3533
-    /**
3534
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3535
-     * otherwise throws an exception
3536
-     *
3537
-     * @param string $should_be_order_string
3538
-     * @return string either ASC, asc, DESC or desc
3539
-     * @throws EE_Error
3540
-     */
3541
-    private function _extract_order($should_be_order_string)
3542
-    {
3543
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3544
-            return $should_be_order_string;
3545
-        }
3546
-        throw new EE_Error(
3547
-            sprintf(
3548
-                __(
3549
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3550
-                    "event_espresso"
3551
-                ), get_class($this), $should_be_order_string
3552
-            )
3553
-        );
3554
-    }
3555
-
3556
-
3557
-
3558
-    /**
3559
-     * Looks at all the models which are included in this query, and asks each
3560
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3561
-     * so they can be merged
3562
-     *
3563
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3564
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3565
-     *                                                                  'none' means NO default where conditions will
3566
-     *                                                                  be used AT ALL during this query.
3567
-     *                                                                  'other_models_only' means default where
3568
-     *                                                                  conditions from other models will be used, but
3569
-     *                                                                  not for this primary model. 'all', the default,
3570
-     *                                                                  means default where conditions will apply as
3571
-     *                                                                  normal
3572
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3573
-     * @throws EE_Error
3574
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3575
-     */
3576
-    private function _get_default_where_conditions_for_models_in_query(
3577
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3578
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3579
-        $where_query_params = array()
3580
-    ) {
3581
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3582
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3583
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3584
-                "event_espresso"), $use_default_where_conditions,
3585
-                implode(", ", $allowed_used_default_where_conditions_values)));
3586
-        }
3587
-        $universal_query_params = array();
3588
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3589
-            $universal_query_params = $this->_get_default_where_conditions();
3590
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3591
-            $universal_query_params = $this->_get_minimum_where_conditions();
3592
-        }
3593
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3594
-            $related_model = $this->get_related_model_obj($model_name);
3595
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3596
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3597
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3598
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3599
-            } else {
3600
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3601
-                continue;
3602
-            }
3603
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3604
-                $related_model_universal_where_params,
3605
-                $where_query_params,
3606
-                $related_model,
3607
-                $model_relation_path
3608
-            );
3609
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3610
-                $universal_query_params,
3611
-                $overrides
3612
-            );
3613
-        }
3614
-        return $universal_query_params;
3615
-    }
3616
-
3617
-
3618
-
3619
-    /**
3620
-     * Determines whether or not we should use default where conditions for the model in question
3621
-     * (this model, or other related models).
3622
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3623
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3624
-     * We should use default where conditions on related models when they requested to use default where conditions
3625
-     * on all models, or specifically just on other related models
3626
-     * @param      $default_where_conditions_value
3627
-     * @param bool $for_this_model false means this is for OTHER related models
3628
-     * @return bool
3629
-     */
3630
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3631
-    {
3632
-        return (
3633
-                   $for_this_model
3634
-                   && in_array(
3635
-                       $default_where_conditions_value,
3636
-                       array(
3637
-                           EEM_Base::default_where_conditions_all,
3638
-                           EEM_Base::default_where_conditions_this_only,
3639
-                           EEM_Base::default_where_conditions_minimum_others,
3640
-                       ),
3641
-                       true
3642
-                   )
3643
-               )
3644
-               || (
3645
-                   ! $for_this_model
3646
-                   && in_array(
3647
-                       $default_where_conditions_value,
3648
-                       array(
3649
-                           EEM_Base::default_where_conditions_all,
3650
-                           EEM_Base::default_where_conditions_others_only,
3651
-                       ),
3652
-                       true
3653
-                   )
3654
-               );
3655
-    }
3656
-
3657
-    /**
3658
-     * Determines whether or not we should use default minimum conditions for the model in question
3659
-     * (this model, or other related models).
3660
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3661
-     * where conditions.
3662
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3663
-     * on this model or others
3664
-     * @param      $default_where_conditions_value
3665
-     * @param bool $for_this_model false means this is for OTHER related models
3666
-     * @return bool
3667
-     */
3668
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3669
-    {
3670
-        return (
3671
-                   $for_this_model
3672
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3673
-               )
3674
-               || (
3675
-                   ! $for_this_model
3676
-                   && in_array(
3677
-                       $default_where_conditions_value,
3678
-                       array(
3679
-                           EEM_Base::default_where_conditions_minimum_others,
3680
-                           EEM_Base::default_where_conditions_minimum_all,
3681
-                       ),
3682
-                       true
3683
-                   )
3684
-               );
3685
-    }
3686
-
3687
-
3688
-    /**
3689
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3690
-     * then we also add a special where condition which allows for that model's primary key
3691
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3692
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3693
-     *
3694
-     * @param array    $default_where_conditions
3695
-     * @param array    $provided_where_conditions
3696
-     * @param EEM_Base $model
3697
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3698
-     * @return array like EEM_Base::get_all's $query_params[0]
3699
-     * @throws EE_Error
3700
-     */
3701
-    private function _override_defaults_or_make_null_friendly(
3702
-        $default_where_conditions,
3703
-        $provided_where_conditions,
3704
-        $model,
3705
-        $model_relation_path
3706
-    ) {
3707
-        $null_friendly_where_conditions = array();
3708
-        $none_overridden = true;
3709
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3710
-        foreach ($default_where_conditions as $key => $val) {
3711
-            if (isset($provided_where_conditions[$key])) {
3712
-                $none_overridden = false;
3713
-            } else {
3714
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3715
-            }
3716
-        }
3717
-        if ($none_overridden && $default_where_conditions) {
3718
-            if ($model->has_primary_key_field()) {
3719
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3720
-                                                                                . "."
3721
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3722
-            }/*else{
35
+	//admin posty
36
+	//basic -> grants access to mine -> if they don't have it, select none
37
+	//*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
38
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
39
+	//*_published -> grants access to published -> if they dont have it, select non-published
40
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
41
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
42
+	//frontend posty
43
+	//by default has access to published
44
+	//basic -> grants access to mine that aren't published, and all published
45
+	//*_others ->grants access to others that aren't private, all mine
46
+	//*_private -> grants full access
47
+	//frontend non-posty
48
+	//like admin posty
49
+	//category-y
50
+	//assign -> grants access to join-table
51
+	//(delete, edit)
52
+	//payment-method-y
53
+	//for each registered payment method,
54
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
55
+	/**
56
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
57
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
58
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
59
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
60
+	 *
61
+	 * @var boolean
62
+	 */
63
+	private $_values_already_prepared_by_model_object = 0;
64
+
65
+	/**
66
+	 * when $_values_already_prepared_by_model_object equals this, we assume
67
+	 * the data is just like form input that needs to have the model fields'
68
+	 * prepare_for_set and prepare_for_use_in_db called on it
69
+	 */
70
+	const not_prepared_by_model_object = 0;
71
+
72
+	/**
73
+	 * when $_values_already_prepared_by_model_object equals this, we
74
+	 * assume this value is coming from a model object and doesn't need to have
75
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
76
+	 */
77
+	const prepared_by_model_object = 1;
78
+
79
+	/**
80
+	 * when $_values_already_prepared_by_model_object equals this, we assume
81
+	 * the values are already to be used in the database (ie no processing is done
82
+	 * on them by the model's fields)
83
+	 */
84
+	const prepared_for_use_in_db = 2;
85
+
86
+
87
+	protected $singular_item = 'Item';
88
+
89
+	protected $plural_item   = 'Items';
90
+
91
+	/**
92
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
93
+	 */
94
+	protected $_tables;
95
+
96
+	/**
97
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
98
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
99
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
100
+	 *
101
+	 * @var \EE_Model_Field_Base[] $_fields
102
+	 */
103
+	protected $_fields;
104
+
105
+	/**
106
+	 * array of different kinds of relations
107
+	 *
108
+	 * @var \EE_Model_Relation_Base[] $_model_relations
109
+	 */
110
+	protected $_model_relations;
111
+
112
+	/**
113
+	 * @var \EE_Index[] $_indexes
114
+	 */
115
+	protected $_indexes = array();
116
+
117
+	/**
118
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
119
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
120
+	 * by setting the same columns as used in these queries in the query yourself.
121
+	 *
122
+	 * @var EE_Default_Where_Conditions
123
+	 */
124
+	protected $_default_where_conditions_strategy;
125
+
126
+	/**
127
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
128
+	 * This is particularly useful when you want something between 'none' and 'default'
129
+	 *
130
+	 * @var EE_Default_Where_Conditions
131
+	 */
132
+	protected $_minimum_where_conditions_strategy;
133
+
134
+	/**
135
+	 * String describing how to find the "owner" of this model's objects.
136
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
137
+	 * But when there isn't, this indicates which related model, or transiently-related model,
138
+	 * has the foreign key to the wp_users table.
139
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
140
+	 * related to events, and events have a foreign key to wp_users.
141
+	 * On EEM_Transaction, this would be 'Transaction.Event'
142
+	 *
143
+	 * @var string
144
+	 */
145
+	protected $_model_chain_to_wp_user = '';
146
+
147
+	/**
148
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
149
+	 * don't need it (particularly CPT models)
150
+	 *
151
+	 * @var bool
152
+	 */
153
+	protected $_ignore_where_strategy = false;
154
+
155
+	/**
156
+	 * String used in caps relating to this model. Eg, if the caps relating to this
157
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
158
+	 *
159
+	 * @var string. If null it hasn't been initialized yet. If false then we
160
+	 * have indicated capabilities don't apply to this
161
+	 */
162
+	protected $_caps_slug = null;
163
+
164
+	/**
165
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
166
+	 * and next-level keys are capability names, and each's value is a
167
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
168
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
169
+	 * and then each capability in the corresponding sub-array that they're missing
170
+	 * adds the where conditions onto the query.
171
+	 *
172
+	 * @var array
173
+	 */
174
+	protected $_cap_restrictions = array(
175
+		self::caps_read       => array(),
176
+		self::caps_read_admin => array(),
177
+		self::caps_edit       => array(),
178
+		self::caps_delete     => array(),
179
+	);
180
+
181
+	/**
182
+	 * Array defining which cap restriction generators to use to create default
183
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
184
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
185
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
186
+	 * automatically set this to false (not just null).
187
+	 *
188
+	 * @var EE_Restriction_Generator_Base[]
189
+	 */
190
+	protected $_cap_restriction_generators = array();
191
+
192
+	/**
193
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
194
+	 */
195
+	const caps_read       = 'read';
196
+
197
+	const caps_read_admin = 'read_admin';
198
+
199
+	const caps_edit       = 'edit';
200
+
201
+	const caps_delete     = 'delete';
202
+
203
+	/**
204
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
205
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
206
+	 * maps to 'read' because when looking for relevant permissions we're going to use
207
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
208
+	 *
209
+	 * @var array
210
+	 */
211
+	protected $_cap_contexts_to_cap_action_map = array(
212
+		self::caps_read       => 'read',
213
+		self::caps_read_admin => 'read',
214
+		self::caps_edit       => 'edit',
215
+		self::caps_delete     => 'delete',
216
+	);
217
+
218
+	/**
219
+	 * Timezone
220
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
221
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
222
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
223
+	 * EE_Datetime_Field data type will have access to it.
224
+	 *
225
+	 * @var string
226
+	 */
227
+	protected $_timezone;
228
+
229
+
230
+	/**
231
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
232
+	 * multisite.
233
+	 *
234
+	 * @var int
235
+	 */
236
+	protected static $_model_query_blog_id;
237
+
238
+	/**
239
+	 * A copy of _fields, except the array keys are the model names pointed to by
240
+	 * the field
241
+	 *
242
+	 * @var EE_Model_Field_Base[]
243
+	 */
244
+	private $_cache_foreign_key_to_fields = array();
245
+
246
+	/**
247
+	 * Cached list of all the fields on the model, indexed by their name
248
+	 *
249
+	 * @var EE_Model_Field_Base[]
250
+	 */
251
+	private $_cached_fields = null;
252
+
253
+	/**
254
+	 * Cached list of all the fields on the model, except those that are
255
+	 * marked as only pertinent to the database
256
+	 *
257
+	 * @var EE_Model_Field_Base[]
258
+	 */
259
+	private $_cached_fields_non_db_only = null;
260
+
261
+	/**
262
+	 * A cached reference to the primary key for quick lookup
263
+	 *
264
+	 * @var EE_Model_Field_Base
265
+	 */
266
+	private $_primary_key_field = null;
267
+
268
+	/**
269
+	 * Flag indicating whether this model has a primary key or not
270
+	 *
271
+	 * @var boolean
272
+	 */
273
+	protected $_has_primary_key_field = null;
274
+
275
+	/**
276
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
277
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
278
+	 *
279
+	 * @var boolean
280
+	 */
281
+	protected $_wp_core_model = false;
282
+
283
+	/**
284
+	 *    List of valid operators that can be used for querying.
285
+	 * The keys are all operators we'll accept, the values are the real SQL
286
+	 * operators used
287
+	 *
288
+	 * @var array
289
+	 */
290
+	protected $_valid_operators = array(
291
+		'='           => '=',
292
+		'<='          => '<=',
293
+		'<'           => '<',
294
+		'>='          => '>=',
295
+		'>'           => '>',
296
+		'!='          => '!=',
297
+		'LIKE'        => 'LIKE',
298
+		'like'        => 'LIKE',
299
+		'NOT_LIKE'    => 'NOT LIKE',
300
+		'not_like'    => 'NOT LIKE',
301
+		'NOT LIKE'    => 'NOT LIKE',
302
+		'not like'    => 'NOT LIKE',
303
+		'IN'          => 'IN',
304
+		'in'          => 'IN',
305
+		'NOT_IN'      => 'NOT IN',
306
+		'not_in'      => 'NOT IN',
307
+		'NOT IN'      => 'NOT IN',
308
+		'not in'      => 'NOT IN',
309
+		'between'     => 'BETWEEN',
310
+		'BETWEEN'     => 'BETWEEN',
311
+		'IS_NOT_NULL' => 'IS NOT NULL',
312
+		'is_not_null' => 'IS NOT NULL',
313
+		'IS NOT NULL' => 'IS NOT NULL',
314
+		'is not null' => 'IS NOT NULL',
315
+		'IS_NULL'     => 'IS NULL',
316
+		'is_null'     => 'IS NULL',
317
+		'IS NULL'     => 'IS NULL',
318
+		'is null'     => 'IS NULL',
319
+		'REGEXP'      => 'REGEXP',
320
+		'regexp'      => 'REGEXP',
321
+		'NOT_REGEXP'  => 'NOT REGEXP',
322
+		'not_regexp'  => 'NOT REGEXP',
323
+		'NOT REGEXP'  => 'NOT REGEXP',
324
+		'not regexp'  => 'NOT REGEXP',
325
+	);
326
+
327
+	/**
328
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
329
+	 *
330
+	 * @var array
331
+	 */
332
+	protected $_in_style_operators = array('IN', 'NOT IN');
333
+
334
+	/**
335
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
336
+	 * '12-31-2012'"
337
+	 *
338
+	 * @var array
339
+	 */
340
+	protected $_between_style_operators = array('BETWEEN');
341
+
342
+	/**
343
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
344
+	 * on a join table.
345
+	 *
346
+	 * @var array
347
+	 */
348
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
349
+
350
+	/**
351
+	 * Allowed values for $query_params['order'] for ordering in queries
352
+	 *
353
+	 * @var array
354
+	 */
355
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
356
+
357
+	/**
358
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
359
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
360
+	 *
361
+	 * @var array
362
+	 */
363
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
364
+
365
+	/**
366
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
367
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
368
+	 *
369
+	 * @var array
370
+	 */
371
+	private $_allowed_query_params = array(
372
+		0,
373
+		'limit',
374
+		'order_by',
375
+		'group_by',
376
+		'having',
377
+		'force_join',
378
+		'order',
379
+		'on_join_limit',
380
+		'default_where_conditions',
381
+		'caps',
382
+	);
383
+
384
+	/**
385
+	 * All the data types that can be used in $wpdb->prepare statements.
386
+	 *
387
+	 * @var array
388
+	 */
389
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
390
+
391
+	/**
392
+	 *    EE_Registry Object
393
+	 *
394
+	 * @var    object
395
+	 * @access    protected
396
+	 */
397
+	protected $EE = null;
398
+
399
+
400
+	/**
401
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
402
+	 *
403
+	 * @var int
404
+	 */
405
+	protected $_show_next_x_db_queries = 0;
406
+
407
+	/**
408
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
409
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
410
+	 *
411
+	 * @var array
412
+	 */
413
+	protected $_custom_selections = array();
414
+
415
+	/**
416
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
417
+	 * caches every model object we've fetched from the DB on this request
418
+	 *
419
+	 * @var array
420
+	 */
421
+	protected $_entity_map;
422
+
423
+	/**
424
+	 * constant used to show EEM_Base has not yet verified the db on this http request
425
+	 */
426
+	const db_verified_none = 0;
427
+
428
+	/**
429
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
430
+	 * but not the addons' dbs
431
+	 */
432
+	const db_verified_core = 1;
433
+
434
+	/**
435
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
436
+	 * the EE core db too)
437
+	 */
438
+	const db_verified_addons = 2;
439
+
440
+	/**
441
+	 * indicates whether an EEM_Base child has already re-verified the DB
442
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
443
+	 * looking like EEM_Base::db_verified_*
444
+	 *
445
+	 * @var int - 0 = none, 1 = core, 2 = addons
446
+	 */
447
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
448
+
449
+	/**
450
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
451
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
452
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
453
+	 */
454
+	const default_where_conditions_all = 'all';
455
+
456
+	/**
457
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
458
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
459
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
460
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
461
+	 *        models which share tables with other models, this can return data for the wrong model.
462
+	 */
463
+	const default_where_conditions_this_only = 'this_model_only';
464
+
465
+	/**
466
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
467
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
468
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
469
+	 */
470
+	const default_where_conditions_others_only = 'other_models_only';
471
+
472
+	/**
473
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
474
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
475
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
476
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
477
+	 *        (regardless of whether those events and venues are trashed)
478
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
479
+	 *        events.
480
+	 */
481
+	const default_where_conditions_minimum_all = 'minimum';
482
+
483
+	/**
484
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
485
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
486
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
487
+	 *        not)
488
+	 */
489
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
490
+
491
+	/**
492
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
493
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
494
+	 *        it's possible it will return table entries for other models. You should use
495
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
496
+	 */
497
+	const default_where_conditions_none = 'none';
498
+
499
+
500
+
501
+	/**
502
+	 * About all child constructors:
503
+	 * they should define the _tables, _fields and _model_relations arrays.
504
+	 * Should ALWAYS be called after child constructor.
505
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
506
+	 * finalizes constructing all the object's attributes.
507
+	 * Generally, rather than requiring a child to code
508
+	 * $this->_tables = array(
509
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
510
+	 *        ...);
511
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
512
+	 * each EE_Table has a function to set the table's alias after the constructor, using
513
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
514
+	 * do something similar.
515
+	 *
516
+	 * @param null $timezone
517
+	 * @throws EE_Error
518
+	 */
519
+	protected function __construct($timezone = null)
520
+	{
521
+		// check that the model has not been loaded too soon
522
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
523
+			throw new EE_Error (
524
+				sprintf(
525
+					__('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.',
526
+						'event_espresso'),
527
+					get_class($this)
528
+				)
529
+			);
530
+		}
531
+		/**
532
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
533
+		 */
534
+		if (empty(EEM_Base::$_model_query_blog_id)) {
535
+			EEM_Base::set_model_query_blog_id();
536
+		}
537
+		/**
538
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
539
+		 * just use EE_Register_Model_Extension
540
+		 *
541
+		 * @var EE_Table_Base[] $_tables
542
+		 */
543
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
544
+		foreach ($this->_tables as $table_alias => $table_obj) {
545
+			/** @var $table_obj EE_Table_Base */
546
+			$table_obj->_construct_finalize_with_alias($table_alias);
547
+			if ($table_obj instanceof EE_Secondary_Table) {
548
+				/** @var $table_obj EE_Secondary_Table */
549
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
550
+			}
551
+		}
552
+		/**
553
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
554
+		 * EE_Register_Model_Extension
555
+		 *
556
+		 * @param EE_Model_Field_Base[] $_fields
557
+		 */
558
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
559
+		$this->_invalidate_field_caches();
560
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
561
+			if (! array_key_exists($table_alias, $this->_tables)) {
562
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
563
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
564
+			}
565
+			foreach ($fields_for_table as $field_name => $field_obj) {
566
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
+				//primary key field base has a slightly different _construct_finalize
568
+				/** @var $field_obj EE_Model_Field_Base */
569
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
+			}
571
+		}
572
+		// everything is related to Extra_Meta
573
+		if (get_class($this) !== 'EEM_Extra_Meta') {
574
+			//make extra meta related to everything, but don't block deleting things just
575
+			//because they have related extra meta info. For now just orphan those extra meta
576
+			//in the future we should automatically delete them
577
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		//and change logs
580
+		if (get_class($this) !== 'EEM_Change_Log') {
581
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
+		}
583
+		/**
584
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
+		 * EE_Register_Model_Extension
586
+		 *
587
+		 * @param EE_Model_Relation_Base[] $_model_relations
588
+		 */
589
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
590
+			$this->_model_relations);
591
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
592
+			/** @var $relation_obj EE_Model_Relation_Base */
593
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
594
+		}
595
+		foreach ($this->_indexes as $index_name => $index_obj) {
596
+			/** @var $index_obj EE_Index */
597
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
598
+		}
599
+		$this->set_timezone($timezone);
600
+		//finalize default where condition strategy, or set default
601
+		if (! $this->_default_where_conditions_strategy) {
602
+			//nothing was set during child constructor, so set default
603
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
604
+		}
605
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
606
+		if (! $this->_minimum_where_conditions_strategy) {
607
+			//nothing was set during child constructor, so set default
608
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
609
+		}
610
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
611
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
612
+		//to indicate to NOT set it, set it to the logical default
613
+		if ($this->_caps_slug === null) {
614
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
615
+		}
616
+		//initialize the standard cap restriction generators if none were specified by the child constructor
617
+		if ($this->_cap_restriction_generators !== false) {
618
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
619
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
620
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
621
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
622
+						new EE_Restriction_Generator_Protected(),
623
+						$cap_context,
624
+						$this
625
+					);
626
+				}
627
+			}
628
+		}
629
+		//if there are cap restriction generators, use them to make the default cap restrictions
630
+		if ($this->_cap_restriction_generators !== false) {
631
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
632
+				if (! $generator_object) {
633
+					continue;
634
+				}
635
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
636
+					throw new EE_Error(
637
+						sprintf(
638
+							__('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.',
639
+								'event_espresso'),
640
+							$context,
641
+							$this->get_this_model_name()
642
+						)
643
+					);
644
+				}
645
+				$action = $this->cap_action_for_context($context);
646
+				if (! $generator_object->construction_finalized()) {
647
+					$generator_object->_construct_finalize($this, $action);
648
+				}
649
+			}
650
+		}
651
+		do_action('AHEE__' . get_class($this) . '__construct__end');
652
+	}
653
+
654
+
655
+
656
+	/**
657
+	 * Generates the cap restrictions for the given context, or if they were
658
+	 * already generated just gets what's cached
659
+	 *
660
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
661
+	 * @return EE_Default_Where_Conditions[]
662
+	 */
663
+	protected function _generate_cap_restrictions($context)
664
+	{
665
+		if (isset($this->_cap_restriction_generators[$context])
666
+			&& $this->_cap_restriction_generators[$context]
667
+			   instanceof
668
+			   EE_Restriction_Generator_Base
669
+		) {
670
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
671
+		} else {
672
+			return array();
673
+		}
674
+	}
675
+
676
+
677
+
678
+	/**
679
+	 * Used to set the $_model_query_blog_id static property.
680
+	 *
681
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
682
+	 *                      value for get_current_blog_id() will be used.
683
+	 */
684
+	public static function set_model_query_blog_id($blog_id = 0)
685
+	{
686
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
687
+	}
688
+
689
+
690
+
691
+	/**
692
+	 * Returns whatever is set as the internal $model_query_blog_id.
693
+	 *
694
+	 * @return int
695
+	 */
696
+	public static function get_model_query_blog_id()
697
+	{
698
+		return EEM_Base::$_model_query_blog_id;
699
+	}
700
+
701
+
702
+
703
+	/**
704
+	 * This function is a singleton method used to instantiate the Espresso_model object
705
+	 *
706
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
707
+	 *                                (and any incoming timezone data that gets saved).
708
+	 *                                Note this just sends the timezone info to the date time model field objects.
709
+	 *                                Default is NULL
710
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
711
+	 * @return static (as in the concrete child class)
712
+	 * @throws InvalidArgumentException
713
+	 * @throws InvalidInterfaceException
714
+	 * @throws InvalidDataTypeException
715
+	 * @throws EE_Error
716
+	 */
717
+	public static function instance($timezone = null)
718
+	{
719
+		// check if instance of Espresso_model already exists
720
+		if (! static::$_instance instanceof static) {
721
+			// instantiate Espresso_model
722
+			static::$_instance = new static(
723
+				$timezone,
724
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
725
+			);
726
+		}
727
+		//we might have a timezone set, let set_timezone decide what to do with it
728
+		static::$_instance->set_timezone($timezone);
729
+		// Espresso_model object
730
+		return static::$_instance;
731
+	}
732
+
733
+
734
+
735
+	/**
736
+	 * resets the model and returns it
737
+	 *
738
+	 * @param null | string $timezone
739
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
740
+	 * @throws ReflectionException
741
+	 * all its properties reset; if it wasn't instantiated, returns null)
742
+	 * @throws EE_Error
743
+	 * @throws InvalidArgumentException
744
+	 * @throws InvalidDataTypeException
745
+	 * @throws InvalidInterfaceException
746
+	 */
747
+	public static function reset($timezone = null)
748
+	{
749
+		if (static::$_instance instanceof EEM_Base) {
750
+			//let's try to NOT swap out the current instance for a new one
751
+			//because if someone has a reference to it, we can't remove their reference
752
+			//so it's best to keep using the same reference, but change the original object
753
+			//reset all its properties to their original values as defined in the class
754
+			$r = new ReflectionClass(get_class(static::$_instance));
755
+			$static_properties = $r->getStaticProperties();
756
+			foreach ($r->getDefaultProperties() as $property => $value) {
757
+				//don't set instance to null like it was originally,
758
+				//but it's static anyways, and we're ignoring static properties (for now at least)
759
+				if (! isset($static_properties[$property])) {
760
+					static::$_instance->{$property} = $value;
761
+				}
762
+			}
763
+			//and then directly call its constructor again, like we would if we were creating a new one
764
+			static::$_instance->__construct(
765
+				$timezone,
766
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
767
+			);
768
+			return self::instance();
769
+		}
770
+		return null;
771
+	}
772
+
773
+
774
+
775
+	/**
776
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
777
+	 *
778
+	 * @param  boolean $translated return localized strings or JUST the array.
779
+	 * @return array
780
+	 * @throws EE_Error
781
+	 */
782
+	public function status_array($translated = false)
783
+	{
784
+		if (! array_key_exists('Status', $this->_model_relations)) {
785
+			return array();
786
+		}
787
+		$model_name = $this->get_this_model_name();
788
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
789
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
790
+		$status_array = array();
791
+		foreach ($stati as $status) {
792
+			$status_array[$status->ID()] = $status->get('STS_code');
793
+		}
794
+		return $translated
795
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
796
+			: $status_array;
797
+	}
798
+
799
+
800
+
801
+	/**
802
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
803
+	 *
804
+	 * @param array $query_params             {
805
+	 * @var array $0 (where) array {
806
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
807
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
808
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
809
+	 *                                        conditions based on related models (and even
810
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
811
+	 *                                        name. Eg,
812
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
813
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
814
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
815
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
816
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
817
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
818
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
819
+	 *                                        to Venues (even when each of those models actually consisted of two
820
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
821
+	 *                                        just having
822
+	 *                                        "Venue.VNU_ID", you could have
823
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
824
+	 *                                        events are related to Registrations, which are related to Attendees). You
825
+	 *                                        can take it even further with
826
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
827
+	 *                                        (from the default of '='), change the value to an numerically-indexed
828
+	 *                                        array, where the first item in the list is the operator. eg: array(
829
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
830
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
831
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
832
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
833
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
834
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
835
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
836
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
837
+	 *                                        the value is a field, simply provide a third array item (true) to the
838
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
839
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
840
+	 *                                        Note: you can also use related model field names like you would any other
841
+	 *                                        field name. eg:
842
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
843
+	 *                                        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__>' =>
844
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
845
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
846
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
847
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
848
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
849
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
850
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
851
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
852
+	 *                                        "stick" until you specify an AND. eg
853
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
854
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
855
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
856
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
857
+	 *                                        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 >>
858
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
859
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
860
+	 *                                        too, eg:
861
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
862
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
863
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
864
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
865
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
866
+	 *                                        the OFFSET, the 2nd is the LIMIT
867
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
868
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
869
+	 *                                        following format array('on_join_limit'
870
+	 *                                        => array( 'table_alias', array(1,2) ) ).
871
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
872
+	 *                                        values are either 'ASC' or 'DESC'.
873
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
874
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
875
+	 *                                        DESC..." respectively. Like the
876
+	 *                                        'where' conditions, these fields can be on related models. Eg
877
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
878
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
879
+	 *                                        Attendee, Price, Datetime, etc.)
880
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
881
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
882
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
883
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
884
+	 *                                        order by the primary key. Eg,
885
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
886
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
887
+	 *                                        DTT_EVT_start) or
888
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
889
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
890
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
891
+	 *                                        'group_by'=>'VNU_ID', or
892
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
893
+	 *                                        if no
894
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
895
+	 *                                        model's primary key (or combined primary keys). This avoids some
896
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
897
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
898
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
899
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
900
+	 *                                        results)
901
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
902
+	 *                                        array where values are models to be joined in the query.Eg
903
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
904
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
905
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
906
+	 *                                        related models which belongs to the current model
907
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
908
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
909
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
910
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
911
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
912
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
913
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
914
+	 *                                        this model's default where conditions added to the query, use
915
+	 *                                        'this_model_only'. If you want to use all default where conditions
916
+	 *                                        (default), set to 'all'.
917
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
918
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
919
+	 *                                        everything? Or should we only show the current user items they should be
920
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
921
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
922
+	 *                                        }
923
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
924
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
925
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
926
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
927
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
928
+	 *                                        array( array(
929
+	 *                                        'OR'=>array(
930
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
931
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
932
+	 *                                        )
933
+	 *                                        ),
934
+	 *                                        'limit'=>10,
935
+	 *                                        'group_by'=>'TXN_ID'
936
+	 *                                        ));
937
+	 *                                        get all the answers to the question titled "shirt size" for event with id
938
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
939
+	 *                                        'Question.QST_display_text'=>'shirt size',
940
+	 *                                        'Registration.Event.EVT_ID'=>12
941
+	 *                                        ),
942
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
943
+	 *                                        ));
944
+	 * @throws EE_Error
945
+	 */
946
+	public function get_all($query_params = array())
947
+	{
948
+		if (isset($query_params['limit'])
949
+			&& ! isset($query_params['group_by'])
950
+		) {
951
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
952
+		}
953
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * Modifies the query parameters so we only get back model objects
960
+	 * that "belong" to the current user
961
+	 *
962
+	 * @param array $query_params @see EEM_Base::get_all()
963
+	 * @return array like EEM_Base::get_all
964
+	 */
965
+	public function alter_query_params_to_only_include_mine($query_params = array())
966
+	{
967
+		$wp_user_field_name = $this->wp_user_field_name();
968
+		if ($wp_user_field_name) {
969
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
970
+		}
971
+		return $query_params;
972
+	}
973
+
974
+
975
+
976
+	/**
977
+	 * Returns the name of the field's name that points to the WP_User table
978
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
979
+	 * foreign key to the WP_User table)
980
+	 *
981
+	 * @return string|boolean string on success, boolean false when there is no
982
+	 * foreign key to the WP_User table
983
+	 */
984
+	public function wp_user_field_name()
985
+	{
986
+		try {
987
+			if (! empty($this->_model_chain_to_wp_user)) {
988
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
989
+				$last_model_name = end($models_to_follow_to_wp_users);
990
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
991
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
992
+			} else {
993
+				$model_with_fk_to_wp_users = $this;
994
+				$model_chain_to_wp_user = '';
995
+			}
996
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
997
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
998
+		} catch (EE_Error $e) {
999
+			return false;
1000
+		}
1001
+	}
1002
+
1003
+
1004
+
1005
+	/**
1006
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
1007
+	 * (or transiently-related model) has a foreign key to the wp_users table;
1008
+	 * useful for finding if model objects of this type are 'owned' by the current user.
1009
+	 * This is an empty string when the foreign key is on this model and when it isn't,
1010
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
1011
+	 * (or transiently-related model)
1012
+	 *
1013
+	 * @return string
1014
+	 */
1015
+	public function model_chain_to_wp_user()
1016
+	{
1017
+		return $this->_model_chain_to_wp_user;
1018
+	}
1019
+
1020
+
1021
+
1022
+	/**
1023
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1024
+	 * like how registrations don't have a foreign key to wp_users, but the
1025
+	 * events they are for are), or is unrelated to wp users.
1026
+	 * generally available
1027
+	 *
1028
+	 * @return boolean
1029
+	 */
1030
+	public function is_owned()
1031
+	{
1032
+		if ($this->model_chain_to_wp_user()) {
1033
+			return true;
1034
+		}
1035
+		try {
1036
+			$this->get_foreign_key_to('WP_User');
1037
+			return true;
1038
+		} catch (EE_Error $e) {
1039
+			return false;
1040
+		}
1041
+	}
1042
+
1043
+
1044
+
1045
+	/**
1046
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1047
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1048
+	 * the model)
1049
+	 *
1050
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1051
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1052
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1053
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1054
+	 *                                  override this and set the select to "*", or a specific column name, like
1055
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1056
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1057
+	 *                                  the aliases used to refer to this selection, and values are to be
1058
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1059
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1060
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1061
+	 * @throws EE_Error
1062
+	 */
1063
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1064
+	{
1065
+		// remember the custom selections, if any, and type cast as array
1066
+		// (unless $columns_to_select is an object, then just set as an empty array)
1067
+		// Note: (array) 'some string' === array( 'some string' )
1068
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1069
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1070
+		$select_expressions = $columns_to_select !== null
1071
+			? $this->_construct_select_from_input($columns_to_select)
1072
+			: $this->_construct_default_select_sql($model_query_info);
1073
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1074
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1075
+	}
1076
+
1077
+
1078
+
1079
+	/**
1080
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1081
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1082
+	 * take care of joins, field preparation etc.
1083
+	 *
1084
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1085
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1086
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1087
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1088
+	 *                                  override this and set the select to "*", or a specific column name, like
1089
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1090
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1091
+	 *                                  the aliases used to refer to this selection, and values are to be
1092
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1093
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1094
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1095
+	 * @throws EE_Error
1096
+	 */
1097
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1098
+	{
1099
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1100
+	}
1101
+
1102
+
1103
+
1104
+	/**
1105
+	 * For creating a custom select statement
1106
+	 *
1107
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1108
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1109
+	 *                                 SQL, and 1=>is the datatype
1110
+	 * @throws EE_Error
1111
+	 * @return string
1112
+	 */
1113
+	private function _construct_select_from_input($columns_to_select)
1114
+	{
1115
+		if (is_array($columns_to_select)) {
1116
+			$select_sql_array = array();
1117
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1118
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1119
+					throw new EE_Error(
1120
+						sprintf(
1121
+							__(
1122
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1123
+								"event_espresso"
1124
+							),
1125
+							$selection_and_datatype,
1126
+							$alias
1127
+						)
1128
+					);
1129
+				}
1130
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1131
+					throw new EE_Error(
1132
+						sprintf(
1133
+							__(
1134
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1135
+								"event_espresso"
1136
+							),
1137
+							$selection_and_datatype[1],
1138
+							$selection_and_datatype[0],
1139
+							$alias,
1140
+							implode(",", $this->_valid_wpdb_data_types)
1141
+						)
1142
+					);
1143
+				}
1144
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1145
+			}
1146
+			$columns_to_select_string = implode(", ", $select_sql_array);
1147
+		} else {
1148
+			$columns_to_select_string = $columns_to_select;
1149
+		}
1150
+		return $columns_to_select_string;
1151
+	}
1152
+
1153
+
1154
+
1155
+	/**
1156
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1157
+	 *
1158
+	 * @return string
1159
+	 * @throws EE_Error
1160
+	 */
1161
+	public function primary_key_name()
1162
+	{
1163
+		return $this->get_primary_key_field()->get_name();
1164
+	}
1165
+
1166
+
1167
+
1168
+	/**
1169
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1170
+	 * If there is no primary key on this model, $id is treated as primary key string
1171
+	 *
1172
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1173
+	 * @return EE_Base_Class
1174
+	 */
1175
+	public function get_one_by_ID($id)
1176
+	{
1177
+		if ($this->get_from_entity_map($id)) {
1178
+			return $this->get_from_entity_map($id);
1179
+		}
1180
+		return $this->get_one(
1181
+			$this->alter_query_params_to_restrict_by_ID(
1182
+				$id,
1183
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1184
+			)
1185
+		);
1186
+	}
1187
+
1188
+
1189
+
1190
+	/**
1191
+	 * Alters query parameters to only get items with this ID are returned.
1192
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1193
+	 * or could just be a simple primary key ID
1194
+	 *
1195
+	 * @param int   $id
1196
+	 * @param array $query_params
1197
+	 * @return array of normal query params, @see EEM_Base::get_all
1198
+	 * @throws EE_Error
1199
+	 */
1200
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1201
+	{
1202
+		if (! isset($query_params[0])) {
1203
+			$query_params[0] = array();
1204
+		}
1205
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1206
+		if ($conditions_from_id === null) {
1207
+			$query_params[0][$this->primary_key_name()] = $id;
1208
+		} else {
1209
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1210
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1211
+		}
1212
+		return $query_params;
1213
+	}
1214
+
1215
+
1216
+
1217
+	/**
1218
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1219
+	 * array. If no item is found, null is returned.
1220
+	 *
1221
+	 * @param array $query_params like EEM_Base's $query_params variable.
1222
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1223
+	 * @throws EE_Error
1224
+	 */
1225
+	public function get_one($query_params = array())
1226
+	{
1227
+		if (! is_array($query_params)) {
1228
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1229
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1230
+					gettype($query_params)), '4.6.0');
1231
+			$query_params = array();
1232
+		}
1233
+		$query_params['limit'] = 1;
1234
+		$items = $this->get_all($query_params);
1235
+		if (empty($items)) {
1236
+			return null;
1237
+		}
1238
+		return array_shift($items);
1239
+	}
1240
+
1241
+
1242
+
1243
+	/**
1244
+	 * Returns the next x number of items in sequence from the given value as
1245
+	 * found in the database matching the given query conditions.
1246
+	 *
1247
+	 * @param mixed $current_field_value    Value used for the reference point.
1248
+	 * @param null  $field_to_order_by      What field is used for the
1249
+	 *                                      reference point.
1250
+	 * @param int   $limit                  How many to return.
1251
+	 * @param array $query_params           Extra conditions on the query.
1252
+	 * @param null  $columns_to_select      If left null, then an array of
1253
+	 *                                      EE_Base_Class objects is returned,
1254
+	 *                                      otherwise you can indicate just the
1255
+	 *                                      columns you want returned.
1256
+	 * @return EE_Base_Class[]|array
1257
+	 * @throws EE_Error
1258
+	 */
1259
+	public function next_x(
1260
+		$current_field_value,
1261
+		$field_to_order_by = null,
1262
+		$limit = 1,
1263
+		$query_params = array(),
1264
+		$columns_to_select = null
1265
+	) {
1266
+		return $this->_get_consecutive(
1267
+			$current_field_value,
1268
+			'>',
1269
+			$field_to_order_by,
1270
+			$limit,
1271
+			$query_params,
1272
+			$columns_to_select
1273
+		);
1274
+	}
1275
+
1276
+
1277
+
1278
+	/**
1279
+	 * Returns the previous x number of items in sequence from the given value
1280
+	 * as found in the database matching the given query conditions.
1281
+	 *
1282
+	 * @param mixed $current_field_value    Value used for the reference point.
1283
+	 * @param null  $field_to_order_by      What field is used for the
1284
+	 *                                      reference point.
1285
+	 * @param int   $limit                  How many to return.
1286
+	 * @param array $query_params           Extra conditions on the query.
1287
+	 * @param null  $columns_to_select      If left null, then an array of
1288
+	 *                                      EE_Base_Class objects is returned,
1289
+	 *                                      otherwise you can indicate just the
1290
+	 *                                      columns you want returned.
1291
+	 * @return EE_Base_Class[]|array
1292
+	 * @throws EE_Error
1293
+	 */
1294
+	public function previous_x(
1295
+		$current_field_value,
1296
+		$field_to_order_by = null,
1297
+		$limit = 1,
1298
+		$query_params = array(),
1299
+		$columns_to_select = null
1300
+	) {
1301
+		return $this->_get_consecutive(
1302
+			$current_field_value,
1303
+			'<',
1304
+			$field_to_order_by,
1305
+			$limit,
1306
+			$query_params,
1307
+			$columns_to_select
1308
+		);
1309
+	}
1310
+
1311
+
1312
+
1313
+	/**
1314
+	 * Returns the next item in sequence from the given value as found in the
1315
+	 * database matching the given query conditions.
1316
+	 *
1317
+	 * @param mixed $current_field_value    Value used for the reference point.
1318
+	 * @param null  $field_to_order_by      What field is used for the
1319
+	 *                                      reference point.
1320
+	 * @param array $query_params           Extra conditions on the query.
1321
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1322
+	 *                                      object is returned, otherwise you
1323
+	 *                                      can indicate just the columns you
1324
+	 *                                      want and a single array indexed by
1325
+	 *                                      the columns will be returned.
1326
+	 * @return EE_Base_Class|null|array()
1327
+	 * @throws EE_Error
1328
+	 */
1329
+	public function next(
1330
+		$current_field_value,
1331
+		$field_to_order_by = null,
1332
+		$query_params = array(),
1333
+		$columns_to_select = null
1334
+	) {
1335
+		$results = $this->_get_consecutive(
1336
+			$current_field_value,
1337
+			'>',
1338
+			$field_to_order_by,
1339
+			1,
1340
+			$query_params,
1341
+			$columns_to_select
1342
+		);
1343
+		return empty($results) ? null : reset($results);
1344
+	}
1345
+
1346
+
1347
+
1348
+	/**
1349
+	 * Returns the previous item in sequence from the given value as found in
1350
+	 * the database matching the given query conditions.
1351
+	 *
1352
+	 * @param mixed $current_field_value    Value used for the reference point.
1353
+	 * @param null  $field_to_order_by      What field is used for the
1354
+	 *                                      reference point.
1355
+	 * @param array $query_params           Extra conditions on the query.
1356
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1357
+	 *                                      object is returned, otherwise you
1358
+	 *                                      can indicate just the columns you
1359
+	 *                                      want and a single array indexed by
1360
+	 *                                      the columns will be returned.
1361
+	 * @return EE_Base_Class|null|array()
1362
+	 * @throws EE_Error
1363
+	 */
1364
+	public function previous(
1365
+		$current_field_value,
1366
+		$field_to_order_by = null,
1367
+		$query_params = array(),
1368
+		$columns_to_select = null
1369
+	) {
1370
+		$results = $this->_get_consecutive(
1371
+			$current_field_value,
1372
+			'<',
1373
+			$field_to_order_by,
1374
+			1,
1375
+			$query_params,
1376
+			$columns_to_select
1377
+		);
1378
+		return empty($results) ? null : reset($results);
1379
+	}
1380
+
1381
+
1382
+
1383
+	/**
1384
+	 * Returns the a consecutive number of items in sequence from the given
1385
+	 * value as found in the database matching the given query conditions.
1386
+	 *
1387
+	 * @param mixed  $current_field_value   Value used for the reference point.
1388
+	 * @param string $operand               What operand is used for the sequence.
1389
+	 * @param string $field_to_order_by     What field is used for the reference point.
1390
+	 * @param int    $limit                 How many to return.
1391
+	 * @param array  $query_params          Extra conditions on the query.
1392
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1393
+	 *                                      otherwise you can indicate just the columns you want returned.
1394
+	 * @return EE_Base_Class[]|array
1395
+	 * @throws EE_Error
1396
+	 */
1397
+	protected function _get_consecutive(
1398
+		$current_field_value,
1399
+		$operand = '>',
1400
+		$field_to_order_by = null,
1401
+		$limit = 1,
1402
+		$query_params = array(),
1403
+		$columns_to_select = null
1404
+	) {
1405
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1406
+		if (empty($field_to_order_by)) {
1407
+			if ($this->has_primary_key_field()) {
1408
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1409
+			} else {
1410
+				if (WP_DEBUG) {
1411
+					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).',
1412
+						'event_espresso'));
1413
+				}
1414
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1415
+				return array();
1416
+			}
1417
+		}
1418
+		if (! is_array($query_params)) {
1419
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1420
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1421
+					gettype($query_params)), '4.6.0');
1422
+			$query_params = array();
1423
+		}
1424
+		//let's add the where query param for consecutive look up.
1425
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1426
+		$query_params['limit'] = $limit;
1427
+		//set direction
1428
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1429
+		$query_params['order_by'] = $operand === '>'
1430
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1431
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1432
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1433
+		if (empty($columns_to_select)) {
1434
+			return $this->get_all($query_params);
1435
+		}
1436
+		//getting just the fields
1437
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1438
+	}
1439
+
1440
+
1441
+
1442
+	/**
1443
+	 * This sets the _timezone property after model object has been instantiated.
1444
+	 *
1445
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1446
+	 */
1447
+	public function set_timezone($timezone)
1448
+	{
1449
+		if ($timezone !== null) {
1450
+			$this->_timezone = $timezone;
1451
+		}
1452
+		//note we need to loop through relations and set the timezone on those objects as well.
1453
+		foreach ($this->_model_relations as $relation) {
1454
+			$relation->set_timezone($timezone);
1455
+		}
1456
+		//and finally we do the same for any datetime fields
1457
+		foreach ($this->_fields as $field) {
1458
+			if ($field instanceof EE_Datetime_Field) {
1459
+				$field->set_timezone($timezone);
1460
+			}
1461
+		}
1462
+	}
1463
+
1464
+
1465
+
1466
+	/**
1467
+	 * This just returns whatever is set for the current timezone.
1468
+	 *
1469
+	 * @access public
1470
+	 * @return string
1471
+	 */
1472
+	public function get_timezone()
1473
+	{
1474
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1475
+		if (empty($this->_timezone)) {
1476
+			foreach ($this->_fields as $field) {
1477
+				if ($field instanceof EE_Datetime_Field) {
1478
+					$this->set_timezone($field->get_timezone());
1479
+					break;
1480
+				}
1481
+			}
1482
+		}
1483
+		//if timezone STILL empty then return the default timezone for the site.
1484
+		if (empty($this->_timezone)) {
1485
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1486
+		}
1487
+		return $this->_timezone;
1488
+	}
1489
+
1490
+
1491
+
1492
+	/**
1493
+	 * This returns the date formats set for the given field name and also ensures that
1494
+	 * $this->_timezone property is set correctly.
1495
+	 *
1496
+	 * @since 4.6.x
1497
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1498
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1499
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1500
+	 * @return array formats in an array with the date format first, and the time format last.
1501
+	 */
1502
+	public function get_formats_for($field_name, $pretty = false)
1503
+	{
1504
+		$field_settings = $this->field_settings_for($field_name);
1505
+		//if not a valid EE_Datetime_Field then throw error
1506
+		if (! $field_settings instanceof EE_Datetime_Field) {
1507
+			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.',
1508
+				'event_espresso'), $field_name));
1509
+		}
1510
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1511
+		//the field.
1512
+		$this->_timezone = $field_settings->get_timezone();
1513
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1514
+	}
1515
+
1516
+
1517
+
1518
+	/**
1519
+	 * This returns the current time in a format setup for a query on this model.
1520
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1521
+	 * it will return:
1522
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1523
+	 *  NOW
1524
+	 *  - or a unix timestamp (equivalent to time())
1525
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1526
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1527
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1528
+	 * @since 4.6.x
1529
+	 * @param string $field_name       The field the current time is needed for.
1530
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1531
+	 *                                 formatted string matching the set format for the field in the set timezone will
1532
+	 *                                 be returned.
1533
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1534
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1535
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1536
+	 *                                 exception is triggered.
1537
+	 */
1538
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1539
+	{
1540
+		$formats = $this->get_formats_for($field_name);
1541
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1542
+		if ($timestamp) {
1543
+			return $DateTime->format('U');
1544
+		}
1545
+		//not returning timestamp, so return formatted string in timezone.
1546
+		switch ($what) {
1547
+			case 'time' :
1548
+				return $DateTime->format($formats[1]);
1549
+				break;
1550
+			case 'date' :
1551
+				return $DateTime->format($formats[0]);
1552
+				break;
1553
+			default :
1554
+				return $DateTime->format(implode(' ', $formats));
1555
+				break;
1556
+		}
1557
+	}
1558
+
1559
+
1560
+
1561
+	/**
1562
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1563
+	 * for the model are.  Returns a DateTime object.
1564
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1565
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1566
+	 * ignored.
1567
+	 *
1568
+	 * @param string $field_name      The field being setup.
1569
+	 * @param string $timestring      The date time string being used.
1570
+	 * @param string $incoming_format The format for the time string.
1571
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1572
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1573
+	 *                                format is
1574
+	 *                                'U', this is ignored.
1575
+	 * @return DateTime
1576
+	 * @throws EE_Error
1577
+	 */
1578
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1579
+	{
1580
+		//just using this to ensure the timezone is set correctly internally
1581
+		$this->get_formats_for($field_name);
1582
+		//load EEH_DTT_Helper
1583
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1584
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1585
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1586
+	}
1587
+
1588
+
1589
+
1590
+	/**
1591
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1592
+	 *
1593
+	 * @return EE_Table_Base[]
1594
+	 */
1595
+	public function get_tables()
1596
+	{
1597
+		return $this->_tables;
1598
+	}
1599
+
1600
+
1601
+
1602
+	/**
1603
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1604
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1605
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1606
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1607
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1608
+	 * model object with EVT_ID = 1
1609
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1610
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1611
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1612
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1613
+	 * are not specified)
1614
+	 *
1615
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1616
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1617
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1618
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1619
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1620
+	 *                                         ID=34, we'd use this method as follows:
1621
+	 *                                         EEM_Transaction::instance()->update(
1622
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1623
+	 *                                         array(array('TXN_ID'=>34)));
1624
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1625
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1626
+	 *                                         consider updating Question's QST_admin_label field is of type
1627
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1628
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1629
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1630
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1631
+	 *                                         TRUE, it is assumed that you've already called
1632
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1633
+	 *                                         malicious javascript. However, if
1634
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1635
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1636
+	 *                                         and every other field, before insertion. We provide this parameter
1637
+	 *                                         because model objects perform their prepare_for_set function on all
1638
+	 *                                         their values, and so don't need to be called again (and in many cases,
1639
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1640
+	 *                                         prepare_for_set method...)
1641
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1642
+	 *                                         in this model's entity map according to $fields_n_values that match
1643
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1644
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1645
+	 *                                         could get out-of-sync with the database
1646
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1647
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1648
+	 *                                         bad)
1649
+	 * @throws EE_Error
1650
+	 */
1651
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1652
+	{
1653
+		if (! is_array($query_params)) {
1654
+			EE_Error::doing_it_wrong('EEM_Base::update',
1655
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1656
+					gettype($query_params)), '4.6.0');
1657
+			$query_params = array();
1658
+		}
1659
+		/**
1660
+		 * Action called before a model update call has been made.
1661
+		 *
1662
+		 * @param EEM_Base $model
1663
+		 * @param array    $fields_n_values the updated fields and their new values
1664
+		 * @param array    $query_params    @see EEM_Base::get_all()
1665
+		 */
1666
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1667
+		/**
1668
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1669
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1670
+		 *
1671
+		 * @param array    $fields_n_values fields and their new values
1672
+		 * @param EEM_Base $model           the model being queried
1673
+		 * @param array    $query_params    see EEM_Base::get_all()
1674
+		 */
1675
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1676
+			$query_params);
1677
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1678
+		//to do that, for each table, verify that it's PK isn't null.
1679
+		$tables = $this->get_tables();
1680
+		//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
1681
+		//NOTE: we should make this code more efficient by NOT querying twice
1682
+		//before the real update, but that needs to first go through ALPHA testing
1683
+		//as it's dangerous. says Mike August 8 2014
1684
+		//we want to make sure the default_where strategy is ignored
1685
+		$this->_ignore_where_strategy = true;
1686
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1687
+		foreach ($wpdb_select_results as $wpdb_result) {
1688
+			// type cast stdClass as array
1689
+			$wpdb_result = (array)$wpdb_result;
1690
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1691
+			if ($this->has_primary_key_field()) {
1692
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1693
+			} else {
1694
+				//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)
1695
+				$main_table_pk_value = null;
1696
+			}
1697
+			//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
1698
+			//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
1699
+			if (count($tables) > 1) {
1700
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1701
+				//in that table, and so we'll want to insert one
1702
+				foreach ($tables as $table_obj) {
1703
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1704
+					//if there is no private key for this table on the results, it means there's no entry
1705
+					//in this table, right? so insert a row in the current table, using any fields available
1706
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1707
+						   && $wpdb_result[$this_table_pk_column])
1708
+					) {
1709
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1710
+							$main_table_pk_value);
1711
+						//if we died here, report the error
1712
+						if (! $success) {
1713
+							return false;
1714
+						}
1715
+					}
1716
+				}
1717
+			}
1718
+			//				//and now check that if we have cached any models by that ID on the model, that
1719
+			//				//they also get updated properly
1720
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1721
+			//				if( $model_object ){
1722
+			//					foreach( $fields_n_values as $field => $value ){
1723
+			//						$model_object->set($field, $value);
1724
+			//let's make sure default_where strategy is followed now
1725
+			$this->_ignore_where_strategy = false;
1726
+		}
1727
+		//if we want to keep model objects in sync, AND
1728
+		//if this wasn't called from a model object (to update itself)
1729
+		//then we want to make sure we keep all the existing
1730
+		//model objects in sync with the db
1731
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1732
+			if ($this->has_primary_key_field()) {
1733
+				$model_objs_affected_ids = $this->get_col($query_params);
1734
+			} else {
1735
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1736
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1737
+				$model_objs_affected_ids = array();
1738
+				foreach ($models_affected_key_columns as $row) {
1739
+					$combined_index_key = $this->get_index_primary_key_string($row);
1740
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1741
+				}
1742
+			}
1743
+			if (! $model_objs_affected_ids) {
1744
+				//wait wait wait- if nothing was affected let's stop here
1745
+				return 0;
1746
+			}
1747
+			foreach ($model_objs_affected_ids as $id) {
1748
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1749
+				if ($model_obj_in_entity_map) {
1750
+					foreach ($fields_n_values as $field => $new_value) {
1751
+						$model_obj_in_entity_map->set($field, $new_value);
1752
+					}
1753
+				}
1754
+			}
1755
+			//if there is a primary key on this model, we can now do a slight optimization
1756
+			if ($this->has_primary_key_field()) {
1757
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1758
+				$query_params = array(
1759
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1760
+					'limit'                    => count($model_objs_affected_ids),
1761
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1762
+				);
1763
+			}
1764
+		}
1765
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1766
+		$SQL = "UPDATE "
1767
+			   . $model_query_info->get_full_join_sql()
1768
+			   . " SET "
1769
+			   . $this->_construct_update_sql($fields_n_values)
1770
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1771
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1772
+		/**
1773
+		 * Action called after a model update call has been made.
1774
+		 *
1775
+		 * @param EEM_Base $model
1776
+		 * @param array    $fields_n_values the updated fields and their new values
1777
+		 * @param array    $query_params    @see EEM_Base::get_all()
1778
+		 * @param int      $rows_affected
1779
+		 */
1780
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1781
+		return $rows_affected;//how many supposedly got updated
1782
+	}
1783
+
1784
+
1785
+
1786
+	/**
1787
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1788
+	 * are teh values of the field specified (or by default the primary key field)
1789
+	 * that matched the query params. Note that you should pass the name of the
1790
+	 * model FIELD, not the database table's column name.
1791
+	 *
1792
+	 * @param array  $query_params @see EEM_Base::get_all()
1793
+	 * @param string $field_to_select
1794
+	 * @return array just like $wpdb->get_col()
1795
+	 * @throws EE_Error
1796
+	 */
1797
+	public function get_col($query_params = array(), $field_to_select = null)
1798
+	{
1799
+		if ($field_to_select) {
1800
+			$field = $this->field_settings_for($field_to_select);
1801
+		} elseif ($this->has_primary_key_field()) {
1802
+			$field = $this->get_primary_key_field();
1803
+		} else {
1804
+			//no primary key, just grab the first column
1805
+			$field = reset($this->field_settings());
1806
+		}
1807
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1808
+		$select_expressions = $field->get_qualified_column();
1809
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1810
+		return $this->_do_wpdb_query('get_col', array($SQL));
1811
+	}
1812
+
1813
+
1814
+
1815
+	/**
1816
+	 * Returns a single column value for a single row from the database
1817
+	 *
1818
+	 * @param array  $query_params    @see EEM_Base::get_all()
1819
+	 * @param string $field_to_select @see EEM_Base::get_col()
1820
+	 * @return string
1821
+	 * @throws EE_Error
1822
+	 */
1823
+	public function get_var($query_params = array(), $field_to_select = null)
1824
+	{
1825
+		$query_params['limit'] = 1;
1826
+		$col = $this->get_col($query_params, $field_to_select);
1827
+		if (! empty($col)) {
1828
+			return reset($col);
1829
+		}
1830
+		return null;
1831
+	}
1832
+
1833
+
1834
+
1835
+	/**
1836
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1837
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1838
+	 * injection, but currently no further filtering is done
1839
+	 *
1840
+	 * @global      $wpdb
1841
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1842
+	 *                               be updated to in the DB
1843
+	 * @return string of SQL
1844
+	 * @throws EE_Error
1845
+	 */
1846
+	public function _construct_update_sql($fields_n_values)
1847
+	{
1848
+		/** @type WPDB $wpdb */
1849
+		global $wpdb;
1850
+		$cols_n_values = array();
1851
+		foreach ($fields_n_values as $field_name => $value) {
1852
+			$field_obj = $this->field_settings_for($field_name);
1853
+			//if the value is NULL, we want to assign the value to that.
1854
+			//wpdb->prepare doesn't really handle that properly
1855
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1856
+			$value_sql = $prepared_value === null ? 'NULL'
1857
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1858
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1859
+		}
1860
+		return implode(",", $cols_n_values);
1861
+	}
1862
+
1863
+
1864
+
1865
+	/**
1866
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1867
+	 * Performs a HARD delete, meaning the database row should always be removed,
1868
+	 * not just have a flag field on it switched
1869
+	 * Wrapper for EEM_Base::delete_permanently()
1870
+	 *
1871
+	 * @param mixed $id
1872
+	 * @return boolean whether the row got deleted or not
1873
+	 * @throws EE_Error
1874
+	 */
1875
+	public function delete_permanently_by_ID($id)
1876
+	{
1877
+		return $this->delete_permanently(
1878
+			array(
1879
+				array($this->get_primary_key_field()->get_name() => $id),
1880
+				'limit' => 1,
1881
+			)
1882
+		);
1883
+	}
1884
+
1885
+
1886
+
1887
+	/**
1888
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1889
+	 * Wrapper for EEM_Base::delete()
1890
+	 *
1891
+	 * @param mixed $id
1892
+	 * @return boolean whether the row got deleted or not
1893
+	 * @throws EE_Error
1894
+	 */
1895
+	public function delete_by_ID($id)
1896
+	{
1897
+		return $this->delete(
1898
+			array(
1899
+				array($this->get_primary_key_field()->get_name() => $id),
1900
+				'limit' => 1,
1901
+			)
1902
+		);
1903
+	}
1904
+
1905
+
1906
+
1907
+	/**
1908
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1909
+	 * meaning if the model has a field that indicates its been "trashed" or
1910
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1911
+	 *
1912
+	 * @see EEM_Base::delete_permanently
1913
+	 * @param array   $query_params
1914
+	 * @param boolean $allow_blocking
1915
+	 * @return int how many rows got deleted
1916
+	 * @throws EE_Error
1917
+	 */
1918
+	public function delete($query_params, $allow_blocking = true)
1919
+	{
1920
+		return $this->delete_permanently($query_params, $allow_blocking);
1921
+	}
1922
+
1923
+
1924
+
1925
+	/**
1926
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1927
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1928
+	 * as archived, not actually deleted
1929
+	 *
1930
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1931
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1932
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1933
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1934
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1935
+	 *                                DB
1936
+	 * @return int how many rows got deleted
1937
+	 * @throws EE_Error
1938
+	 */
1939
+	public function delete_permanently($query_params, $allow_blocking = true)
1940
+	{
1941
+		/**
1942
+		 * Action called just before performing a real deletion query. You can use the
1943
+		 * model and its $query_params to find exactly which items will be deleted
1944
+		 *
1945
+		 * @param EEM_Base $model
1946
+		 * @param array    $query_params   @see EEM_Base::get_all()
1947
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1948
+		 *                                 to block (prevent) this deletion
1949
+		 */
1950
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1951
+		//some MySQL databases may be running safe mode, which may restrict
1952
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1953
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1954
+		//to delete them
1955
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1956
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1957
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1958
+			$columns_and_ids_for_deleting
1959
+		);
1960
+		/**
1961
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1962
+		 *
1963
+		 * @param EEM_Base $this  The model instance being acted on.
1964
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1965
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1966
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1967
+		 *                                                  derived from the incoming query parameters.
1968
+		 *                                                  @see details on the structure of this array in the phpdocs
1969
+		 *                                                  for the `_get_ids_for_delete_method`
1970
+		 *
1971
+		 */
1972
+		do_action('AHEE__EEM_Base__delete__before_query',
1973
+			$this,
1974
+			$query_params,
1975
+			$allow_blocking,
1976
+			$columns_and_ids_for_deleting
1977
+		);
1978
+		if ($deletion_where_query_part) {
1979
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1980
+			$table_aliases = array_keys($this->_tables);
1981
+			$SQL = "DELETE "
1982
+				   . implode(", ", $table_aliases)
1983
+				   . " FROM "
1984
+				   . $model_query_info->get_full_join_sql()
1985
+				   . " WHERE "
1986
+				   . $deletion_where_query_part;
1987
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1988
+		} else {
1989
+			$rows_deleted = 0;
1990
+		}
1991
+
1992
+		//Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1993
+		//there was no error with the delete query.
1994
+		if ($this->has_primary_key_field()
1995
+			&& $rows_deleted !== false
1996
+			&& isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1997
+		) {
1998
+			$ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1999
+			foreach ($ids_for_removal as $id) {
2000
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2001
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2002
+				}
2003
+			}
2004
+
2005
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2006
+			//`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2007
+			//unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2008
+			// (although it is possible).
2009
+			//Note this can be skipped by using the provided filter and returning false.
2010
+			if (apply_filters(
2011
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2012
+				! $this instanceof EEM_Extra_Meta,
2013
+				$this
2014
+			)) {
2015
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2016
+					0 => array(
2017
+						'EXM_type' => $this->get_this_model_name(),
2018
+						'OBJ_ID'   => array(
2019
+							'IN',
2020
+							$ids_for_removal
2021
+						)
2022
+					)
2023
+				));
2024
+			}
2025
+		}
2026
+
2027
+		/**
2028
+		 * Action called just after performing a real deletion query. Although at this point the
2029
+		 * items should have been deleted
2030
+		 *
2031
+		 * @param EEM_Base $model
2032
+		 * @param array    $query_params @see EEM_Base::get_all()
2033
+		 * @param int      $rows_deleted
2034
+		 */
2035
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2036
+		return $rows_deleted;//how many supposedly got deleted
2037
+	}
2038
+
2039
+
2040
+
2041
+	/**
2042
+	 * Checks all the relations that throw error messages when there are blocking related objects
2043
+	 * for related model objects. If there are any related model objects on those relations,
2044
+	 * adds an EE_Error, and return true
2045
+	 *
2046
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2047
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2048
+	 *                                                 should be ignored when determining whether there are related
2049
+	 *                                                 model objects which block this model object's deletion. Useful
2050
+	 *                                                 if you know A is related to B and are considering deleting A,
2051
+	 *                                                 but want to see if A has any other objects blocking its deletion
2052
+	 *                                                 before removing the relation between A and B
2053
+	 * @return boolean
2054
+	 * @throws EE_Error
2055
+	 */
2056
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2057
+	{
2058
+		//first, if $ignore_this_model_obj was supplied, get its model
2059
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2060
+			$ignored_model = $ignore_this_model_obj->get_model();
2061
+		} else {
2062
+			$ignored_model = null;
2063
+		}
2064
+		//now check all the relations of $this_model_obj_or_id and see if there
2065
+		//are any related model objects blocking it?
2066
+		$is_blocked = false;
2067
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2068
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2069
+				//if $ignore_this_model_obj was supplied, then for the query
2070
+				//on that model needs to be told to ignore $ignore_this_model_obj
2071
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2072
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2073
+						array(
2074
+							$ignored_model->get_primary_key_field()->get_name() => array(
2075
+								'!=',
2076
+								$ignore_this_model_obj->ID(),
2077
+							),
2078
+						),
2079
+					));
2080
+				} else {
2081
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2082
+				}
2083
+				if ($related_model_objects) {
2084
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2085
+					$is_blocked = true;
2086
+				}
2087
+			}
2088
+		}
2089
+		return $is_blocked;
2090
+	}
2091
+
2092
+
2093
+	/**
2094
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2095
+	 * @param array $row_results_for_deleting
2096
+	 * @param bool  $allow_blocking
2097
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2098
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2099
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2100
+	 *                 deleted. Example:
2101
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2102
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2103
+	 *                 where each element is a group of columns and values that get deleted. Example:
2104
+	 *                      array(
2105
+	 *                          0 => array(
2106
+	 *                              'Term_Relationship.object_id' => 1
2107
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2108
+	 *                          ),
2109
+	 *                          1 => array(
2110
+	 *                              'Term_Relationship.object_id' => 1
2111
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2112
+	 *                          )
2113
+	 *                      )
2114
+	 * @throws EE_Error
2115
+	 */
2116
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2117
+	{
2118
+		$ids_to_delete_indexed_by_column = array();
2119
+		if ($this->has_primary_key_field()) {
2120
+			$primary_table = $this->_get_main_table();
2121
+			$other_tables = $this->_get_other_tables();
2122
+			$ids_to_delete_indexed_by_column = $query = array();
2123
+			foreach ($row_results_for_deleting as $item_to_delete) {
2124
+				//before we mark this item for deletion,
2125
+				//make sure there's no related entities blocking its deletion (if we're checking)
2126
+				if (
2127
+					$allow_blocking
2128
+					&& $this->delete_is_blocked_by_related_models(
2129
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2130
+					)
2131
+				) {
2132
+					continue;
2133
+				}
2134
+				//primary table deletes
2135
+				if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2136
+					$ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2137
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2138
+				}
2139
+			}
2140
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2141
+			$fields = $this->get_combined_primary_key_fields();
2142
+			foreach ($row_results_for_deleting as $item_to_delete) {
2143
+				$ids_to_delete_indexed_by_column_for_row = array();
2144
+				foreach ($fields as $cpk_field) {
2145
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2146
+						$ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2147
+							$item_to_delete[$cpk_field->get_qualified_column()];
2148
+					}
2149
+				}
2150
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2151
+			}
2152
+		} else {
2153
+			//so there's no primary key and no combined key...
2154
+			//sorry, can't help you
2155
+			throw new EE_Error(
2156
+				sprintf(
2157
+					__(
2158
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2159
+						"event_espresso"
2160
+					), get_class($this)
2161
+				)
2162
+			);
2163
+		}
2164
+		return $ids_to_delete_indexed_by_column;
2165
+	}
2166
+
2167
+
2168
+	/**
2169
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2170
+	 * the corresponding query_part for the query performing the delete.
2171
+	 *
2172
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2173
+	 * @return string
2174
+	 * @throws EE_Error
2175
+	 */
2176
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2177
+		$query_part = '';
2178
+		if (empty($ids_to_delete_indexed_by_column)) {
2179
+			return $query_part;
2180
+		} elseif ($this->has_primary_key_field()) {
2181
+			$query = array();
2182
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2183
+				//make sure we have unique $ids
2184
+				$ids = array_unique($ids);
2185
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2186
+			}
2187
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2188
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2189
+			$ways_to_identify_a_row = array();
2190
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2191
+				$values_for_each_combined_primary_key_for_a_row = array();
2192
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2193
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2194
+				}
2195
+				$ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2196
+			}
2197
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2198
+		}
2199
+		return $query_part;
2200
+	}
2201
+
2202
+
2203
+
2204
+
2205
+	/**
2206
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2207
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2208
+	 * column
2209
+	 *
2210
+	 * @param array  $query_params   like EEM_Base::get_all's
2211
+	 * @param string $field_to_count field on model to count by (not column name)
2212
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2213
+	 *                               that by the setting $distinct to TRUE;
2214
+	 * @return int
2215
+	 * @throws EE_Error
2216
+	 */
2217
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2218
+	{
2219
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2220
+		if ($field_to_count) {
2221
+			$field_obj = $this->field_settings_for($field_to_count);
2222
+			$column_to_count = $field_obj->get_qualified_column();
2223
+		} elseif ($this->has_primary_key_field()) {
2224
+			$pk_field_obj = $this->get_primary_key_field();
2225
+			$column_to_count = $pk_field_obj->get_qualified_column();
2226
+		} else {
2227
+			//there's no primary key
2228
+			//if we're counting distinct items, and there's no primary key,
2229
+			//we need to list out the columns for distinction;
2230
+			//otherwise we can just use star
2231
+			if ($distinct) {
2232
+				$columns_to_use = array();
2233
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2234
+					$columns_to_use[] = $field_obj->get_qualified_column();
2235
+				}
2236
+				$column_to_count = implode(',', $columns_to_use);
2237
+			} else {
2238
+				$column_to_count = '*';
2239
+			}
2240
+		}
2241
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2242
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2243
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2244
+	}
2245
+
2246
+
2247
+
2248
+	/**
2249
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2250
+	 *
2251
+	 * @param array  $query_params like EEM_Base::get_all
2252
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2253
+	 * @return float
2254
+	 * @throws EE_Error
2255
+	 */
2256
+	public function sum($query_params, $field_to_sum = null)
2257
+	{
2258
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2259
+		if ($field_to_sum) {
2260
+			$field_obj = $this->field_settings_for($field_to_sum);
2261
+		} else {
2262
+			$field_obj = $this->get_primary_key_field();
2263
+		}
2264
+		$column_to_count = $field_obj->get_qualified_column();
2265
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2266
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2267
+		$data_type = $field_obj->get_wpdb_data_type();
2268
+		if ($data_type === '%d' || $data_type === '%s') {
2269
+			return (float)$return_value;
2270
+		}
2271
+		//must be %f
2272
+		return (float)$return_value;
2273
+	}
2274
+
2275
+
2276
+
2277
+	/**
2278
+	 * Just calls the specified method on $wpdb with the given arguments
2279
+	 * Consolidates a little extra error handling code
2280
+	 *
2281
+	 * @param string $wpdb_method
2282
+	 * @param array  $arguments_to_provide
2283
+	 * @throws EE_Error
2284
+	 * @global wpdb  $wpdb
2285
+	 * @return mixed
2286
+	 */
2287
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2288
+	{
2289
+		//if we're in maintenance mode level 2, DON'T run any queries
2290
+		//because level 2 indicates the database needs updating and
2291
+		//is probably out of sync with the code
2292
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2293
+			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.",
2294
+				"event_espresso")));
2295
+		}
2296
+		/** @type WPDB $wpdb */
2297
+		global $wpdb;
2298
+		if (! method_exists($wpdb, $wpdb_method)) {
2299
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2300
+				'event_espresso'), $wpdb_method));
2301
+		}
2302
+		if (WP_DEBUG) {
2303
+			$old_show_errors_value = $wpdb->show_errors;
2304
+			$wpdb->show_errors(false);
2305
+		}
2306
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2307
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2308
+		if (WP_DEBUG) {
2309
+			$wpdb->show_errors($old_show_errors_value);
2310
+			if (! empty($wpdb->last_error)) {
2311
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2312
+			}
2313
+			if ($result === false) {
2314
+				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"',
2315
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2316
+			}
2317
+		} elseif ($result === false) {
2318
+			EE_Error::add_error(
2319
+				sprintf(
2320
+					__('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"',
2321
+						'event_espresso'),
2322
+					$wpdb_method,
2323
+					var_export($arguments_to_provide, true),
2324
+					$wpdb->last_error
2325
+				),
2326
+				__FILE__,
2327
+				__FUNCTION__,
2328
+				__LINE__
2329
+			);
2330
+		}
2331
+		return $result;
2332
+	}
2333
+
2334
+
2335
+
2336
+	/**
2337
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2338
+	 * and if there's an error tries to verify the DB is correct. Uses
2339
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2340
+	 * we should try to fix the EE core db, the addons, or just give up
2341
+	 *
2342
+	 * @param string $wpdb_method
2343
+	 * @param array  $arguments_to_provide
2344
+	 * @return mixed
2345
+	 */
2346
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2347
+	{
2348
+		/** @type WPDB $wpdb */
2349
+		global $wpdb;
2350
+		$wpdb->last_error = null;
2351
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2352
+		// was there an error running the query? but we don't care on new activations
2353
+		// (we're going to setup the DB anyway on new activations)
2354
+		if (($result === false || ! empty($wpdb->last_error))
2355
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2356
+		) {
2357
+			switch (EEM_Base::$_db_verification_level) {
2358
+				case EEM_Base::db_verified_none :
2359
+					// let's double-check core's DB
2360
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2361
+					break;
2362
+				case EEM_Base::db_verified_core :
2363
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2364
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2365
+					break;
2366
+				case EEM_Base::db_verified_addons :
2367
+					// ummmm... you in trouble
2368
+					return $result;
2369
+					break;
2370
+			}
2371
+			if (! empty($error_message)) {
2372
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2373
+				trigger_error($error_message);
2374
+			}
2375
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2376
+		}
2377
+		return $result;
2378
+	}
2379
+
2380
+
2381
+
2382
+	/**
2383
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2384
+	 * EEM_Base::$_db_verification_level
2385
+	 *
2386
+	 * @param string $wpdb_method
2387
+	 * @param array  $arguments_to_provide
2388
+	 * @return string
2389
+	 */
2390
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2391
+	{
2392
+		/** @type WPDB $wpdb */
2393
+		global $wpdb;
2394
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2395
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2396
+		$error_message = sprintf(
2397
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2398
+				'event_espresso'),
2399
+			$wpdb->last_error,
2400
+			$wpdb_method,
2401
+			wp_json_encode($arguments_to_provide)
2402
+		);
2403
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2404
+		return $error_message;
2405
+	}
2406
+
2407
+
2408
+
2409
+	/**
2410
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2411
+	 * EEM_Base::$_db_verification_level
2412
+	 *
2413
+	 * @param $wpdb_method
2414
+	 * @param $arguments_to_provide
2415
+	 * @return string
2416
+	 */
2417
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2418
+	{
2419
+		/** @type WPDB $wpdb */
2420
+		global $wpdb;
2421
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2422
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2423
+		$error_message = sprintf(
2424
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2425
+				'event_espresso'),
2426
+			$wpdb->last_error,
2427
+			$wpdb_method,
2428
+			wp_json_encode($arguments_to_provide)
2429
+		);
2430
+		EE_System::instance()->initialize_addons();
2431
+		return $error_message;
2432
+	}
2433
+
2434
+
2435
+
2436
+	/**
2437
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2438
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2439
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2440
+	 * ..."
2441
+	 *
2442
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2443
+	 * @return string
2444
+	 */
2445
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2446
+	{
2447
+		return " FROM " . $model_query_info->get_full_join_sql() .
2448
+			   $model_query_info->get_where_sql() .
2449
+			   $model_query_info->get_group_by_sql() .
2450
+			   $model_query_info->get_having_sql() .
2451
+			   $model_query_info->get_order_by_sql() .
2452
+			   $model_query_info->get_limit_sql();
2453
+	}
2454
+
2455
+
2456
+
2457
+	/**
2458
+	 * Set to easily debug the next X queries ran from this model.
2459
+	 *
2460
+	 * @param int $count
2461
+	 */
2462
+	public function show_next_x_db_queries($count = 1)
2463
+	{
2464
+		$this->_show_next_x_db_queries = $count;
2465
+	}
2466
+
2467
+
2468
+
2469
+	/**
2470
+	 * @param $sql_query
2471
+	 */
2472
+	public function show_db_query_if_previously_requested($sql_query)
2473
+	{
2474
+		if ($this->_show_next_x_db_queries > 0) {
2475
+			echo $sql_query;
2476
+			$this->_show_next_x_db_queries--;
2477
+		}
2478
+	}
2479
+
2480
+
2481
+
2482
+	/**
2483
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2484
+	 * There are the 3 cases:
2485
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2486
+	 * $otherModelObject has no ID, it is first saved.
2487
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2488
+	 * has no ID, it is first saved.
2489
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2490
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2491
+	 * join table
2492
+	 *
2493
+	 * @param        EE_Base_Class                     /int $thisModelObject
2494
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2495
+	 * @param string $relationName                     , key in EEM_Base::_relations
2496
+	 *                                                 an attendee to a group, you also want to specify which role they
2497
+	 *                                                 will have in that group. So you would use this parameter to
2498
+	 *                                                 specify array('role-column-name'=>'role-id')
2499
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2500
+	 *                                                 to for relation to methods that allow you to further specify
2501
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2502
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2503
+	 *                                                 because these will be inserted in any new rows created as well.
2504
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2505
+	 * @throws EE_Error
2506
+	 */
2507
+	public function add_relationship_to(
2508
+		$id_or_obj,
2509
+		$other_model_id_or_obj,
2510
+		$relationName,
2511
+		$extra_join_model_fields_n_values = array()
2512
+	) {
2513
+		$relation_obj = $this->related_settings_for($relationName);
2514
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2515
+	}
2516
+
2517
+
2518
+
2519
+	/**
2520
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2521
+	 * There are the 3 cases:
2522
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2523
+	 * error
2524
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2525
+	 * an error
2526
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2527
+	 *
2528
+	 * @param        EE_Base_Class /int $id_or_obj
2529
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2530
+	 * @param string $relationName key in EEM_Base::_relations
2531
+	 * @return boolean of success
2532
+	 * @throws EE_Error
2533
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2534
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2535
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2536
+	 *                             because these will be inserted in any new rows created as well.
2537
+	 */
2538
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2539
+	{
2540
+		$relation_obj = $this->related_settings_for($relationName);
2541
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2542
+	}
2543
+
2544
+
2545
+
2546
+	/**
2547
+	 * @param mixed           $id_or_obj
2548
+	 * @param string          $relationName
2549
+	 * @param array           $where_query_params
2550
+	 * @param EE_Base_Class[] objects to which relations were removed
2551
+	 * @return \EE_Base_Class[]
2552
+	 * @throws EE_Error
2553
+	 */
2554
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2555
+	{
2556
+		$relation_obj = $this->related_settings_for($relationName);
2557
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2558
+	}
2559
+
2560
+
2561
+
2562
+	/**
2563
+	 * Gets all the related items of the specified $model_name, using $query_params.
2564
+	 * Note: by default, we remove the "default query params"
2565
+	 * because we want to get even deleted items etc.
2566
+	 *
2567
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2568
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2569
+	 * @param array  $query_params like EEM_Base::get_all
2570
+	 * @return EE_Base_Class[]
2571
+	 * @throws EE_Error
2572
+	 */
2573
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2574
+	{
2575
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2576
+		$relation_settings = $this->related_settings_for($model_name);
2577
+		return $relation_settings->get_all_related($model_obj, $query_params);
2578
+	}
2579
+
2580
+
2581
+
2582
+	/**
2583
+	 * Deletes all the model objects across the relation indicated by $model_name
2584
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2585
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2586
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2587
+	 *
2588
+	 * @param EE_Base_Class|int|string $id_or_obj
2589
+	 * @param string                   $model_name
2590
+	 * @param array                    $query_params
2591
+	 * @return int how many deleted
2592
+	 * @throws EE_Error
2593
+	 */
2594
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2595
+	{
2596
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2597
+		$relation_settings = $this->related_settings_for($model_name);
2598
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2599
+	}
2600
+
2601
+
2602
+
2603
+	/**
2604
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2605
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2606
+	 * the model objects can't be hard deleted because of blocking related model objects,
2607
+	 * just does a soft-delete on them instead.
2608
+	 *
2609
+	 * @param EE_Base_Class|int|string $id_or_obj
2610
+	 * @param string                   $model_name
2611
+	 * @param array                    $query_params
2612
+	 * @return int how many deleted
2613
+	 * @throws EE_Error
2614
+	 */
2615
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2616
+	{
2617
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2618
+		$relation_settings = $this->related_settings_for($model_name);
2619
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2620
+	}
2621
+
2622
+
2623
+
2624
+	/**
2625
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2626
+	 * unless otherwise specified in the $query_params
2627
+	 *
2628
+	 * @param        int             /EE_Base_Class $id_or_obj
2629
+	 * @param string $model_name     like 'Event', or 'Registration'
2630
+	 * @param array  $query_params   like EEM_Base::get_all's
2631
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2632
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2633
+	 *                               that by the setting $distinct to TRUE;
2634
+	 * @return int
2635
+	 * @throws EE_Error
2636
+	 */
2637
+	public function count_related(
2638
+		$id_or_obj,
2639
+		$model_name,
2640
+		$query_params = array(),
2641
+		$field_to_count = null,
2642
+		$distinct = false
2643
+	) {
2644
+		$related_model = $this->get_related_model_obj($model_name);
2645
+		//we're just going to use the query params on the related model's normal get_all query,
2646
+		//except add a condition to say to match the current mod
2647
+		if (! isset($query_params['default_where_conditions'])) {
2648
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2649
+		}
2650
+		$this_model_name = $this->get_this_model_name();
2651
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2652
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2653
+		return $related_model->count($query_params, $field_to_count, $distinct);
2654
+	}
2655
+
2656
+
2657
+
2658
+	/**
2659
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2660
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2661
+	 *
2662
+	 * @param        int           /EE_Base_Class $id_or_obj
2663
+	 * @param string $model_name   like 'Event', or 'Registration'
2664
+	 * @param array  $query_params like EEM_Base::get_all's
2665
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2666
+	 * @return float
2667
+	 * @throws EE_Error
2668
+	 */
2669
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2670
+	{
2671
+		$related_model = $this->get_related_model_obj($model_name);
2672
+		if (! is_array($query_params)) {
2673
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2674
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2675
+					gettype($query_params)), '4.6.0');
2676
+			$query_params = array();
2677
+		}
2678
+		//we're just going to use the query params on the related model's normal get_all query,
2679
+		//except add a condition to say to match the current mod
2680
+		if (! isset($query_params['default_where_conditions'])) {
2681
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682
+		}
2683
+		$this_model_name = $this->get_this_model_name();
2684
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2686
+		return $related_model->sum($query_params, $field_to_sum);
2687
+	}
2688
+
2689
+
2690
+
2691
+	/**
2692
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2693
+	 * $modelObject
2694
+	 *
2695
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2696
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2697
+	 * @param array               $query_params     like EEM_Base::get_all's
2698
+	 * @return EE_Base_Class
2699
+	 * @throws EE_Error
2700
+	 */
2701
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2702
+	{
2703
+		$query_params['limit'] = 1;
2704
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2705
+		if ($results) {
2706
+			return array_shift($results);
2707
+		}
2708
+		return null;
2709
+	}
2710
+
2711
+
2712
+
2713
+	/**
2714
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2715
+	 *
2716
+	 * @return string
2717
+	 */
2718
+	public function get_this_model_name()
2719
+	{
2720
+		return str_replace("EEM_", "", get_class($this));
2721
+	}
2722
+
2723
+
2724
+
2725
+	/**
2726
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2727
+	 *
2728
+	 * @return EE_Any_Foreign_Model_Name_Field
2729
+	 * @throws EE_Error
2730
+	 */
2731
+	public function get_field_containing_related_model_name()
2732
+	{
2733
+		foreach ($this->field_settings(true) as $field) {
2734
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2735
+				$field_with_model_name = $field;
2736
+			}
2737
+		}
2738
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2739
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2740
+				$this->get_this_model_name()));
2741
+		}
2742
+		return $field_with_model_name;
2743
+	}
2744
+
2745
+
2746
+
2747
+	/**
2748
+	 * Inserts a new entry into the database, for each table.
2749
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2750
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2751
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2752
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2753
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2754
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2755
+	 *
2756
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2757
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2758
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2759
+	 *                              of EEM_Base)
2760
+	 * @return int new primary key on main table that got inserted
2761
+	 * @throws EE_Error
2762
+	 */
2763
+	public function insert($field_n_values)
2764
+	{
2765
+		/**
2766
+		 * Filters the fields and their values before inserting an item using the models
2767
+		 *
2768
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2769
+		 * @param EEM_Base $model           the model used
2770
+		 */
2771
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2772
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2773
+			$main_table = $this->_get_main_table();
2774
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2775
+			if ($new_id !== false) {
2776
+				foreach ($this->_get_other_tables() as $other_table) {
2777
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2778
+				}
2779
+			}
2780
+			/**
2781
+			 * Done just after attempting to insert a new model object
2782
+			 *
2783
+			 * @param EEM_Base   $model           used
2784
+			 * @param array      $fields_n_values fields and their values
2785
+			 * @param int|string the              ID of the newly-inserted model object
2786
+			 */
2787
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2788
+			return $new_id;
2789
+		}
2790
+		return false;
2791
+	}
2792
+
2793
+
2794
+
2795
+	/**
2796
+	 * Checks that the result would satisfy the unique indexes on this model
2797
+	 *
2798
+	 * @param array  $field_n_values
2799
+	 * @param string $action
2800
+	 * @return boolean
2801
+	 * @throws EE_Error
2802
+	 */
2803
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2804
+	{
2805
+		foreach ($this->unique_indexes() as $index_name => $index) {
2806
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2807
+			if ($this->exists(array($uniqueness_where_params))) {
2808
+				EE_Error::add_error(
2809
+					sprintf(
2810
+						__(
2811
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2812
+							"event_espresso"
2813
+						),
2814
+						$action,
2815
+						$this->_get_class_name(),
2816
+						$index_name,
2817
+						implode(",", $index->field_names()),
2818
+						http_build_query($uniqueness_where_params)
2819
+					),
2820
+					__FILE__,
2821
+					__FUNCTION__,
2822
+					__LINE__
2823
+				);
2824
+				return false;
2825
+			}
2826
+		}
2827
+		return true;
2828
+	}
2829
+
2830
+
2831
+
2832
+	/**
2833
+	 * Checks the database for an item that conflicts (ie, if this item were
2834
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2835
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2836
+	 * can be either an EE_Base_Class or an array of fields n values
2837
+	 *
2838
+	 * @param EE_Base_Class|array $obj_or_fields_array
2839
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2840
+	 *                                                 when looking for conflicts
2841
+	 *                                                 (ie, if false, we ignore the model object's primary key
2842
+	 *                                                 when finding "conflicts". If true, it's also considered).
2843
+	 *                                                 Only works for INT primary key,
2844
+	 *                                                 STRING primary keys cannot be ignored
2845
+	 * @throws EE_Error
2846
+	 * @return EE_Base_Class|array
2847
+	 */
2848
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2849
+	{
2850
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2851
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2852
+		} elseif (is_array($obj_or_fields_array)) {
2853
+			$fields_n_values = $obj_or_fields_array;
2854
+		} else {
2855
+			throw new EE_Error(
2856
+				sprintf(
2857
+					__(
2858
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2859
+						"event_espresso"
2860
+					),
2861
+					get_class($this),
2862
+					$obj_or_fields_array
2863
+				)
2864
+			);
2865
+		}
2866
+		$query_params = array();
2867
+		if ($this->has_primary_key_field()
2868
+			&& ($include_primary_key
2869
+				|| $this->get_primary_key_field()
2870
+				   instanceof
2871
+				   EE_Primary_Key_String_Field)
2872
+			&& isset($fields_n_values[$this->primary_key_name()])
2873
+		) {
2874
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2875
+		}
2876
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2877
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2878
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2879
+		}
2880
+		//if there is nothing to base this search on, then we shouldn't find anything
2881
+		if (empty($query_params)) {
2882
+			return array();
2883
+		}
2884
+		return $this->get_one($query_params);
2885
+	}
2886
+
2887
+
2888
+
2889
+	/**
2890
+	 * Like count, but is optimized and returns a boolean instead of an int
2891
+	 *
2892
+	 * @param array $query_params
2893
+	 * @return boolean
2894
+	 * @throws EE_Error
2895
+	 */
2896
+	public function exists($query_params)
2897
+	{
2898
+		$query_params['limit'] = 1;
2899
+		return $this->count($query_params) > 0;
2900
+	}
2901
+
2902
+
2903
+
2904
+	/**
2905
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2906
+	 *
2907
+	 * @param int|string $id
2908
+	 * @return boolean
2909
+	 * @throws EE_Error
2910
+	 */
2911
+	public function exists_by_ID($id)
2912
+	{
2913
+		return $this->exists(
2914
+			array(
2915
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2916
+				array(
2917
+					$this->primary_key_name() => $id,
2918
+				),
2919
+			)
2920
+		);
2921
+	}
2922
+
2923
+
2924
+
2925
+	/**
2926
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2927
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2928
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2929
+	 * on the main table)
2930
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2931
+	 * cases where we want to call it directly rather than via insert().
2932
+	 *
2933
+	 * @access   protected
2934
+	 * @param EE_Table_Base $table
2935
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2936
+	 *                                       float
2937
+	 * @param int           $new_id          for now we assume only int keys
2938
+	 * @throws EE_Error
2939
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2940
+	 * @return int ID of new row inserted, or FALSE on failure
2941
+	 */
2942
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2943
+	{
2944
+		global $wpdb;
2945
+		$insertion_col_n_values = array();
2946
+		$format_for_insertion = array();
2947
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2948
+		foreach ($fields_on_table as $field_name => $field_obj) {
2949
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2950
+			if ($field_obj->is_auto_increment()) {
2951
+				continue;
2952
+			}
2953
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2954
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2955
+			if ($prepared_value !== null) {
2956
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2957
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2958
+			}
2959
+		}
2960
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2961
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2962
+			//so add the fk to the main table as a column
2963
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2964
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2965
+		}
2966
+		//insert the new entry
2967
+		$result = $this->_do_wpdb_query('insert',
2968
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2969
+		if ($result === false) {
2970
+			return false;
2971
+		}
2972
+		//ok, now what do we return for the ID of the newly-inserted thing?
2973
+		if ($this->has_primary_key_field()) {
2974
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2975
+				return $wpdb->insert_id;
2976
+			}
2977
+			//it's not an auto-increment primary key, so
2978
+			//it must have been supplied
2979
+			return $fields_n_values[$this->get_primary_key_field()->get_name()];
2980
+		}
2981
+		//we can't return a  primary key because there is none. instead return
2982
+		//a unique string indicating this model
2983
+		return $this->get_index_primary_key_string($fields_n_values);
2984
+	}
2985
+
2986
+
2987
+
2988
+	/**
2989
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2990
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2991
+	 * and there is no default, we pass it along. WPDB will take care of it)
2992
+	 *
2993
+	 * @param EE_Model_Field_Base $field_obj
2994
+	 * @param array               $fields_n_values
2995
+	 * @return mixed string|int|float depending on what the table column will be expecting
2996
+	 * @throws EE_Error
2997
+	 */
2998
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2999
+	{
3000
+		//if this field doesn't allow nullable, don't allow it
3001
+		if (
3002
+			! $field_obj->is_nullable()
3003
+			&& (
3004
+				! isset($fields_n_values[$field_obj->get_name()])
3005
+				|| $fields_n_values[$field_obj->get_name()] === null
3006
+			)
3007
+		) {
3008
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3009
+		}
3010
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3011
+			? $fields_n_values[$field_obj->get_name()]
3012
+			: null;
3013
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3014
+	}
3015
+
3016
+
3017
+
3018
+	/**
3019
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3020
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3021
+	 * the field's prepare_for_set() method.
3022
+	 *
3023
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3024
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3025
+	 *                                   top of file)
3026
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3027
+	 *                                   $value is a custom selection
3028
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3029
+	 */
3030
+	private function _prepare_value_for_use_in_db($value, $field)
3031
+	{
3032
+		if ($field && $field instanceof EE_Model_Field_Base) {
3033
+			switch ($this->_values_already_prepared_by_model_object) {
3034
+				/** @noinspection PhpMissingBreakStatementInspection */
3035
+				case self::not_prepared_by_model_object:
3036
+					$value = $field->prepare_for_set($value);
3037
+				//purposefully left out "return"
3038
+				case self::prepared_by_model_object:
3039
+					/** @noinspection SuspiciousAssignmentsInspection */
3040
+					$value = $field->prepare_for_use_in_db($value);
3041
+				case self::prepared_for_use_in_db:
3042
+					//leave the value alone
3043
+			}
3044
+			return $value;
3045
+		}
3046
+		return $value;
3047
+	}
3048
+
3049
+
3050
+
3051
+	/**
3052
+	 * Returns the main table on this model
3053
+	 *
3054
+	 * @return EE_Primary_Table
3055
+	 * @throws EE_Error
3056
+	 */
3057
+	protected function _get_main_table()
3058
+	{
3059
+		foreach ($this->_tables as $table) {
3060
+			if ($table instanceof EE_Primary_Table) {
3061
+				return $table;
3062
+			}
3063
+		}
3064
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3065
+			'event_espresso'), get_class($this)));
3066
+	}
3067
+
3068
+
3069
+
3070
+	/**
3071
+	 * table
3072
+	 * returns EE_Primary_Table table name
3073
+	 *
3074
+	 * @return string
3075
+	 * @throws EE_Error
3076
+	 */
3077
+	public function table()
3078
+	{
3079
+		return $this->_get_main_table()->get_table_name();
3080
+	}
3081
+
3082
+
3083
+
3084
+	/**
3085
+	 * table
3086
+	 * returns first EE_Secondary_Table table name
3087
+	 *
3088
+	 * @return string
3089
+	 */
3090
+	public function second_table()
3091
+	{
3092
+		// grab second table from tables array
3093
+		$second_table = end($this->_tables);
3094
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3095
+	}
3096
+
3097
+
3098
+
3099
+	/**
3100
+	 * get_table_obj_by_alias
3101
+	 * returns table name given it's alias
3102
+	 *
3103
+	 * @param string $table_alias
3104
+	 * @return EE_Primary_Table | EE_Secondary_Table
3105
+	 */
3106
+	public function get_table_obj_by_alias($table_alias = '')
3107
+	{
3108
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3109
+	}
3110
+
3111
+
3112
+
3113
+	/**
3114
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3115
+	 *
3116
+	 * @return EE_Secondary_Table[]
3117
+	 */
3118
+	protected function _get_other_tables()
3119
+	{
3120
+		$other_tables = array();
3121
+		foreach ($this->_tables as $table_alias => $table) {
3122
+			if ($table instanceof EE_Secondary_Table) {
3123
+				$other_tables[$table_alias] = $table;
3124
+			}
3125
+		}
3126
+		return $other_tables;
3127
+	}
3128
+
3129
+
3130
+
3131
+	/**
3132
+	 * Finds all the fields that correspond to the given table
3133
+	 *
3134
+	 * @param string $table_alias , array key in EEM_Base::_tables
3135
+	 * @return EE_Model_Field_Base[]
3136
+	 */
3137
+	public function _get_fields_for_table($table_alias)
3138
+	{
3139
+		return $this->_fields[$table_alias];
3140
+	}
3141
+
3142
+
3143
+
3144
+	/**
3145
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3146
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3147
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3148
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3149
+	 * related Registration, Transaction, and Payment models.
3150
+	 *
3151
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3152
+	 * @return EE_Model_Query_Info_Carrier
3153
+	 * @throws EE_Error
3154
+	 */
3155
+	public function _extract_related_models_from_query($query_params)
3156
+	{
3157
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3158
+		if (array_key_exists(0, $query_params)) {
3159
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3160
+		}
3161
+		if (array_key_exists('group_by', $query_params)) {
3162
+			if (is_array($query_params['group_by'])) {
3163
+				$this->_extract_related_models_from_sub_params_array_values(
3164
+					$query_params['group_by'],
3165
+					$query_info_carrier,
3166
+					'group_by'
3167
+				);
3168
+			} elseif (! empty ($query_params['group_by'])) {
3169
+				$this->_extract_related_model_info_from_query_param(
3170
+					$query_params['group_by'],
3171
+					$query_info_carrier,
3172
+					'group_by'
3173
+				);
3174
+			}
3175
+		}
3176
+		if (array_key_exists('having', $query_params)) {
3177
+			$this->_extract_related_models_from_sub_params_array_keys(
3178
+				$query_params[0],
3179
+				$query_info_carrier,
3180
+				'having'
3181
+			);
3182
+		}
3183
+		if (array_key_exists('order_by', $query_params)) {
3184
+			if (is_array($query_params['order_by'])) {
3185
+				$this->_extract_related_models_from_sub_params_array_keys(
3186
+					$query_params['order_by'],
3187
+					$query_info_carrier,
3188
+					'order_by'
3189
+				);
3190
+			} elseif (! empty($query_params['order_by'])) {
3191
+				$this->_extract_related_model_info_from_query_param(
3192
+					$query_params['order_by'],
3193
+					$query_info_carrier,
3194
+					'order_by'
3195
+				);
3196
+			}
3197
+		}
3198
+		if (array_key_exists('force_join', $query_params)) {
3199
+			$this->_extract_related_models_from_sub_params_array_values(
3200
+				$query_params['force_join'],
3201
+				$query_info_carrier,
3202
+				'force_join'
3203
+			);
3204
+		}
3205
+		return $query_info_carrier;
3206
+	}
3207
+
3208
+
3209
+
3210
+	/**
3211
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3212
+	 *
3213
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3214
+	 *                                                      $query_params['having']
3215
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3216
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3217
+	 * @throws EE_Error
3218
+	 * @return \EE_Model_Query_Info_Carrier
3219
+	 */
3220
+	private function _extract_related_models_from_sub_params_array_keys(
3221
+		$sub_query_params,
3222
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3223
+		$query_param_type
3224
+	) {
3225
+		if (! empty($sub_query_params)) {
3226
+			$sub_query_params = (array)$sub_query_params;
3227
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3228
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3229
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3230
+					$query_param_type);
3231
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3232
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3233
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3234
+				//of array('Registration.TXN_ID'=>23)
3235
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3236
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3237
+					if (! is_array($possibly_array_of_params)) {
3238
+						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'))",
3239
+							"event_espresso"),
3240
+							$param, $possibly_array_of_params));
3241
+					}
3242
+					$this->_extract_related_models_from_sub_params_array_keys(
3243
+						$possibly_array_of_params,
3244
+						$model_query_info_carrier, $query_param_type
3245
+					);
3246
+				} elseif ($query_param_type === 0 //ie WHERE
3247
+						  && is_array($possibly_array_of_params)
3248
+						  && isset($possibly_array_of_params[2])
3249
+						  && $possibly_array_of_params[2] == true
3250
+				) {
3251
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3252
+					//indicating that $possible_array_of_params[1] is actually a field name,
3253
+					//from which we should extract query parameters!
3254
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3255
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3256
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3257
+					}
3258
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3259
+						$model_query_info_carrier, $query_param_type);
3260
+				}
3261
+			}
3262
+		}
3263
+		return $model_query_info_carrier;
3264
+	}
3265
+
3266
+
3267
+
3268
+	/**
3269
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3270
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3271
+	 *
3272
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3273
+	 *                                                      $query_params['having']
3274
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3275
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3276
+	 * @throws EE_Error
3277
+	 * @return \EE_Model_Query_Info_Carrier
3278
+	 */
3279
+	private function _extract_related_models_from_sub_params_array_values(
3280
+		$sub_query_params,
3281
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3282
+		$query_param_type
3283
+	) {
3284
+		if (! empty($sub_query_params)) {
3285
+			if (! is_array($sub_query_params)) {
3286
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3287
+					$sub_query_params));
3288
+			}
3289
+			foreach ($sub_query_params as $param) {
3290
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3291
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3292
+					$query_param_type);
3293
+			}
3294
+		}
3295
+		return $model_query_info_carrier;
3296
+	}
3297
+
3298
+
3299
+
3300
+	/**
3301
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3302
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3303
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3304
+	 * but use them in a different order. Eg, we need to know what models we are querying
3305
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3306
+	 * other models before we can finalize the where clause SQL.
3307
+	 *
3308
+	 * @param array $query_params
3309
+	 * @throws EE_Error
3310
+	 * @return EE_Model_Query_Info_Carrier
3311
+	 */
3312
+	public function _create_model_query_info_carrier($query_params)
3313
+	{
3314
+		if (! is_array($query_params)) {
3315
+			EE_Error::doing_it_wrong(
3316
+				'EEM_Base::_create_model_query_info_carrier',
3317
+				sprintf(
3318
+					__(
3319
+						'$query_params should be an array, you passed a variable of type %s',
3320
+						'event_espresso'
3321
+					),
3322
+					gettype($query_params)
3323
+				),
3324
+				'4.6.0'
3325
+			);
3326
+			$query_params = array();
3327
+		}
3328
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3329
+		//first check if we should alter the query to account for caps or not
3330
+		//because the caps might require us to do extra joins
3331
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3332
+			$query_params[0] = $where_query_params = array_replace_recursive(
3333
+				$where_query_params,
3334
+				$this->caps_where_conditions(
3335
+					$query_params['caps']
3336
+				)
3337
+			);
3338
+		}
3339
+		$query_object = $this->_extract_related_models_from_query($query_params);
3340
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3341
+		foreach ($where_query_params as $key => $value) {
3342
+			if (is_int($key)) {
3343
+				throw new EE_Error(
3344
+					sprintf(
3345
+						__(
3346
+							"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.",
3347
+							"event_espresso"
3348
+						),
3349
+						$key,
3350
+						var_export($value, true),
3351
+						var_export($query_params, true),
3352
+						get_class($this)
3353
+					)
3354
+				);
3355
+			}
3356
+		}
3357
+		if (
3358
+			array_key_exists('default_where_conditions', $query_params)
3359
+			&& ! empty($query_params['default_where_conditions'])
3360
+		) {
3361
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3362
+		} else {
3363
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3364
+		}
3365
+		$where_query_params = array_merge(
3366
+			$this->_get_default_where_conditions_for_models_in_query(
3367
+				$query_object,
3368
+				$use_default_where_conditions,
3369
+				$where_query_params
3370
+			),
3371
+			$where_query_params
3372
+		);
3373
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3374
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3375
+		// So we need to setup a subquery and use that for the main join.
3376
+		// Note for now this only works on the primary table for the model.
3377
+		// So for instance, you could set the limit array like this:
3378
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3379
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3380
+			$query_object->set_main_model_join_sql(
3381
+				$this->_construct_limit_join_select(
3382
+					$query_params['on_join_limit'][0],
3383
+					$query_params['on_join_limit'][1]
3384
+				)
3385
+			);
3386
+		}
3387
+		//set limit
3388
+		if (array_key_exists('limit', $query_params)) {
3389
+			if (is_array($query_params['limit'])) {
3390
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3391
+					$e = sprintf(
3392
+						__(
3393
+							"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)",
3394
+							"event_espresso"
3395
+						),
3396
+						http_build_query($query_params['limit'])
3397
+					);
3398
+					throw new EE_Error($e . "|" . $e);
3399
+				}
3400
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3401
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3402
+			} elseif (! empty ($query_params['limit'])) {
3403
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3404
+			}
3405
+		}
3406
+		//set order by
3407
+		if (array_key_exists('order_by', $query_params)) {
3408
+			if (is_array($query_params['order_by'])) {
3409
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3410
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3411
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3412
+				if (array_key_exists('order', $query_params)) {
3413
+					throw new EE_Error(
3414
+						sprintf(
3415
+							__(
3416
+								"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 ",
3417
+								"event_espresso"
3418
+							),
3419
+							get_class($this),
3420
+							implode(", ", array_keys($query_params['order_by'])),
3421
+							implode(", ", $query_params['order_by']),
3422
+							$query_params['order']
3423
+						)
3424
+					);
3425
+				}
3426
+				$this->_extract_related_models_from_sub_params_array_keys(
3427
+					$query_params['order_by'],
3428
+					$query_object,
3429
+					'order_by'
3430
+				);
3431
+				//assume it's an array of fields to order by
3432
+				$order_array = array();
3433
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3434
+					$order = $this->_extract_order($order);
3435
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3436
+				}
3437
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3438
+			} elseif (! empty ($query_params['order_by'])) {
3439
+				$this->_extract_related_model_info_from_query_param(
3440
+					$query_params['order_by'],
3441
+					$query_object,
3442
+					'order',
3443
+					$query_params['order_by']
3444
+				);
3445
+				$order = isset($query_params['order'])
3446
+					? $this->_extract_order($query_params['order'])
3447
+					: 'DESC';
3448
+				$query_object->set_order_by_sql(
3449
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3450
+				);
3451
+			}
3452
+		}
3453
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3454
+		if (! array_key_exists('order_by', $query_params)
3455
+			&& array_key_exists('order', $query_params)
3456
+			&& ! empty($query_params['order'])
3457
+		) {
3458
+			$pk_field = $this->get_primary_key_field();
3459
+			$order = $this->_extract_order($query_params['order']);
3460
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3461
+		}
3462
+		//set group by
3463
+		if (array_key_exists('group_by', $query_params)) {
3464
+			if (is_array($query_params['group_by'])) {
3465
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3466
+				$group_by_array = array();
3467
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3468
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3469
+				}
3470
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3471
+			} elseif (! empty ($query_params['group_by'])) {
3472
+				$query_object->set_group_by_sql(
3473
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3474
+				);
3475
+			}
3476
+		}
3477
+		//set having
3478
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3479
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3480
+		}
3481
+		//now, just verify they didn't pass anything wack
3482
+		foreach ($query_params as $query_key => $query_value) {
3483
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3484
+				throw new EE_Error(
3485
+					sprintf(
3486
+						__(
3487
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3488
+							'event_espresso'
3489
+						),
3490
+						$query_key,
3491
+						get_class($this),
3492
+						//						print_r( $this->_allowed_query_params, TRUE )
3493
+						implode(',', $this->_allowed_query_params)
3494
+					)
3495
+				);
3496
+			}
3497
+		}
3498
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3499
+		if (empty($main_model_join_sql)) {
3500
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3501
+		}
3502
+		return $query_object;
3503
+	}
3504
+
3505
+
3506
+
3507
+	/**
3508
+	 * Gets the where conditions that should be imposed on the query based on the
3509
+	 * context (eg reading frontend, backend, edit or delete).
3510
+	 *
3511
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3512
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3513
+	 * @throws EE_Error
3514
+	 */
3515
+	public function caps_where_conditions($context = self::caps_read)
3516
+	{
3517
+		EEM_Base::verify_is_valid_cap_context($context);
3518
+		$cap_where_conditions = array();
3519
+		$cap_restrictions = $this->caps_missing($context);
3520
+		/**
3521
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3522
+		 */
3523
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3524
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3525
+				$restriction_if_no_cap->get_default_where_conditions());
3526
+		}
3527
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3528
+			$cap_restrictions);
3529
+	}
3530
+
3531
+
3532
+
3533
+	/**
3534
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3535
+	 * otherwise throws an exception
3536
+	 *
3537
+	 * @param string $should_be_order_string
3538
+	 * @return string either ASC, asc, DESC or desc
3539
+	 * @throws EE_Error
3540
+	 */
3541
+	private function _extract_order($should_be_order_string)
3542
+	{
3543
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3544
+			return $should_be_order_string;
3545
+		}
3546
+		throw new EE_Error(
3547
+			sprintf(
3548
+				__(
3549
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3550
+					"event_espresso"
3551
+				), get_class($this), $should_be_order_string
3552
+			)
3553
+		);
3554
+	}
3555
+
3556
+
3557
+
3558
+	/**
3559
+	 * Looks at all the models which are included in this query, and asks each
3560
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3561
+	 * so they can be merged
3562
+	 *
3563
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3564
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3565
+	 *                                                                  'none' means NO default where conditions will
3566
+	 *                                                                  be used AT ALL during this query.
3567
+	 *                                                                  'other_models_only' means default where
3568
+	 *                                                                  conditions from other models will be used, but
3569
+	 *                                                                  not for this primary model. 'all', the default,
3570
+	 *                                                                  means default where conditions will apply as
3571
+	 *                                                                  normal
3572
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3573
+	 * @throws EE_Error
3574
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3575
+	 */
3576
+	private function _get_default_where_conditions_for_models_in_query(
3577
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3578
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3579
+		$where_query_params = array()
3580
+	) {
3581
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3582
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3583
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3584
+				"event_espresso"), $use_default_where_conditions,
3585
+				implode(", ", $allowed_used_default_where_conditions_values)));
3586
+		}
3587
+		$universal_query_params = array();
3588
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3589
+			$universal_query_params = $this->_get_default_where_conditions();
3590
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3591
+			$universal_query_params = $this->_get_minimum_where_conditions();
3592
+		}
3593
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3594
+			$related_model = $this->get_related_model_obj($model_name);
3595
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3596
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3597
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3598
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3599
+			} else {
3600
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3601
+				continue;
3602
+			}
3603
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3604
+				$related_model_universal_where_params,
3605
+				$where_query_params,
3606
+				$related_model,
3607
+				$model_relation_path
3608
+			);
3609
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3610
+				$universal_query_params,
3611
+				$overrides
3612
+			);
3613
+		}
3614
+		return $universal_query_params;
3615
+	}
3616
+
3617
+
3618
+
3619
+	/**
3620
+	 * Determines whether or not we should use default where conditions for the model in question
3621
+	 * (this model, or other related models).
3622
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3623
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3624
+	 * We should use default where conditions on related models when they requested to use default where conditions
3625
+	 * on all models, or specifically just on other related models
3626
+	 * @param      $default_where_conditions_value
3627
+	 * @param bool $for_this_model false means this is for OTHER related models
3628
+	 * @return bool
3629
+	 */
3630
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3631
+	{
3632
+		return (
3633
+				   $for_this_model
3634
+				   && in_array(
3635
+					   $default_where_conditions_value,
3636
+					   array(
3637
+						   EEM_Base::default_where_conditions_all,
3638
+						   EEM_Base::default_where_conditions_this_only,
3639
+						   EEM_Base::default_where_conditions_minimum_others,
3640
+					   ),
3641
+					   true
3642
+				   )
3643
+			   )
3644
+			   || (
3645
+				   ! $for_this_model
3646
+				   && in_array(
3647
+					   $default_where_conditions_value,
3648
+					   array(
3649
+						   EEM_Base::default_where_conditions_all,
3650
+						   EEM_Base::default_where_conditions_others_only,
3651
+					   ),
3652
+					   true
3653
+				   )
3654
+			   );
3655
+	}
3656
+
3657
+	/**
3658
+	 * Determines whether or not we should use default minimum conditions for the model in question
3659
+	 * (this model, or other related models).
3660
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3661
+	 * where conditions.
3662
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3663
+	 * on this model or others
3664
+	 * @param      $default_where_conditions_value
3665
+	 * @param bool $for_this_model false means this is for OTHER related models
3666
+	 * @return bool
3667
+	 */
3668
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3669
+	{
3670
+		return (
3671
+				   $for_this_model
3672
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3673
+			   )
3674
+			   || (
3675
+				   ! $for_this_model
3676
+				   && in_array(
3677
+					   $default_where_conditions_value,
3678
+					   array(
3679
+						   EEM_Base::default_where_conditions_minimum_others,
3680
+						   EEM_Base::default_where_conditions_minimum_all,
3681
+					   ),
3682
+					   true
3683
+				   )
3684
+			   );
3685
+	}
3686
+
3687
+
3688
+	/**
3689
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3690
+	 * then we also add a special where condition which allows for that model's primary key
3691
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3692
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3693
+	 *
3694
+	 * @param array    $default_where_conditions
3695
+	 * @param array    $provided_where_conditions
3696
+	 * @param EEM_Base $model
3697
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3698
+	 * @return array like EEM_Base::get_all's $query_params[0]
3699
+	 * @throws EE_Error
3700
+	 */
3701
+	private function _override_defaults_or_make_null_friendly(
3702
+		$default_where_conditions,
3703
+		$provided_where_conditions,
3704
+		$model,
3705
+		$model_relation_path
3706
+	) {
3707
+		$null_friendly_where_conditions = array();
3708
+		$none_overridden = true;
3709
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3710
+		foreach ($default_where_conditions as $key => $val) {
3711
+			if (isset($provided_where_conditions[$key])) {
3712
+				$none_overridden = false;
3713
+			} else {
3714
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3715
+			}
3716
+		}
3717
+		if ($none_overridden && $default_where_conditions) {
3718
+			if ($model->has_primary_key_field()) {
3719
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3720
+																				. "."
3721
+																				. $model->primary_key_name()] = array('IS NULL');
3722
+			}/*else{
3723 3723
 				//@todo NO PK, use other defaults
3724 3724
 			}*/
3725
-        }
3726
-        return $null_friendly_where_conditions;
3727
-    }
3728
-
3729
-
3730
-
3731
-    /**
3732
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3733
-     * default where conditions on all get_all, update, and delete queries done by this model.
3734
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3735
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3736
-     *
3737
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3738
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3739
-     */
3740
-    private function _get_default_where_conditions($model_relation_path = null)
3741
-    {
3742
-        if ($this->_ignore_where_strategy) {
3743
-            return array();
3744
-        }
3745
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3746
-    }
3747
-
3748
-
3749
-
3750
-    /**
3751
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3752
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3753
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3754
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3755
-     * Similar to _get_default_where_conditions
3756
-     *
3757
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3758
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3759
-     */
3760
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3761
-    {
3762
-        if ($this->_ignore_where_strategy) {
3763
-            return array();
3764
-        }
3765
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3766
-    }
3767
-
3768
-
3769
-
3770
-    /**
3771
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3772
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3773
-     *
3774
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3775
-     * @return string
3776
-     * @throws EE_Error
3777
-     */
3778
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3779
-    {
3780
-        $selects = $this->_get_columns_to_select_for_this_model();
3781
-        foreach (
3782
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3783
-            $name_of_other_model_included
3784
-        ) {
3785
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3786
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3787
-            foreach ($other_model_selects as $key => $value) {
3788
-                $selects[] = $value;
3789
-            }
3790
-        }
3791
-        return implode(", ", $selects);
3792
-    }
3793
-
3794
-
3795
-
3796
-    /**
3797
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3798
-     * So that's going to be the columns for all the fields on the model
3799
-     *
3800
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3801
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3802
-     */
3803
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3804
-    {
3805
-        $fields = $this->field_settings();
3806
-        $selects = array();
3807
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3808
-            $this->get_this_model_name());
3809
-        foreach ($fields as $field_obj) {
3810
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3811
-                         . $field_obj->get_table_alias()
3812
-                         . "."
3813
-                         . $field_obj->get_table_column()
3814
-                         . " AS '"
3815
-                         . $table_alias_with_model_relation_chain_prefix
3816
-                         . $field_obj->get_table_alias()
3817
-                         . "."
3818
-                         . $field_obj->get_table_column()
3819
-                         . "'";
3820
-        }
3821
-        //make sure we are also getting the PKs of each table
3822
-        $tables = $this->get_tables();
3823
-        if (count($tables) > 1) {
3824
-            foreach ($tables as $table_obj) {
3825
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3826
-                                       . $table_obj->get_fully_qualified_pk_column();
3827
-                if (! in_array($qualified_pk_column, $selects)) {
3828
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3829
-                }
3830
-            }
3831
-        }
3832
-        return $selects;
3833
-    }
3834
-
3835
-
3836
-
3837
-    /**
3838
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3839
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3840
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3841
-     * SQL for joining, and the data types
3842
-     *
3843
-     * @param null|string                 $original_query_param
3844
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3845
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3846
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3847
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3848
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3849
-     *                                                          or 'Registration's
3850
-     * @param string                      $original_query_param what it originally was (eg
3851
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3852
-     *                                                          matches $query_param
3853
-     * @throws EE_Error
3854
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3855
-     */
3856
-    private function _extract_related_model_info_from_query_param(
3857
-        $query_param,
3858
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3859
-        $query_param_type,
3860
-        $original_query_param = null
3861
-    ) {
3862
-        if ($original_query_param === null) {
3863
-            $original_query_param = $query_param;
3864
-        }
3865
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3866
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3867
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3868
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3869
-        //check to see if we have a field on this model
3870
-        $this_model_fields = $this->field_settings(true);
3871
-        if (array_key_exists($query_param, $this_model_fields)) {
3872
-            if ($allow_fields) {
3873
-                return;
3874
-            }
3875
-            throw new EE_Error(
3876
-                sprintf(
3877
-                    __(
3878
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3879
-                        "event_espresso"
3880
-                    ),
3881
-                    $query_param, get_class($this), $query_param_type, $original_query_param
3882
-                )
3883
-            );
3884
-        }
3885
-        //check if this is a special logic query param
3886
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3887
-            if ($allow_logic_query_params) {
3888
-                return;
3889
-            }
3890
-            throw new EE_Error(
3891
-                sprintf(
3892
-                    __(
3893
-                        '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',
3894
-                        'event_espresso'
3895
-                    ),
3896
-                    implode('", "', $this->_logic_query_param_keys),
3897
-                    $query_param,
3898
-                    get_class($this),
3899
-                    '<br />',
3900
-                    "\t"
3901
-                    . ' $passed_in_query_info = <pre>'
3902
-                    . print_r($passed_in_query_info, true)
3903
-                    . '</pre>'
3904
-                    . "\n\t"
3905
-                    . ' $query_param_type = '
3906
-                    . $query_param_type
3907
-                    . "\n\t"
3908
-                    . ' $original_query_param = '
3909
-                    . $original_query_param
3910
-                )
3911
-            );
3912
-        }
3913
-        //check if it's a custom selection
3914
-        if (array_key_exists($query_param, $this->_custom_selections)) {
3915
-            return;
3916
-        }
3917
-        //check if has a model name at the beginning
3918
-        //and
3919
-        //check if it's a field on a related model
3920
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3921
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3922
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3923
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3924
-                if ($query_param === '') {
3925
-                    //nothing left to $query_param
3926
-                    //we should actually end in a field name, not a model like this!
3927
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3928
-                        "event_espresso"),
3929
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3930
-                }
3931
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3932
-                $related_model_obj->_extract_related_model_info_from_query_param(
3933
-                    $query_param,
3934
-                    $passed_in_query_info, $query_param_type, $original_query_param
3935
-                );
3936
-                return;
3937
-            }
3938
-            if ($query_param === $valid_related_model_name) {
3939
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3940
-                return;
3941
-            }
3942
-        }
3943
-        //ok so $query_param didn't start with a model name
3944
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3945
-        //it's wack, that's what it is
3946
-        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",
3947
-            "event_espresso"),
3948
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3949
-    }
3950
-
3951
-
3952
-
3953
-    /**
3954
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3955
-     * and store it on $passed_in_query_info
3956
-     *
3957
-     * @param string                      $model_name
3958
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3959
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3960
-     *                                                          model and $model_name. Eg, if we are querying Event,
3961
-     *                                                          and are adding a join to 'Payment' with the original
3962
-     *                                                          query param key
3963
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3964
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3965
-     *                                                          Payment wants to add default query params so that it
3966
-     *                                                          will know what models to prepend onto its default query
3967
-     *                                                          params or in case it wants to rename tables (in case
3968
-     *                                                          there are multiple joins to the same table)
3969
-     * @return void
3970
-     * @throws EE_Error
3971
-     */
3972
-    private function _add_join_to_model(
3973
-        $model_name,
3974
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3975
-        $original_query_param
3976
-    ) {
3977
-        $relation_obj = $this->related_settings_for($model_name);
3978
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3979
-        //check if the relation is HABTM, because then we're essentially doing two joins
3980
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3981
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3982
-            $join_model_obj = $relation_obj->get_join_model();
3983
-            //replace the model specified with the join model for this relation chain, whi
3984
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3985
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3986
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3987
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3988
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3989
-            $passed_in_query_info->merge($new_query_info);
3990
-        }
3991
-        //now just join to the other table pointed to by the relation object, and add its data types
3992
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3993
-            array($model_relation_chain => $model_name),
3994
-            $relation_obj->get_join_statement($model_relation_chain));
3995
-        $passed_in_query_info->merge($new_query_info);
3996
-    }
3997
-
3998
-
3999
-
4000
-    /**
4001
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4002
-     *
4003
-     * @param array $where_params like EEM_Base::get_all
4004
-     * @return string of SQL
4005
-     * @throws EE_Error
4006
-     */
4007
-    private function _construct_where_clause($where_params)
4008
-    {
4009
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4010
-        if ($SQL) {
4011
-            return " WHERE " . $SQL;
4012
-        }
4013
-        return '';
4014
-    }
4015
-
4016
-
4017
-
4018
-    /**
4019
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4020
-     * and should be passed HAVING parameters, not WHERE parameters
4021
-     *
4022
-     * @param array $having_params
4023
-     * @return string
4024
-     * @throws EE_Error
4025
-     */
4026
-    private function _construct_having_clause($having_params)
4027
-    {
4028
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4029
-        if ($SQL) {
4030
-            return " HAVING " . $SQL;
4031
-        }
4032
-        return '';
4033
-    }
4034
-
4035
-
4036
-
4037
-    /**
4038
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
4039
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
4040
-     * EEM_Attendee.
4041
-     *
4042
-     * @param string $field_name
4043
-     * @param string $model_name
4044
-     * @return EE_Model_Field_Base
4045
-     * @throws EE_Error
4046
-     */
4047
-    protected function _get_field_on_model($field_name, $model_name)
4048
-    {
4049
-        $model_class = 'EEM_' . $model_name;
4050
-        $model_filepath = $model_class . ".model.php";
4051
-        if (is_readable($model_filepath)) {
4052
-            require_once($model_filepath);
4053
-            $model_instance = call_user_func($model_name . "::instance");
4054
-            /* @var $model_instance EEM_Base */
4055
-            return $model_instance->field_settings_for($field_name);
4056
-        }
4057
-        throw new EE_Error(
4058
-            sprintf(
4059
-                __(
4060
-                    'No model named %s exists, with classname %s and filepath %s',
4061
-                    'event_espresso'
4062
-                ), $model_name, $model_class, $model_filepath
4063
-            )
4064
-        );
4065
-    }
4066
-
4067
-
4068
-
4069
-    /**
4070
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4071
-     * Event_Meta.meta_value = 'foo'))"
4072
-     *
4073
-     * @param array  $where_params see EEM_Base::get_all for documentation
4074
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4075
-     * @throws EE_Error
4076
-     * @return string of SQL
4077
-     */
4078
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4079
-    {
4080
-        $where_clauses = array();
4081
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4082
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4083
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4084
-                switch ($query_param) {
4085
-                    case 'not':
4086
-                    case 'NOT':
4087
-                        $where_clauses[] = "! ("
4088
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4089
-                                $glue)
4090
-                                           . ")";
4091
-                        break;
4092
-                    case 'and':
4093
-                    case 'AND':
4094
-                        $where_clauses[] = " ("
4095
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4096
-                                ' AND ')
4097
-                                           . ")";
4098
-                        break;
4099
-                    case 'or':
4100
-                    case 'OR':
4101
-                        $where_clauses[] = " ("
4102
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4103
-                                ' OR ')
4104
-                                           . ")";
4105
-                        break;
4106
-                }
4107
-            } else {
4108
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4109
-                //if it's not a normal field, maybe it's a custom selection?
4110
-                if (! $field_obj) {
4111
-                    if (isset($this->_custom_selections[$query_param][1])) {
4112
-                        $field_obj = $this->_custom_selections[$query_param][1];
4113
-                    } else {
4114
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4115
-                            "event_espresso"), $query_param));
4116
-                    }
4117
-                }
4118
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4119
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4120
-            }
4121
-        }
4122
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4123
-    }
4124
-
4125
-
4126
-
4127
-    /**
4128
-     * Takes the input parameter and extract the table name (alias) and column name
4129
-     *
4130
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4131
-     * @throws EE_Error
4132
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4133
-     */
4134
-    private function _deduce_column_name_from_query_param($query_param)
4135
-    {
4136
-        $field = $this->_deduce_field_from_query_param($query_param);
4137
-        if ($field) {
4138
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4139
-                $query_param);
4140
-            return $table_alias_prefix . $field->get_qualified_column();
4141
-        }
4142
-        if (array_key_exists($query_param, $this->_custom_selections)) {
4143
-            //maybe it's custom selection item?
4144
-            //if so, just use it as the "column name"
4145
-            return $query_param;
4146
-        }
4147
-        throw new EE_Error(
4148
-            sprintf(
4149
-                __(
4150
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4151
-                    "event_espresso"
4152
-                ), $query_param, implode(",", $this->_custom_selections)
4153
-            )
4154
-        );
4155
-    }
4156
-
4157
-
4158
-
4159
-    /**
4160
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4161
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4162
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4163
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4164
-     *
4165
-     * @param string $condition_query_param_key
4166
-     * @return string
4167
-     */
4168
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4169
-    {
4170
-        $pos_of_star = strpos($condition_query_param_key, '*');
4171
-        if ($pos_of_star === false) {
4172
-            return $condition_query_param_key;
4173
-        }
4174
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4175
-        return $condition_query_param_sans_star;
4176
-    }
4177
-
4178
-
4179
-
4180
-    /**
4181
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4182
-     *
4183
-     * @param                            mixed      array | string    $op_and_value
4184
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4185
-     * @throws EE_Error
4186
-     * @return string
4187
-     */
4188
-    private function _construct_op_and_value($op_and_value, $field_obj)
4189
-    {
4190
-        if (is_array($op_and_value)) {
4191
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4192
-            if (! $operator) {
4193
-                $php_array_like_string = array();
4194
-                foreach ($op_and_value as $key => $value) {
4195
-                    $php_array_like_string[] = "$key=>$value";
4196
-                }
4197
-                throw new EE_Error(
4198
-                    sprintf(
4199
-                        __(
4200
-                            "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))",
4201
-                            "event_espresso"
4202
-                        ),
4203
-                        implode(",", $php_array_like_string)
4204
-                    )
4205
-                );
4206
-            }
4207
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4208
-        } else {
4209
-            $operator = '=';
4210
-            $value = $op_and_value;
4211
-        }
4212
-        //check to see if the value is actually another field
4213
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4214
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4215
-        }
4216
-        if (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4217
-            //in this case, the value should be an array, or at least a comma-separated list
4218
-            //it will need to handle a little differently
4219
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4220
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4221
-            return $operator . SP . $cleaned_value;
4222
-        }
4223
-        if (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4224
-            //the value should be an array with count of two.
4225
-            if (count($value) !== 2) {
4226
-                throw new EE_Error(
4227
-                    sprintf(
4228
-                        __(
4229
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4230
-                            'event_espresso'
4231
-                        ),
4232
-                        "BETWEEN"
4233
-                    )
4234
-                );
4235
-            }
4236
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4237
-            return $operator . SP . $cleaned_value;
4238
-        }
4239
-        if (in_array($operator, $this->_null_style_operators)) {
4240
-            if ($value !== null) {
4241
-                throw new EE_Error(
4242
-                    sprintf(
4243
-                        __(
4244
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4245
-                            "event_espresso"
4246
-                        ),
4247
-                        $value,
4248
-                        $operator
4249
-                    )
4250
-                );
4251
-            }
4252
-            return $operator;
4253
-        }
4254
-        if ($operator === 'LIKE' && ! is_array($value)) {
4255
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4256
-            //remove other junk. So just treat it as a string.
4257
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4258
-        }
4259
-        if (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4260
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4261
-        }
4262
-        if (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4263
-            throw new EE_Error(
4264
-                sprintf(
4265
-                    __(
4266
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4267
-                        'event_espresso'
4268
-                    ),
4269
-                    $operator,
4270
-                    $operator
4271
-                )
4272
-            );
4273
-        }
4274
-        if (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4275
-            throw new EE_Error(
4276
-                sprintf(
4277
-                    __(
4278
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4279
-                        'event_espresso'
4280
-                    ),
4281
-                    $operator,
4282
-                    $operator
4283
-                )
4284
-            );
4285
-        }
4286
-        throw new EE_Error(
4287
-            sprintf(
4288
-                __(
4289
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4290
-                    "event_espresso"
4291
-                ),
4292
-                http_build_query($op_and_value)
4293
-            )
4294
-        );
4295
-    }
4296
-
4297
-
4298
-
4299
-    /**
4300
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4301
-     *
4302
-     * @param array                      $values
4303
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4304
-     *                                              '%s'
4305
-     * @return string
4306
-     * @throws EE_Error
4307
-     */
4308
-    public function _construct_between_value($values, $field_obj)
4309
-    {
4310
-        $cleaned_values = array();
4311
-        foreach ($values as $value) {
4312
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4313
-        }
4314
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4315
-    }
4316
-
4317
-
4318
-
4319
-    /**
4320
-     * Takes an array or a comma-separated list of $values and cleans them
4321
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4322
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4323
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4324
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4325
-     *
4326
-     * @param mixed                      $values    array or comma-separated string
4327
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4328
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4329
-     * @throws EE_Error
4330
-     */
4331
-    public function _construct_in_value($values, $field_obj)
4332
-    {
4333
-        //check if the value is a CSV list
4334
-        if (is_string($values)) {
4335
-            //in which case, turn it into an array
4336
-            $values = explode(",", $values);
4337
-        }
4338
-        $cleaned_values = array();
4339
-        foreach ($values as $value) {
4340
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4341
-        }
4342
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4343
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4344
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4345
-        if (empty($cleaned_values)) {
4346
-            $all_fields = $this->field_settings();
4347
-            $a_field = array_shift($all_fields);
4348
-            $main_table = $this->_get_main_table();
4349
-            $cleaned_values[] = "SELECT "
4350
-                                . $a_field->get_table_column()
4351
-                                . " FROM "
4352
-                                . $main_table->get_table_name()
4353
-                                . " WHERE FALSE";
4354
-        }
4355
-        return "(" . implode(",", $cleaned_values) . ")";
4356
-    }
4357
-
4358
-
4359
-
4360
-    /**
4361
-     * @param mixed                      $value
4362
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4363
-     * @throws EE_Error
4364
-     * @return false|null|string
4365
-     */
4366
-    private function _wpdb_prepare_using_field($value, $field_obj)
4367
-    {
4368
-        /** @type WPDB $wpdb */
4369
-        global $wpdb;
4370
-        if ($field_obj instanceof EE_Model_Field_Base) {
4371
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4372
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4373
-        } //$field_obj should really just be a data type
4374
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4375
-            throw new EE_Error(
4376
-                sprintf(
4377
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4378
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4379
-                )
4380
-            );
4381
-        }
4382
-        return $wpdb->prepare($field_obj, $value);
4383
-    }
4384
-
4385
-
4386
-
4387
-    /**
4388
-     * Takes the input parameter and finds the model field that it indicates.
4389
-     *
4390
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4391
-     * @throws EE_Error
4392
-     * @return EE_Model_Field_Base
4393
-     */
4394
-    protected function _deduce_field_from_query_param($query_param_name)
4395
-    {
4396
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4397
-        //which will help us find the database table and column
4398
-        $query_param_parts = explode(".", $query_param_name);
4399
-        if (empty($query_param_parts)) {
4400
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4401
-                'event_espresso'), $query_param_name));
4402
-        }
4403
-        $number_of_parts = count($query_param_parts);
4404
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4405
-        if ($number_of_parts === 1) {
4406
-            $field_name = $last_query_param_part;
4407
-            $model_obj = $this;
4408
-        } else {// $number_of_parts >= 2
4409
-            //the last part is the column name, and there are only 2parts. therefore...
4410
-            $field_name = $last_query_param_part;
4411
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4412
-        }
4413
-        try {
4414
-            return $model_obj->field_settings_for($field_name);
4415
-        } catch (EE_Error $e) {
4416
-            return null;
4417
-        }
4418
-    }
4419
-
4420
-
4421
-
4422
-    /**
4423
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4424
-     * alias and column which corresponds to it
4425
-     *
4426
-     * @param string $field_name
4427
-     * @throws EE_Error
4428
-     * @return string
4429
-     */
4430
-    public function _get_qualified_column_for_field($field_name)
4431
-    {
4432
-        $all_fields = $this->field_settings();
4433
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4434
-        if ($field) {
4435
-            return $field->get_qualified_column();
4436
-        }
4437
-        throw new EE_Error(
4438
-            sprintf(
4439
-                __(
4440
-                    "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.",
4441
-                    'event_espresso'
4442
-                ), $field_name, get_class($this)
4443
-            )
4444
-        );
4445
-    }
4446
-
4447
-
4448
-
4449
-    /**
4450
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4451
-     * Example usage:
4452
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4453
-     *      array(),
4454
-     *      ARRAY_A,
4455
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4456
-     *  );
4457
-     * is equivalent to
4458
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4459
-     * and
4460
-     *  EEM_Event::instance()->get_all_wpdb_results(
4461
-     *      array(
4462
-     *          array(
4463
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4464
-     *          ),
4465
-     *          ARRAY_A,
4466
-     *          implode(
4467
-     *              ', ',
4468
-     *              array_merge(
4469
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4470
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4471
-     *              )
4472
-     *          )
4473
-     *      )
4474
-     *  );
4475
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4476
-     *
4477
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4478
-     *                                            and the one whose fields you are selecting for example: when querying
4479
-     *                                            tickets model and selecting fields from the tickets model you would
4480
-     *                                            leave this parameter empty, because no models are needed to join
4481
-     *                                            between the queried model and the selected one. Likewise when
4482
-     *                                            querying the datetime model and selecting fields from the tickets
4483
-     *                                            model, it would also be left empty, because there is a direct
4484
-     *                                            relation from datetimes to tickets, so no model is needed to join
4485
-     *                                            them together. However, when querying from the event model and
4486
-     *                                            selecting fields from the ticket model, you should provide the string
4487
-     *                                            'Datetime', indicating that the event model must first join to the
4488
-     *                                            datetime model in order to find its relation to ticket model.
4489
-     *                                            Also, when querying from the venue model and selecting fields from
4490
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4491
-     *                                            indicating you need to join the venue model to the event model,
4492
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4493
-     *                                            This string is used to deduce the prefix that gets added onto the
4494
-     *                                            models' tables qualified columns
4495
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4496
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4497
-     *                                            qualified column names
4498
-     * @return array|string
4499
-     */
4500
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4501
-    {
4502
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4503
-        $qualified_columns = array();
4504
-        foreach ($this->field_settings() as $field_name => $field) {
4505
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4506
-        }
4507
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4508
-    }
4509
-
4510
-
4511
-
4512
-    /**
4513
-     * constructs the select use on special limit joins
4514
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4515
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4516
-     * (as that is typically where the limits would be set).
4517
-     *
4518
-     * @param  string       $table_alias The table the select is being built for
4519
-     * @param  mixed|string $limit       The limit for this select
4520
-     * @return string                The final select join element for the query.
4521
-     */
4522
-    public function _construct_limit_join_select($table_alias, $limit)
4523
-    {
4524
-        $SQL = '';
4525
-        foreach ($this->_tables as $table_obj) {
4526
-            if ($table_obj instanceof EE_Primary_Table) {
4527
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4528
-                    ? $table_obj->get_select_join_limit($limit)
4529
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4530
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4531
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4532
-                    ? $table_obj->get_select_join_limit_join($limit)
4533
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4534
-            }
4535
-        }
4536
-        return $SQL;
4537
-    }
4538
-
4539
-
4540
-
4541
-    /**
4542
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4543
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4544
-     *
4545
-     * @return string SQL
4546
-     * @throws EE_Error
4547
-     */
4548
-    public function _construct_internal_join()
4549
-    {
4550
-        $SQL = $this->_get_main_table()->get_table_sql();
4551
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4552
-        return $SQL;
4553
-    }
4554
-
4555
-
4556
-
4557
-    /**
4558
-     * Constructs the SQL for joining all the tables on this model.
4559
-     * Normally $alias should be the primary table's alias, but in cases where
4560
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4561
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4562
-     * alias, this will construct SQL like:
4563
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4564
-     * With $alias being a secondary table's alias, this will construct SQL like:
4565
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4566
-     *
4567
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4568
-     * @return string
4569
-     */
4570
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4571
-    {
4572
-        $SQL = '';
4573
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4574
-        foreach ($this->_tables as $table_obj) {
4575
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4576
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4577
-                    //so we're joining to this table, meaning the table is already in
4578
-                    //the FROM statement, BUT the primary table isn't. So we want
4579
-                    //to add the inverse join sql
4580
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4581
-                } else {
4582
-                    //just add a regular JOIN to this table from the primary table
4583
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4584
-                }
4585
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4586
-        }
4587
-        return $SQL;
4588
-    }
4589
-
4590
-
4591
-
4592
-    /**
4593
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4594
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4595
-     * their data type (eg, '%s', '%d', etc)
4596
-     *
4597
-     * @return array
4598
-     */
4599
-    public function _get_data_types()
4600
-    {
4601
-        $data_types = array();
4602
-        foreach ($this->field_settings() as $field_obj) {
4603
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4604
-            /** @var $field_obj EE_Model_Field_Base */
4605
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4606
-        }
4607
-        return $data_types;
4608
-    }
4609
-
4610
-
4611
-
4612
-    /**
4613
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4614
-     *
4615
-     * @param string $model_name
4616
-     * @throws EE_Error
4617
-     * @return EEM_Base
4618
-     */
4619
-    public function get_related_model_obj($model_name)
4620
-    {
4621
-        $model_classname = "EEM_" . $model_name;
4622
-        if (! class_exists($model_classname)) {
4623
-            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",
4624
-                'event_espresso'), $model_name, $model_classname));
4625
-        }
4626
-        return call_user_func($model_classname . "::instance");
4627
-    }
4628
-
4629
-
4630
-
4631
-    /**
4632
-     * Returns the array of EE_ModelRelations for this model.
4633
-     *
4634
-     * @return EE_Model_Relation_Base[]
4635
-     */
4636
-    public function relation_settings()
4637
-    {
4638
-        return $this->_model_relations;
4639
-    }
4640
-
4641
-
4642
-
4643
-    /**
4644
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4645
-     * because without THOSE models, this model probably doesn't have much purpose.
4646
-     * (Eg, without an event, datetimes have little purpose.)
4647
-     *
4648
-     * @return EE_Belongs_To_Relation[]
4649
-     */
4650
-    public function belongs_to_relations()
4651
-    {
4652
-        $belongs_to_relations = array();
4653
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4654
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4655
-                $belongs_to_relations[$model_name] = $relation_obj;
4656
-            }
4657
-        }
4658
-        return $belongs_to_relations;
4659
-    }
4660
-
4661
-
4662
-
4663
-    /**
4664
-     * Returns the specified EE_Model_Relation, or throws an exception
4665
-     *
4666
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4667
-     * @throws EE_Error
4668
-     * @return EE_Model_Relation_Base
4669
-     */
4670
-    public function related_settings_for($relation_name)
4671
-    {
4672
-        $relatedModels = $this->relation_settings();
4673
-        if (! array_key_exists($relation_name, $relatedModels)) {
4674
-            throw new EE_Error(
4675
-                sprintf(
4676
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4677
-                        'event_espresso'),
4678
-                    $relation_name,
4679
-                    $this->_get_class_name(),
4680
-                    implode(', ', array_keys($relatedModels))
4681
-                )
4682
-            );
4683
-        }
4684
-        return $relatedModels[$relation_name];
4685
-    }
4686
-
4687
-
4688
-
4689
-    /**
4690
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4691
-     * fields
4692
-     *
4693
-     * @param string $fieldName
4694
-     * @throws EE_Error
4695
-     * @return EE_Model_Field_Base
4696
-     */
4697
-    public function field_settings_for($fieldName)
4698
-    {
4699
-        $fieldSettings = $this->field_settings(true);
4700
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4701
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4702
-                get_class($this)));
4703
-        }
4704
-        return $fieldSettings[$fieldName];
4705
-    }
4706
-
4707
-
4708
-
4709
-    /**
4710
-     * Checks if this field exists on this model
4711
-     *
4712
-     * @param string $fieldName a key in the model's _field_settings array
4713
-     * @return boolean
4714
-     */
4715
-    public function has_field($fieldName)
4716
-    {
4717
-        $fieldSettings = $this->field_settings(true);
4718
-        if (isset($fieldSettings[$fieldName])) {
4719
-            return true;
4720
-        }
4721
-        return false;
4722
-    }
4723
-
4724
-
4725
-
4726
-    /**
4727
-     * Returns whether or not this model has a relation to the specified model
4728
-     *
4729
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4730
-     * @return boolean
4731
-     */
4732
-    public function has_relation($relation_name)
4733
-    {
4734
-        $relations = $this->relation_settings();
4735
-        if (isset($relations[$relation_name])) {
4736
-            return true;
4737
-        }
4738
-        return false;
4739
-    }
4740
-
4741
-
4742
-
4743
-    /**
4744
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4745
-     * Eg, on EE_Answer that would be ANS_ID field object
4746
-     *
4747
-     * @param $field_obj
4748
-     * @return boolean
4749
-     */
4750
-    public function is_primary_key_field($field_obj)
4751
-    {
4752
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4753
-    }
4754
-
4755
-
4756
-
4757
-    /**
4758
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4759
-     * Eg, on EE_Answer that would be ANS_ID field object
4760
-     *
4761
-     * @return EE_Model_Field_Base
4762
-     * @throws EE_Error
4763
-     */
4764
-    public function get_primary_key_field()
4765
-    {
4766
-        if ($this->_primary_key_field === null) {
4767
-            foreach ($this->field_settings(true) as $field_obj) {
4768
-                if ($this->is_primary_key_field($field_obj)) {
4769
-                    $this->_primary_key_field = $field_obj;
4770
-                    break;
4771
-                }
4772
-            }
4773
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4774
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4775
-                    get_class($this)));
4776
-            }
4777
-        }
4778
-        return $this->_primary_key_field;
4779
-    }
4780
-
4781
-
4782
-
4783
-    /**
4784
-     * Returns whether or not not there is a primary key on this model.
4785
-     * Internally does some caching.
4786
-     *
4787
-     * @return boolean
4788
-     */
4789
-    public function has_primary_key_field()
4790
-    {
4791
-        if ($this->_has_primary_key_field === null) {
4792
-            try {
4793
-                $this->get_primary_key_field();
4794
-                $this->_has_primary_key_field = true;
4795
-            } catch (EE_Error $e) {
4796
-                $this->_has_primary_key_field = false;
4797
-            }
4798
-        }
4799
-        return $this->_has_primary_key_field;
4800
-    }
4801
-
4802
-
4803
-
4804
-    /**
4805
-     * Finds the first field of type $field_class_name.
4806
-     *
4807
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4808
-     *                                 EE_Foreign_Key_Field, etc
4809
-     * @return EE_Model_Field_Base or null if none is found
4810
-     */
4811
-    public function get_a_field_of_type($field_class_name)
4812
-    {
4813
-        foreach ($this->field_settings() as $field) {
4814
-            if ($field instanceof $field_class_name) {
4815
-                return $field;
4816
-            }
4817
-        }
4818
-        return null;
4819
-    }
4820
-
4821
-
4822
-
4823
-    /**
4824
-     * Gets a foreign key field pointing to model.
4825
-     *
4826
-     * @param string $model_name eg Event, Registration, not EEM_Event
4827
-     * @return EE_Foreign_Key_Field_Base
4828
-     * @throws EE_Error
4829
-     */
4830
-    public function get_foreign_key_to($model_name)
4831
-    {
4832
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4833
-            foreach ($this->field_settings() as $field) {
4834
-                if (
4835
-                    $field instanceof EE_Foreign_Key_Field_Base
4836
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4837
-                ) {
4838
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4839
-                    break;
4840
-                }
4841
-            }
4842
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4843
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4844
-                    'event_espresso'), $model_name, get_class($this)));
4845
-            }
4846
-        }
4847
-        return $this->_cache_foreign_key_to_fields[$model_name];
4848
-    }
4849
-
4850
-
4851
-
4852
-    /**
4853
-     * Gets the table name (including $wpdb->prefix) for the table alias
4854
-     *
4855
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4856
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4857
-     *                            Either one works
4858
-     * @return string
4859
-     */
4860
-    public function get_table_for_alias($table_alias)
4861
-    {
4862
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4863
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4864
-    }
4865
-
4866
-
4867
-
4868
-    /**
4869
-     * Returns a flat array of all field son this model, instead of organizing them
4870
-     * by table_alias as they are in the constructor.
4871
-     *
4872
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4873
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4874
-     */
4875
-    public function field_settings($include_db_only_fields = false)
4876
-    {
4877
-        if ($include_db_only_fields) {
4878
-            if ($this->_cached_fields === null) {
4879
-                $this->_cached_fields = array();
4880
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4881
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4882
-                        $this->_cached_fields[$field_name] = $field_obj;
4883
-                    }
4884
-                }
4885
-            }
4886
-            return $this->_cached_fields;
4887
-        }
4888
-        if ($this->_cached_fields_non_db_only === null) {
4889
-            $this->_cached_fields_non_db_only = array();
4890
-            foreach ($this->_fields as $fields_corresponding_to_table) {
4891
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4892
-                    /** @var $field_obj EE_Model_Field_Base */
4893
-                    if (! $field_obj->is_db_only_field()) {
4894
-                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4895
-                    }
4896
-                }
4897
-            }
4898
-        }
4899
-        return $this->_cached_fields_non_db_only;
4900
-    }
4901
-
4902
-
4903
-
4904
-    /**
4905
-     *        cycle though array of attendees and create objects out of each item
4906
-     *
4907
-     * @access        private
4908
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4909
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4910
-     *                           numerically indexed)
4911
-     * @throws EE_Error
4912
-     */
4913
-    protected function _create_objects($rows = array())
4914
-    {
4915
-        $array_of_objects = array();
4916
-        if (empty($rows)) {
4917
-            return array();
4918
-        }
4919
-        $count_if_model_has_no_primary_key = 0;
4920
-        $has_primary_key = $this->has_primary_key_field();
4921
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4922
-        foreach ((array)$rows as $row) {
4923
-            if (empty($row)) {
4924
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4925
-                return array();
4926
-            }
4927
-            //check if we've already set this object in the results array,
4928
-            //in which case there's no need to process it further (again)
4929
-            if ($has_primary_key) {
4930
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4931
-                    $row,
4932
-                    $primary_key_field->get_qualified_column(),
4933
-                    $primary_key_field->get_table_column()
4934
-                );
4935
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4936
-                    continue;
4937
-                }
4938
-            }
4939
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4940
-            if (! $classInstance) {
4941
-                throw new EE_Error(
4942
-                    sprintf(
4943
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4944
-                        $this->get_this_model_name(),
4945
-                        http_build_query($row)
4946
-                    )
4947
-                );
4948
-            }
4949
-            //set the timezone on the instantiated objects
4950
-            $classInstance->set_timezone($this->_timezone);
4951
-            //make sure if there is any timezone setting present that we set the timezone for the object
4952
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4953
-            $array_of_objects[$key] = $classInstance;
4954
-            //also, for all the relations of type BelongsTo, see if we can cache
4955
-            //those related models
4956
-            //(we could do this for other relations too, but if there are conditions
4957
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4958
-            //so it requires a little more thought than just caching them immediately...)
4959
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4960
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4961
-                    //check if this model's INFO is present. If so, cache it on the model
4962
-                    $other_model = $relation_obj->get_other_model();
4963
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4964
-                    //if we managed to make a model object from the results, cache it on the main model object
4965
-                    if ($other_model_obj_maybe) {
4966
-                        //set timezone on these other model objects if they are present
4967
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4968
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4969
-                    }
4970
-                }
4971
-            }
4972
-        }
4973
-        return $array_of_objects;
4974
-    }
4975
-
4976
-
4977
-
4978
-    /**
4979
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4980
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4981
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4982
-     * object (as set in the model_field!).
4983
-     *
4984
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4985
-     * @throws Exception
4986
-     */
4987
-    public function create_default_object()
4988
-    {
4989
-        $this_model_fields_and_values = array();
4990
-        //setup the row using default values;
4991
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4992
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4993
-        }
4994
-        $classInstance = $this->_instantiate_new_instance_from_db(
4995
-            $this->_get_class_name(),
4996
-            $this_model_fields_and_values
4997
-        );
4998
-        return $classInstance;
4999
-    }
5000
-
5001
-
5002
-
5003
-    /**
5004
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5005
-     *                             or an stdClass where each property is the name of a column,
5006
-     * @return EE_Base_Class
5007
-     * @throws Exception
5008
-     * @throws EE_Error
5009
-     */
5010
-    public function instantiate_class_from_array_or_object($cols_n_values)
5011
-    {
5012
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5013
-            $cols_n_values = get_object_vars($cols_n_values);
5014
-        }
5015
-        $primary_key = null;
5016
-        //make sure the array only has keys that are fields/columns on this model
5017
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5018
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5019
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5020
-        }
5021
-        //check we actually found results that we can use to build our model object
5022
-        //if not, return null
5023
-        if ($this->has_primary_key_field()) {
5024
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5025
-                return null;
5026
-            }
5027
-        } else if ($this->unique_indexes()) {
5028
-            $first_column = reset($this_model_fields_n_values);
5029
-            if (empty($first_column)) {
5030
-                return null;
5031
-            }
5032
-        }
5033
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5034
-        if ($primary_key) {
5035
-            $classInstance = $this->get_from_entity_map($primary_key);
5036
-            if (! $classInstance) {
5037
-                $classInstance = $this->_instantiate_new_instance_from_db(
5038
-                    $this->_get_class_name(),
5039
-                    $this_model_fields_n_values
5040
-                );
5041
-                // add this new object to the entity map
5042
-                $classInstance = $this->add_to_entity_map($classInstance);
5043
-            }
5044
-        } else {
5045
-            $classInstance = $this->_instantiate_new_instance_from_db(
5046
-                $this->_get_class_name(),
5047
-                $this_model_fields_n_values
5048
-            );
5049
-        }
5050
-        // it is entirely possible that the instantiated class object has a set
5051
-        // timezone_string db field and has set it's internal _timezone property accordingly
5052
-        // (see new_instance_from_db in model objects particularly EE_Event for example).
5053
-        // In this case, we want to make sure the model object doesn't have its timezone string
5054
-        // overwritten by any timezone property currently set here on the model so,
5055
-        // we intentionally override the model _timezone property with the model_object timezone property.
5056
-        $this->set_timezone($classInstance->get_timezone());
5057
-        return $classInstance;
5058
-    }
5059
-
5060
-
5061
-
5062
-    /**
5063
-     * Gets the model object from the  entity map if it exists
5064
-     *
5065
-     * @param int|string $id the ID of the model object
5066
-     * @return EE_Base_Class
5067
-     */
5068
-    public function get_from_entity_map($id)
5069
-    {
5070
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5071
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5072
-    }
5073
-
5074
-
5075
-
5076
-    /**
5077
-     * add_to_entity_map
5078
-     * Adds the object to the model's entity mappings
5079
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5080
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5081
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5082
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5083
-     *        then this method should be called immediately after the update query
5084
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5085
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5086
-     *
5087
-     * @param    EE_Base_Class $object
5088
-     * @throws EE_Error
5089
-     * @return \EE_Base_Class
5090
-     */
5091
-    public function add_to_entity_map(EE_Base_Class $object)
5092
-    {
5093
-        $className = $this->_get_class_name();
5094
-        if (! $object instanceof $className) {
5095
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5096
-                is_object($object) ? get_class($object) : $object, $className));
5097
-        }
5098
-        /** @var $object EE_Base_Class */
5099
-        if (! $object->ID()) {
5100
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5101
-                "event_espresso"), get_class($this)));
5102
-        }
5103
-        // double check it's not already there
5104
-        $classInstance = $this->get_from_entity_map($object->ID());
5105
-        if ($classInstance) {
5106
-            return $classInstance;
5107
-        }
5108
-        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5109
-        return $object;
5110
-    }
5111
-
5112
-
5113
-
5114
-    /**
5115
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5116
-     * if no identifier is provided, then the entire entity map is emptied
5117
-     *
5118
-     * @param int|string $id the ID of the model object
5119
-     * @return boolean
5120
-     */
5121
-    public function clear_entity_map($id = null)
5122
-    {
5123
-        if (empty($id)) {
5124
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5125
-            return true;
5126
-        }
5127
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5128
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5129
-            return true;
5130
-        }
5131
-        return false;
5132
-    }
5133
-
5134
-
5135
-
5136
-    /**
5137
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5138
-     * Given an array where keys are column (or column alias) names and values,
5139
-     * returns an array of their corresponding field names and database values
5140
-     *
5141
-     * @param array $cols_n_values
5142
-     * @return array
5143
-     */
5144
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5145
-    {
5146
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5147
-    }
5148
-
5149
-
5150
-
5151
-    /**
5152
-     * _deduce_fields_n_values_from_cols_n_values
5153
-     * Given an array where keys are column (or column alias) names and values,
5154
-     * returns an array of their corresponding field names and database values
5155
-     *
5156
-     * @param string $cols_n_values
5157
-     * @return array
5158
-     */
5159
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5160
-    {
5161
-        $this_model_fields_n_values = array();
5162
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5163
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5164
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5165
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5166
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5167
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5168
-                    if (! $field_obj->is_db_only_field()) {
5169
-                        //prepare field as if its coming from db
5170
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5171
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5172
-                    }
5173
-                }
5174
-            } else {
5175
-                //the table's rows existed. Use their values
5176
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5177
-                    if (! $field_obj->is_db_only_field()) {
5178
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5179
-                            $cols_n_values, $field_obj->get_qualified_column(),
5180
-                            $field_obj->get_table_column()
5181
-                        );
5182
-                    }
5183
-                }
5184
-            }
5185
-        }
5186
-        return $this_model_fields_n_values;
5187
-    }
5188
-
5189
-
5190
-
5191
-    /**
5192
-     * @param $cols_n_values
5193
-     * @param $qualified_column
5194
-     * @param $regular_column
5195
-     * @return null
5196
-     */
5197
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5198
-    {
5199
-        $value = null;
5200
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5201
-        //does the field on the model relate to this column retrieved from the db?
5202
-        //or is it a db-only field? (not relating to the model)
5203
-        if (isset($cols_n_values[$qualified_column])) {
5204
-            $value = $cols_n_values[$qualified_column];
5205
-        } elseif (isset($cols_n_values[$regular_column])) {
5206
-            $value = $cols_n_values[$regular_column];
5207
-        }
5208
-        return $value;
5209
-    }
5210
-
5211
-
5212
-
5213
-    /**
5214
-     * refresh_entity_map_from_db
5215
-     * Makes sure the model object in the entity map at $id assumes the values
5216
-     * of the database (opposite of EE_base_Class::save())
5217
-     *
5218
-     * @param int|string $id
5219
-     * @return EE_Base_Class
5220
-     * @throws EE_Error
5221
-     */
5222
-    public function refresh_entity_map_from_db($id)
5223
-    {
5224
-        $obj_in_map = $this->get_from_entity_map($id);
5225
-        if ($obj_in_map) {
5226
-            $wpdb_results = $this->_get_all_wpdb_results(
5227
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5228
-            );
5229
-            if ($wpdb_results && is_array($wpdb_results)) {
5230
-                $one_row = reset($wpdb_results);
5231
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5232
-                    $obj_in_map->set_from_db($field_name, $db_value);
5233
-                }
5234
-                //clear the cache of related model objects
5235
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5236
-                    $obj_in_map->clear_cache($relation_name, null, true);
5237
-                }
5238
-            }
5239
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5240
-            return $obj_in_map;
5241
-        }
5242
-        return $this->get_one_by_ID($id);
5243
-    }
5244
-
5245
-
5246
-
5247
-    /**
5248
-     * refresh_entity_map_with
5249
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5250
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5251
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5252
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5253
-     *
5254
-     * @param int|string    $id
5255
-     * @param EE_Base_Class $replacing_model_obj
5256
-     * @return \EE_Base_Class
5257
-     * @throws EE_Error
5258
-     */
5259
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5260
-    {
5261
-        $obj_in_map = $this->get_from_entity_map($id);
5262
-        if ($obj_in_map) {
5263
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5264
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5265
-                    $obj_in_map->set($field_name, $value);
5266
-                }
5267
-                //make the model object in the entity map's cache match the $replacing_model_obj
5268
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5269
-                    $obj_in_map->clear_cache($relation_name, null, true);
5270
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5271
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5272
-                    }
5273
-                }
5274
-            }
5275
-            return $obj_in_map;
5276
-        }
5277
-        $this->add_to_entity_map($replacing_model_obj);
5278
-        return $replacing_model_obj;
5279
-    }
5280
-
5281
-
5282
-
5283
-    /**
5284
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5285
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5286
-     * require_once($this->_getClassName().".class.php");
5287
-     *
5288
-     * @return string
5289
-     */
5290
-    private function _get_class_name()
5291
-    {
5292
-        return "EE_" . $this->get_this_model_name();
5293
-    }
5294
-
5295
-
5296
-
5297
-    /**
5298
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5299
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5300
-     * it would be 'Events'.
5301
-     *
5302
-     * @param int $quantity
5303
-     * @return string
5304
-     */
5305
-    public function item_name($quantity = 1)
5306
-    {
5307
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5308
-    }
5309
-
5310
-
5311
-
5312
-    /**
5313
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5314
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5315
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5316
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5317
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5318
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5319
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5320
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5321
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5322
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5323
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5324
-     *        return $previousReturnValue.$returnString;
5325
-     * }
5326
-     * require('EEM_Answer.model.php');
5327
-     * $answer=EEM_Answer::instance();
5328
-     * echo $answer->my_callback('monkeys',100);
5329
-     * //will output "you called my_callback! and passed args:monkeys,100"
5330
-     *
5331
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5332
-     * @param array  $args       array of original arguments passed to the function
5333
-     * @throws EE_Error
5334
-     * @return mixed whatever the plugin which calls add_filter decides
5335
-     */
5336
-    public function __call($methodName, $args)
5337
-    {
5338
-        $className = get_class($this);
5339
-        $tagName = "FHEE__{$className}__{$methodName}";
5340
-        if (! has_filter($tagName)) {
5341
-            throw new EE_Error(
5342
-                sprintf(
5343
-                    __('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 );',
5344
-                        'event_espresso'),
5345
-                    $methodName,
5346
-                    $className,
5347
-                    $tagName,
5348
-                    '<br />'
5349
-                )
5350
-            );
5351
-        }
5352
-        return apply_filters($tagName, null, $this, $args);
5353
-    }
5354
-
5355
-
5356
-
5357
-    /**
5358
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5359
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5360
-     *
5361
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5362
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5363
-     *                                                       the object's class name
5364
-     *                                                       or object's ID
5365
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5366
-     *                                                       exists in the database. If it does not, we add it
5367
-     * @throws EE_Error
5368
-     * @return EE_Base_Class
5369
-     */
5370
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5371
-    {
5372
-        $className = $this->_get_class_name();
5373
-        if ($base_class_obj_or_id instanceof $className) {
5374
-            $model_object = $base_class_obj_or_id;
5375
-        } else {
5376
-            $primary_key_field = $this->get_primary_key_field();
5377
-            if (
5378
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5379
-                && (
5380
-                    is_int($base_class_obj_or_id)
5381
-                    || is_string($base_class_obj_or_id)
5382
-                )
5383
-            ) {
5384
-                // assume it's an ID.
5385
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5386
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5387
-            } else if (
5388
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5389
-                && is_string($base_class_obj_or_id)
5390
-            ) {
5391
-                // assume its a string representation of the object
5392
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5393
-            } else {
5394
-                throw new EE_Error(
5395
-                    sprintf(
5396
-                        __(
5397
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5398
-                            'event_espresso'
5399
-                        ),
5400
-                        $base_class_obj_or_id,
5401
-                        $this->_get_class_name(),
5402
-                        print_r($base_class_obj_or_id, true)
5403
-                    )
5404
-                );
5405
-            }
5406
-        }
5407
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5408
-            $model_object->save();
5409
-        }
5410
-        return $model_object;
5411
-    }
5412
-
5413
-
5414
-
5415
-    /**
5416
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5417
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5418
-     * returns it ID.
5419
-     *
5420
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5421
-     * @return int|string depending on the type of this model object's ID
5422
-     * @throws EE_Error
5423
-     */
5424
-    public function ensure_is_ID($base_class_obj_or_id)
5425
-    {
5426
-        $className = $this->_get_class_name();
5427
-        if ($base_class_obj_or_id instanceof $className) {
5428
-            /** @var $base_class_obj_or_id EE_Base_Class */
5429
-            $id = $base_class_obj_or_id->ID();
5430
-        } elseif (is_int($base_class_obj_or_id)) {
5431
-            //assume it's an ID
5432
-            $id = $base_class_obj_or_id;
5433
-        } elseif (is_string($base_class_obj_or_id)) {
5434
-            //assume its a string representation of the object
5435
-            $id = $base_class_obj_or_id;
5436
-        } else {
5437
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5438
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5439
-                print_r($base_class_obj_or_id, true)));
5440
-        }
5441
-        return $id;
5442
-    }
5443
-
5444
-
5445
-
5446
-    /**
5447
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5448
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5449
-     * been sanitized and converted into the appropriate domain.
5450
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5451
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5452
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5453
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5454
-     * $EVT = EEM_Event::instance(); $old_setting =
5455
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5456
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5457
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5458
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5459
-     *
5460
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5461
-     * @return void
5462
-     */
5463
-    public function assume_values_already_prepared_by_model_object(
5464
-        $values_already_prepared = self::not_prepared_by_model_object
5465
-    ) {
5466
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5467
-    }
5468
-
5469
-
5470
-
5471
-    /**
5472
-     * Read comments for assume_values_already_prepared_by_model_object()
5473
-     *
5474
-     * @return int
5475
-     */
5476
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5477
-    {
5478
-        return $this->_values_already_prepared_by_model_object;
5479
-    }
5480
-
5481
-
5482
-
5483
-    /**
5484
-     * Gets all the indexes on this model
5485
-     *
5486
-     * @return EE_Index[]
5487
-     */
5488
-    public function indexes()
5489
-    {
5490
-        return $this->_indexes;
5491
-    }
5492
-
5493
-
5494
-
5495
-    /**
5496
-     * Gets all the Unique Indexes on this model
5497
-     *
5498
-     * @return EE_Unique_Index[]
5499
-     */
5500
-    public function unique_indexes()
5501
-    {
5502
-        $unique_indexes = array();
5503
-        foreach ($this->_indexes as $name => $index) {
5504
-            if ($index instanceof EE_Unique_Index) {
5505
-                $unique_indexes [$name] = $index;
5506
-            }
5507
-        }
5508
-        return $unique_indexes;
5509
-    }
5510
-
5511
-
5512
-
5513
-    /**
5514
-     * Gets all the fields which, when combined, make the primary key.
5515
-     * This is usually just an array with 1 element (the primary key), but in cases
5516
-     * where there is no primary key, it's a combination of fields as defined
5517
-     * on a primary index
5518
-     *
5519
-     * @return EE_Model_Field_Base[] indexed by the field's name
5520
-     * @throws EE_Error
5521
-     */
5522
-    public function get_combined_primary_key_fields()
5523
-    {
5524
-        foreach ($this->indexes() as $index) {
5525
-            if ($index instanceof EE_Primary_Key_Index) {
5526
-                return $index->fields();
5527
-            }
5528
-        }
5529
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5530
-    }
5531
-
5532
-
5533
-
5534
-    /**
5535
-     * Used to build a primary key string (when the model has no primary key),
5536
-     * which can be used a unique string to identify this model object.
5537
-     *
5538
-     * @param array $cols_n_values keys are field names, values are their values
5539
-     * @return string
5540
-     * @throws EE_Error
5541
-     */
5542
-    public function get_index_primary_key_string($cols_n_values)
5543
-    {
5544
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5545
-            $this->get_combined_primary_key_fields());
5546
-        return http_build_query($cols_n_values_for_primary_key_index);
5547
-    }
5548
-
5549
-
5550
-
5551
-    /**
5552
-     * Gets the field values from the primary key string
5553
-     *
5554
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5555
-     * @param string $index_primary_key_string
5556
-     * @return null|array
5557
-     * @throws EE_Error
5558
-     */
5559
-    public function parse_index_primary_key_string($index_primary_key_string)
5560
-    {
5561
-        $key_fields = $this->get_combined_primary_key_fields();
5562
-        //check all of them are in the $id
5563
-        $key_vals_in_combined_pk = array();
5564
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5565
-        foreach ($key_fields as $key_field_name => $field_obj) {
5566
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5567
-                return null;
5568
-            }
5569
-        }
5570
-        return $key_vals_in_combined_pk;
5571
-    }
5572
-
5573
-
5574
-
5575
-    /**
5576
-     * verifies that an array of key-value pairs for model fields has a key
5577
-     * for each field comprising the primary key index
5578
-     *
5579
-     * @param array $key_vals
5580
-     * @return boolean
5581
-     * @throws EE_Error
5582
-     */
5583
-    public function has_all_combined_primary_key_fields($key_vals)
5584
-    {
5585
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5586
-        foreach ($keys_it_should_have as $key) {
5587
-            if (! isset($key_vals[$key])) {
5588
-                return false;
5589
-            }
5590
-        }
5591
-        return true;
5592
-    }
5593
-
5594
-
5595
-
5596
-    /**
5597
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5598
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5599
-     *
5600
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5601
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5602
-     * @throws EE_Error
5603
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5604
-     *                                                              indexed)
5605
-     */
5606
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5607
-    {
5608
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5609
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5610
-        } elseif (is_array($model_object_or_attributes_array)) {
5611
-            $attributes_array = $model_object_or_attributes_array;
5612
-        } else {
5613
-            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",
5614
-                "event_espresso"), $model_object_or_attributes_array));
5615
-        }
5616
-        //even copies obviously won't have the same ID, so remove the primary key
5617
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5618
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5619
-            unset($attributes_array[$this->primary_key_name()]);
5620
-        }
5621
-        if (isset($query_params[0])) {
5622
-            $query_params[0] = array_merge($attributes_array, $query_params);
5623
-        } else {
5624
-            $query_params[0] = $attributes_array;
5625
-        }
5626
-        return $this->get_all($query_params);
5627
-    }
5628
-
5629
-
5630
-
5631
-    /**
5632
-     * Gets the first copy we find. See get_all_copies for more details
5633
-     *
5634
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5635
-     * @param array $query_params
5636
-     * @return EE_Base_Class
5637
-     * @throws EE_Error
5638
-     */
5639
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5640
-    {
5641
-        if (! is_array($query_params)) {
5642
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5643
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5644
-                    gettype($query_params)), '4.6.0');
5645
-            $query_params = array();
5646
-        }
5647
-        $query_params['limit'] = 1;
5648
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5649
-        if (is_array($copies)) {
5650
-            return array_shift($copies);
5651
-        }
5652
-        return null;
5653
-    }
5654
-
5655
-
5656
-
5657
-    /**
5658
-     * Updates the item with the specified id. Ignores default query parameters because
5659
-     * we have specified the ID, and its assumed we KNOW what we're doing
5660
-     *
5661
-     * @param array      $fields_n_values keys are field names, values are their new values
5662
-     * @param int|string $id              the value of the primary key to update
5663
-     * @return int number of rows updated
5664
-     * @throws EE_Error
5665
-     */
5666
-    public function update_by_ID($fields_n_values, $id)
5667
-    {
5668
-        $query_params = array(
5669
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5670
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5671
-        );
5672
-        return $this->update($fields_n_values, $query_params);
5673
-    }
5674
-
5675
-
5676
-
5677
-    /**
5678
-     * Changes an operator which was supplied to the models into one usable in SQL
5679
-     *
5680
-     * @param string $operator_supplied
5681
-     * @return string an operator which can be used in SQL
5682
-     * @throws EE_Error
5683
-     */
5684
-    private function _prepare_operator_for_sql($operator_supplied)
5685
-    {
5686
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5687
-            : null;
5688
-        if ($sql_operator) {
5689
-            return $sql_operator;
5690
-        }
5691
-        throw new EE_Error(
5692
-            sprintf(
5693
-                __(
5694
-                    "The operator '%s' is not in the list of valid operators: %s",
5695
-                    "event_espresso"
5696
-                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5697
-            )
5698
-        );
5699
-    }
5700
-
5701
-
5702
-
5703
-    /**
5704
-     * Gets an array where keys are the primary keys and values are their 'names'
5705
-     * (as determined by the model object's name() function, which is often overridden)
5706
-     *
5707
-     * @param array $query_params like get_all's
5708
-     * @return string[]
5709
-     * @throws EE_Error
5710
-     */
5711
-    public function get_all_names($query_params = array())
5712
-    {
5713
-        $objs = $this->get_all($query_params);
5714
-        $names = array();
5715
-        foreach ($objs as $obj) {
5716
-            $names[$obj->ID()] = $obj->name();
5717
-        }
5718
-        return $names;
5719
-    }
5720
-
5721
-
5722
-
5723
-    /**
5724
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5725
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5726
-     * this is duplicated effort and reduces efficiency) you would be better to use
5727
-     * array_keys() on $model_objects.
5728
-     *
5729
-     * @param \EE_Base_Class[] $model_objects
5730
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5731
-     *                                               in the returned array
5732
-     * @return array
5733
-     * @throws EE_Error
5734
-     */
5735
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5736
-    {
5737
-        if (! $this->has_primary_key_field()) {
5738
-            if (WP_DEBUG) {
5739
-                EE_Error::add_error(
5740
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5741
-                    __FILE__,
5742
-                    __FUNCTION__,
5743
-                    __LINE__
5744
-                );
5745
-            }
5746
-        }
5747
-        $IDs = array();
5748
-        foreach ($model_objects as $model_object) {
5749
-            $id = $model_object->ID();
5750
-            if (! $id) {
5751
-                if ($filter_out_empty_ids) {
5752
-                    continue;
5753
-                }
5754
-                if (WP_DEBUG) {
5755
-                    EE_Error::add_error(
5756
-                        __(
5757
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5758
-                            'event_espresso'
5759
-                        ),
5760
-                        __FILE__,
5761
-                        __FUNCTION__,
5762
-                        __LINE__
5763
-                    );
5764
-                }
5765
-            }
5766
-            $IDs[] = $id;
5767
-        }
5768
-        return $IDs;
5769
-    }
5770
-
5771
-
5772
-
5773
-    /**
5774
-     * Returns the string used in capabilities relating to this model. If there
5775
-     * are no capabilities that relate to this model returns false
5776
-     *
5777
-     * @return string|false
5778
-     */
5779
-    public function cap_slug()
5780
-    {
5781
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5782
-    }
5783
-
5784
-
5785
-
5786
-    /**
5787
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5788
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5789
-     * only returns the cap restrictions array in that context (ie, the array
5790
-     * at that key)
5791
-     *
5792
-     * @param string $context
5793
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5794
-     * @throws EE_Error
5795
-     */
5796
-    public function cap_restrictions($context = EEM_Base::caps_read)
5797
-    {
5798
-        EEM_Base::verify_is_valid_cap_context($context);
5799
-        //check if we ought to run the restriction generator first
5800
-        if (
5801
-            isset($this->_cap_restriction_generators[$context])
5802
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5803
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5804
-        ) {
5805
-            $this->_cap_restrictions[$context] = array_merge(
5806
-                $this->_cap_restrictions[$context],
5807
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5808
-            );
5809
-        }
5810
-        //and make sure we've finalized the construction of each restriction
5811
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5812
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5813
-                $where_conditions_obj->_finalize_construct($this);
5814
-            }
5815
-        }
5816
-        return $this->_cap_restrictions[$context];
5817
-    }
5818
-
5819
-
5820
-
5821
-    /**
5822
-     * Indicating whether or not this model thinks its a wp core model
5823
-     *
5824
-     * @return boolean
5825
-     */
5826
-    public function is_wp_core_model()
5827
-    {
5828
-        return $this->_wp_core_model;
5829
-    }
5830
-
5831
-
5832
-
5833
-    /**
5834
-     * Gets all the caps that are missing which impose a restriction on
5835
-     * queries made in this context
5836
-     *
5837
-     * @param string $context one of EEM_Base::caps_ constants
5838
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5839
-     * @throws EE_Error
5840
-     */
5841
-    public function caps_missing($context = EEM_Base::caps_read)
5842
-    {
5843
-        $missing_caps = array();
5844
-        $cap_restrictions = $this->cap_restrictions($context);
5845
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5846
-            if (! EE_Capabilities::instance()
5847
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5848
-            ) {
5849
-                $missing_caps[$cap] = $restriction_if_no_cap;
5850
-            }
5851
-        }
5852
-        return $missing_caps;
5853
-    }
5854
-
5855
-
5856
-
5857
-    /**
5858
-     * Gets the mapping from capability contexts to action strings used in capability names
5859
-     *
5860
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5861
-     * one of 'read', 'edit', or 'delete'
5862
-     */
5863
-    public function cap_contexts_to_cap_action_map()
5864
-    {
5865
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5866
-            $this);
5867
-    }
5868
-
5869
-
5870
-
5871
-    /**
5872
-     * Gets the action string for the specified capability context
5873
-     *
5874
-     * @param string $context
5875
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5876
-     * @throws EE_Error
5877
-     */
5878
-    public function cap_action_for_context($context)
5879
-    {
5880
-        $mapping = $this->cap_contexts_to_cap_action_map();
5881
-        if (isset($mapping[$context])) {
5882
-            return $mapping[$context];
5883
-        }
5884
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5885
-            return $action;
5886
-        }
5887
-        throw new EE_Error(
5888
-            sprintf(
5889
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5890
-                $context,
5891
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5892
-            )
5893
-        );
5894
-    }
5895
-
5896
-
5897
-
5898
-    /**
5899
-     * Returns all the capability contexts which are valid when querying models
5900
-     *
5901
-     * @return array
5902
-     */
5903
-    public static function valid_cap_contexts()
5904
-    {
5905
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5906
-            self::caps_read,
5907
-            self::caps_read_admin,
5908
-            self::caps_edit,
5909
-            self::caps_delete,
5910
-        ));
5911
-    }
5912
-
5913
-
5914
-
5915
-    /**
5916
-     * Returns all valid options for 'default_where_conditions'
5917
-     *
5918
-     * @return array
5919
-     */
5920
-    public static function valid_default_where_conditions()
5921
-    {
5922
-        return array(
5923
-            EEM_Base::default_where_conditions_all,
5924
-            EEM_Base::default_where_conditions_this_only,
5925
-            EEM_Base::default_where_conditions_others_only,
5926
-            EEM_Base::default_where_conditions_minimum_all,
5927
-            EEM_Base::default_where_conditions_minimum_others,
5928
-            EEM_Base::default_where_conditions_none
5929
-        );
5930
-    }
5931
-
5932
-    // public static function default_where_conditions_full
5933
-    /**
5934
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5935
-     *
5936
-     * @param string $context
5937
-     * @return bool
5938
-     * @throws EE_Error
5939
-     */
5940
-    static public function verify_is_valid_cap_context($context)
5941
-    {
5942
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5943
-        if (in_array($context, $valid_cap_contexts)) {
5944
-            return true;
5945
-        }
5946
-        throw new EE_Error(
5947
-            sprintf(
5948
-                __(
5949
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5950
-                    'event_espresso'
5951
-                ),
5952
-                $context,
5953
-                'EEM_Base',
5954
-                implode(',', $valid_cap_contexts)
5955
-            )
5956
-        );
5957
-    }
5958
-
5959
-
5960
-
5961
-    /**
5962
-     * Clears all the models field caches. This is only useful when a sub-class
5963
-     * might have added a field or something and these caches might be invalidated
5964
-     */
5965
-    protected function _invalidate_field_caches()
5966
-    {
5967
-        $this->_cache_foreign_key_to_fields = array();
5968
-        $this->_cached_fields = null;
5969
-        $this->_cached_fields_non_db_only = null;
5970
-    }
5971
-
5972
-
5973
-
5974
-    /**
5975
-     * _instantiate_new_instance_from_db
5976
-     *
5977
-     * @param string $class_name
5978
-     * @param array  $arguments
5979
-     * @return \EE_Base_Class
5980
-     * @throws Exception
5981
-     */
5982
-    public function _instantiate_new_instance_from_db($class_name, $arguments)
5983
-    {
5984
-        if ( ! class_exists($class_name)) {
5985
-            throw new EE_Error(
5986
-                sprintf(
5987
-                    __('The "%s" class does not exist. Please ensure that an autoloader is set.', 'event_espresso'),
5988
-                    $class_name
5989
-                )
5990
-            );
5991
-        }
5992
-        return call_user_func_array(
5993
-            array($class_name, 'new_instance'),
5994
-            array((array)$arguments, $this->_timezone, array(), true)
5995
-        );
5996
-    }
5997
-
5998
-
5999
-    /**
6000
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6001
-     * (eg "and", "or", "not").
6002
-     *
6003
-     * @return array
6004
-     */
6005
-    public function logic_query_param_keys()
6006
-    {
6007
-        return $this->_logic_query_param_keys;
6008
-    }
6009
-
6010
-
6011
-
6012
-    /**
6013
-     * Determines whether or not the where query param array key is for a logic query param.
6014
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6015
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6016
-     *
6017
-     * @param $query_param_key
6018
-     * @return bool
6019
-     */
6020
-    public function is_logic_query_param_key($query_param_key)
6021
-    {
6022
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6023
-            if ($query_param_key === $logic_query_param_key
6024
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6025
-            ) {
6026
-                return true;
6027
-            }
6028
-        }
6029
-        return false;
6030
-    }
3725
+		}
3726
+		return $null_friendly_where_conditions;
3727
+	}
3728
+
3729
+
3730
+
3731
+	/**
3732
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3733
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3734
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3735
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3736
+	 *
3737
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3738
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3739
+	 */
3740
+	private function _get_default_where_conditions($model_relation_path = null)
3741
+	{
3742
+		if ($this->_ignore_where_strategy) {
3743
+			return array();
3744
+		}
3745
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3746
+	}
3747
+
3748
+
3749
+
3750
+	/**
3751
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3752
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3753
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3754
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3755
+	 * Similar to _get_default_where_conditions
3756
+	 *
3757
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3758
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3759
+	 */
3760
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3761
+	{
3762
+		if ($this->_ignore_where_strategy) {
3763
+			return array();
3764
+		}
3765
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3766
+	}
3767
+
3768
+
3769
+
3770
+	/**
3771
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3772
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3773
+	 *
3774
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3775
+	 * @return string
3776
+	 * @throws EE_Error
3777
+	 */
3778
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3779
+	{
3780
+		$selects = $this->_get_columns_to_select_for_this_model();
3781
+		foreach (
3782
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3783
+			$name_of_other_model_included
3784
+		) {
3785
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3786
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3787
+			foreach ($other_model_selects as $key => $value) {
3788
+				$selects[] = $value;
3789
+			}
3790
+		}
3791
+		return implode(", ", $selects);
3792
+	}
3793
+
3794
+
3795
+
3796
+	/**
3797
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3798
+	 * So that's going to be the columns for all the fields on the model
3799
+	 *
3800
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3801
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3802
+	 */
3803
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3804
+	{
3805
+		$fields = $this->field_settings();
3806
+		$selects = array();
3807
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3808
+			$this->get_this_model_name());
3809
+		foreach ($fields as $field_obj) {
3810
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3811
+						 . $field_obj->get_table_alias()
3812
+						 . "."
3813
+						 . $field_obj->get_table_column()
3814
+						 . " AS '"
3815
+						 . $table_alias_with_model_relation_chain_prefix
3816
+						 . $field_obj->get_table_alias()
3817
+						 . "."
3818
+						 . $field_obj->get_table_column()
3819
+						 . "'";
3820
+		}
3821
+		//make sure we are also getting the PKs of each table
3822
+		$tables = $this->get_tables();
3823
+		if (count($tables) > 1) {
3824
+			foreach ($tables as $table_obj) {
3825
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3826
+									   . $table_obj->get_fully_qualified_pk_column();
3827
+				if (! in_array($qualified_pk_column, $selects)) {
3828
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3829
+				}
3830
+			}
3831
+		}
3832
+		return $selects;
3833
+	}
3834
+
3835
+
3836
+
3837
+	/**
3838
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3839
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3840
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3841
+	 * SQL for joining, and the data types
3842
+	 *
3843
+	 * @param null|string                 $original_query_param
3844
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3845
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3846
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3847
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3848
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3849
+	 *                                                          or 'Registration's
3850
+	 * @param string                      $original_query_param what it originally was (eg
3851
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3852
+	 *                                                          matches $query_param
3853
+	 * @throws EE_Error
3854
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3855
+	 */
3856
+	private function _extract_related_model_info_from_query_param(
3857
+		$query_param,
3858
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3859
+		$query_param_type,
3860
+		$original_query_param = null
3861
+	) {
3862
+		if ($original_query_param === null) {
3863
+			$original_query_param = $query_param;
3864
+		}
3865
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3866
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3867
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3868
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3869
+		//check to see if we have a field on this model
3870
+		$this_model_fields = $this->field_settings(true);
3871
+		if (array_key_exists($query_param, $this_model_fields)) {
3872
+			if ($allow_fields) {
3873
+				return;
3874
+			}
3875
+			throw new EE_Error(
3876
+				sprintf(
3877
+					__(
3878
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3879
+						"event_espresso"
3880
+					),
3881
+					$query_param, get_class($this), $query_param_type, $original_query_param
3882
+				)
3883
+			);
3884
+		}
3885
+		//check if this is a special logic query param
3886
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3887
+			if ($allow_logic_query_params) {
3888
+				return;
3889
+			}
3890
+			throw new EE_Error(
3891
+				sprintf(
3892
+					__(
3893
+						'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',
3894
+						'event_espresso'
3895
+					),
3896
+					implode('", "', $this->_logic_query_param_keys),
3897
+					$query_param,
3898
+					get_class($this),
3899
+					'<br />',
3900
+					"\t"
3901
+					. ' $passed_in_query_info = <pre>'
3902
+					. print_r($passed_in_query_info, true)
3903
+					. '</pre>'
3904
+					. "\n\t"
3905
+					. ' $query_param_type = '
3906
+					. $query_param_type
3907
+					. "\n\t"
3908
+					. ' $original_query_param = '
3909
+					. $original_query_param
3910
+				)
3911
+			);
3912
+		}
3913
+		//check if it's a custom selection
3914
+		if (array_key_exists($query_param, $this->_custom_selections)) {
3915
+			return;
3916
+		}
3917
+		//check if has a model name at the beginning
3918
+		//and
3919
+		//check if it's a field on a related model
3920
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3921
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3922
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3923
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3924
+				if ($query_param === '') {
3925
+					//nothing left to $query_param
3926
+					//we should actually end in a field name, not a model like this!
3927
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3928
+						"event_espresso"),
3929
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3930
+				}
3931
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3932
+				$related_model_obj->_extract_related_model_info_from_query_param(
3933
+					$query_param,
3934
+					$passed_in_query_info, $query_param_type, $original_query_param
3935
+				);
3936
+				return;
3937
+			}
3938
+			if ($query_param === $valid_related_model_name) {
3939
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3940
+				return;
3941
+			}
3942
+		}
3943
+		//ok so $query_param didn't start with a model name
3944
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3945
+		//it's wack, that's what it is
3946
+		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",
3947
+			"event_espresso"),
3948
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3949
+	}
3950
+
3951
+
3952
+
3953
+	/**
3954
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3955
+	 * and store it on $passed_in_query_info
3956
+	 *
3957
+	 * @param string                      $model_name
3958
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3959
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3960
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3961
+	 *                                                          and are adding a join to 'Payment' with the original
3962
+	 *                                                          query param key
3963
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3964
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3965
+	 *                                                          Payment wants to add default query params so that it
3966
+	 *                                                          will know what models to prepend onto its default query
3967
+	 *                                                          params or in case it wants to rename tables (in case
3968
+	 *                                                          there are multiple joins to the same table)
3969
+	 * @return void
3970
+	 * @throws EE_Error
3971
+	 */
3972
+	private function _add_join_to_model(
3973
+		$model_name,
3974
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3975
+		$original_query_param
3976
+	) {
3977
+		$relation_obj = $this->related_settings_for($model_name);
3978
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3979
+		//check if the relation is HABTM, because then we're essentially doing two joins
3980
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3981
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3982
+			$join_model_obj = $relation_obj->get_join_model();
3983
+			//replace the model specified with the join model for this relation chain, whi
3984
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3985
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3986
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3987
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3988
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3989
+			$passed_in_query_info->merge($new_query_info);
3990
+		}
3991
+		//now just join to the other table pointed to by the relation object, and add its data types
3992
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3993
+			array($model_relation_chain => $model_name),
3994
+			$relation_obj->get_join_statement($model_relation_chain));
3995
+		$passed_in_query_info->merge($new_query_info);
3996
+	}
3997
+
3998
+
3999
+
4000
+	/**
4001
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4002
+	 *
4003
+	 * @param array $where_params like EEM_Base::get_all
4004
+	 * @return string of SQL
4005
+	 * @throws EE_Error
4006
+	 */
4007
+	private function _construct_where_clause($where_params)
4008
+	{
4009
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4010
+		if ($SQL) {
4011
+			return " WHERE " . $SQL;
4012
+		}
4013
+		return '';
4014
+	}
4015
+
4016
+
4017
+
4018
+	/**
4019
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4020
+	 * and should be passed HAVING parameters, not WHERE parameters
4021
+	 *
4022
+	 * @param array $having_params
4023
+	 * @return string
4024
+	 * @throws EE_Error
4025
+	 */
4026
+	private function _construct_having_clause($having_params)
4027
+	{
4028
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4029
+		if ($SQL) {
4030
+			return " HAVING " . $SQL;
4031
+		}
4032
+		return '';
4033
+	}
4034
+
4035
+
4036
+
4037
+	/**
4038
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
4039
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
4040
+	 * EEM_Attendee.
4041
+	 *
4042
+	 * @param string $field_name
4043
+	 * @param string $model_name
4044
+	 * @return EE_Model_Field_Base
4045
+	 * @throws EE_Error
4046
+	 */
4047
+	protected function _get_field_on_model($field_name, $model_name)
4048
+	{
4049
+		$model_class = 'EEM_' . $model_name;
4050
+		$model_filepath = $model_class . ".model.php";
4051
+		if (is_readable($model_filepath)) {
4052
+			require_once($model_filepath);
4053
+			$model_instance = call_user_func($model_name . "::instance");
4054
+			/* @var $model_instance EEM_Base */
4055
+			return $model_instance->field_settings_for($field_name);
4056
+		}
4057
+		throw new EE_Error(
4058
+			sprintf(
4059
+				__(
4060
+					'No model named %s exists, with classname %s and filepath %s',
4061
+					'event_espresso'
4062
+				), $model_name, $model_class, $model_filepath
4063
+			)
4064
+		);
4065
+	}
4066
+
4067
+
4068
+
4069
+	/**
4070
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4071
+	 * Event_Meta.meta_value = 'foo'))"
4072
+	 *
4073
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4074
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4075
+	 * @throws EE_Error
4076
+	 * @return string of SQL
4077
+	 */
4078
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4079
+	{
4080
+		$where_clauses = array();
4081
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4082
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4083
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4084
+				switch ($query_param) {
4085
+					case 'not':
4086
+					case 'NOT':
4087
+						$where_clauses[] = "! ("
4088
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4089
+								$glue)
4090
+										   . ")";
4091
+						break;
4092
+					case 'and':
4093
+					case 'AND':
4094
+						$where_clauses[] = " ("
4095
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4096
+								' AND ')
4097
+										   . ")";
4098
+						break;
4099
+					case 'or':
4100
+					case 'OR':
4101
+						$where_clauses[] = " ("
4102
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4103
+								' OR ')
4104
+										   . ")";
4105
+						break;
4106
+				}
4107
+			} else {
4108
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4109
+				//if it's not a normal field, maybe it's a custom selection?
4110
+				if (! $field_obj) {
4111
+					if (isset($this->_custom_selections[$query_param][1])) {
4112
+						$field_obj = $this->_custom_selections[$query_param][1];
4113
+					} else {
4114
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4115
+							"event_espresso"), $query_param));
4116
+					}
4117
+				}
4118
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4119
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4120
+			}
4121
+		}
4122
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4123
+	}
4124
+
4125
+
4126
+
4127
+	/**
4128
+	 * Takes the input parameter and extract the table name (alias) and column name
4129
+	 *
4130
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4131
+	 * @throws EE_Error
4132
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4133
+	 */
4134
+	private function _deduce_column_name_from_query_param($query_param)
4135
+	{
4136
+		$field = $this->_deduce_field_from_query_param($query_param);
4137
+		if ($field) {
4138
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4139
+				$query_param);
4140
+			return $table_alias_prefix . $field->get_qualified_column();
4141
+		}
4142
+		if (array_key_exists($query_param, $this->_custom_selections)) {
4143
+			//maybe it's custom selection item?
4144
+			//if so, just use it as the "column name"
4145
+			return $query_param;
4146
+		}
4147
+		throw new EE_Error(
4148
+			sprintf(
4149
+				__(
4150
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4151
+					"event_espresso"
4152
+				), $query_param, implode(",", $this->_custom_selections)
4153
+			)
4154
+		);
4155
+	}
4156
+
4157
+
4158
+
4159
+	/**
4160
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4161
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4162
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4163
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4164
+	 *
4165
+	 * @param string $condition_query_param_key
4166
+	 * @return string
4167
+	 */
4168
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4169
+	{
4170
+		$pos_of_star = strpos($condition_query_param_key, '*');
4171
+		if ($pos_of_star === false) {
4172
+			return $condition_query_param_key;
4173
+		}
4174
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4175
+		return $condition_query_param_sans_star;
4176
+	}
4177
+
4178
+
4179
+
4180
+	/**
4181
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4182
+	 *
4183
+	 * @param                            mixed      array | string    $op_and_value
4184
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4185
+	 * @throws EE_Error
4186
+	 * @return string
4187
+	 */
4188
+	private function _construct_op_and_value($op_and_value, $field_obj)
4189
+	{
4190
+		if (is_array($op_and_value)) {
4191
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4192
+			if (! $operator) {
4193
+				$php_array_like_string = array();
4194
+				foreach ($op_and_value as $key => $value) {
4195
+					$php_array_like_string[] = "$key=>$value";
4196
+				}
4197
+				throw new EE_Error(
4198
+					sprintf(
4199
+						__(
4200
+							"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))",
4201
+							"event_espresso"
4202
+						),
4203
+						implode(",", $php_array_like_string)
4204
+					)
4205
+				);
4206
+			}
4207
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4208
+		} else {
4209
+			$operator = '=';
4210
+			$value = $op_and_value;
4211
+		}
4212
+		//check to see if the value is actually another field
4213
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4214
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4215
+		}
4216
+		if (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4217
+			//in this case, the value should be an array, or at least a comma-separated list
4218
+			//it will need to handle a little differently
4219
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4220
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4221
+			return $operator . SP . $cleaned_value;
4222
+		}
4223
+		if (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4224
+			//the value should be an array with count of two.
4225
+			if (count($value) !== 2) {
4226
+				throw new EE_Error(
4227
+					sprintf(
4228
+						__(
4229
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4230
+							'event_espresso'
4231
+						),
4232
+						"BETWEEN"
4233
+					)
4234
+				);
4235
+			}
4236
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4237
+			return $operator . SP . $cleaned_value;
4238
+		}
4239
+		if (in_array($operator, $this->_null_style_operators)) {
4240
+			if ($value !== null) {
4241
+				throw new EE_Error(
4242
+					sprintf(
4243
+						__(
4244
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4245
+							"event_espresso"
4246
+						),
4247
+						$value,
4248
+						$operator
4249
+					)
4250
+				);
4251
+			}
4252
+			return $operator;
4253
+		}
4254
+		if ($operator === 'LIKE' && ! is_array($value)) {
4255
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4256
+			//remove other junk. So just treat it as a string.
4257
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4258
+		}
4259
+		if (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4260
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4261
+		}
4262
+		if (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4263
+			throw new EE_Error(
4264
+				sprintf(
4265
+					__(
4266
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4267
+						'event_espresso'
4268
+					),
4269
+					$operator,
4270
+					$operator
4271
+				)
4272
+			);
4273
+		}
4274
+		if (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4275
+			throw new EE_Error(
4276
+				sprintf(
4277
+					__(
4278
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4279
+						'event_espresso'
4280
+					),
4281
+					$operator,
4282
+					$operator
4283
+				)
4284
+			);
4285
+		}
4286
+		throw new EE_Error(
4287
+			sprintf(
4288
+				__(
4289
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4290
+					"event_espresso"
4291
+				),
4292
+				http_build_query($op_and_value)
4293
+			)
4294
+		);
4295
+	}
4296
+
4297
+
4298
+
4299
+	/**
4300
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4301
+	 *
4302
+	 * @param array                      $values
4303
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4304
+	 *                                              '%s'
4305
+	 * @return string
4306
+	 * @throws EE_Error
4307
+	 */
4308
+	public function _construct_between_value($values, $field_obj)
4309
+	{
4310
+		$cleaned_values = array();
4311
+		foreach ($values as $value) {
4312
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4313
+		}
4314
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4315
+	}
4316
+
4317
+
4318
+
4319
+	/**
4320
+	 * Takes an array or a comma-separated list of $values and cleans them
4321
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4322
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4323
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4324
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4325
+	 *
4326
+	 * @param mixed                      $values    array or comma-separated string
4327
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4328
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4329
+	 * @throws EE_Error
4330
+	 */
4331
+	public function _construct_in_value($values, $field_obj)
4332
+	{
4333
+		//check if the value is a CSV list
4334
+		if (is_string($values)) {
4335
+			//in which case, turn it into an array
4336
+			$values = explode(",", $values);
4337
+		}
4338
+		$cleaned_values = array();
4339
+		foreach ($values as $value) {
4340
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4341
+		}
4342
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4343
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4344
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4345
+		if (empty($cleaned_values)) {
4346
+			$all_fields = $this->field_settings();
4347
+			$a_field = array_shift($all_fields);
4348
+			$main_table = $this->_get_main_table();
4349
+			$cleaned_values[] = "SELECT "
4350
+								. $a_field->get_table_column()
4351
+								. " FROM "
4352
+								. $main_table->get_table_name()
4353
+								. " WHERE FALSE";
4354
+		}
4355
+		return "(" . implode(",", $cleaned_values) . ")";
4356
+	}
4357
+
4358
+
4359
+
4360
+	/**
4361
+	 * @param mixed                      $value
4362
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4363
+	 * @throws EE_Error
4364
+	 * @return false|null|string
4365
+	 */
4366
+	private function _wpdb_prepare_using_field($value, $field_obj)
4367
+	{
4368
+		/** @type WPDB $wpdb */
4369
+		global $wpdb;
4370
+		if ($field_obj instanceof EE_Model_Field_Base) {
4371
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4372
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4373
+		} //$field_obj should really just be a data type
4374
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4375
+			throw new EE_Error(
4376
+				sprintf(
4377
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4378
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)
4379
+				)
4380
+			);
4381
+		}
4382
+		return $wpdb->prepare($field_obj, $value);
4383
+	}
4384
+
4385
+
4386
+
4387
+	/**
4388
+	 * Takes the input parameter and finds the model field that it indicates.
4389
+	 *
4390
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4391
+	 * @throws EE_Error
4392
+	 * @return EE_Model_Field_Base
4393
+	 */
4394
+	protected function _deduce_field_from_query_param($query_param_name)
4395
+	{
4396
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4397
+		//which will help us find the database table and column
4398
+		$query_param_parts = explode(".", $query_param_name);
4399
+		if (empty($query_param_parts)) {
4400
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4401
+				'event_espresso'), $query_param_name));
4402
+		}
4403
+		$number_of_parts = count($query_param_parts);
4404
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4405
+		if ($number_of_parts === 1) {
4406
+			$field_name = $last_query_param_part;
4407
+			$model_obj = $this;
4408
+		} else {// $number_of_parts >= 2
4409
+			//the last part is the column name, and there are only 2parts. therefore...
4410
+			$field_name = $last_query_param_part;
4411
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4412
+		}
4413
+		try {
4414
+			return $model_obj->field_settings_for($field_name);
4415
+		} catch (EE_Error $e) {
4416
+			return null;
4417
+		}
4418
+	}
4419
+
4420
+
4421
+
4422
+	/**
4423
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4424
+	 * alias and column which corresponds to it
4425
+	 *
4426
+	 * @param string $field_name
4427
+	 * @throws EE_Error
4428
+	 * @return string
4429
+	 */
4430
+	public function _get_qualified_column_for_field($field_name)
4431
+	{
4432
+		$all_fields = $this->field_settings();
4433
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4434
+		if ($field) {
4435
+			return $field->get_qualified_column();
4436
+		}
4437
+		throw new EE_Error(
4438
+			sprintf(
4439
+				__(
4440
+					"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.",
4441
+					'event_espresso'
4442
+				), $field_name, get_class($this)
4443
+			)
4444
+		);
4445
+	}
4446
+
4447
+
4448
+
4449
+	/**
4450
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4451
+	 * Example usage:
4452
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4453
+	 *      array(),
4454
+	 *      ARRAY_A,
4455
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4456
+	 *  );
4457
+	 * is equivalent to
4458
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4459
+	 * and
4460
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4461
+	 *      array(
4462
+	 *          array(
4463
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4464
+	 *          ),
4465
+	 *          ARRAY_A,
4466
+	 *          implode(
4467
+	 *              ', ',
4468
+	 *              array_merge(
4469
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4470
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4471
+	 *              )
4472
+	 *          )
4473
+	 *      )
4474
+	 *  );
4475
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4476
+	 *
4477
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4478
+	 *                                            and the one whose fields you are selecting for example: when querying
4479
+	 *                                            tickets model and selecting fields from the tickets model you would
4480
+	 *                                            leave this parameter empty, because no models are needed to join
4481
+	 *                                            between the queried model and the selected one. Likewise when
4482
+	 *                                            querying the datetime model and selecting fields from the tickets
4483
+	 *                                            model, it would also be left empty, because there is a direct
4484
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4485
+	 *                                            them together. However, when querying from the event model and
4486
+	 *                                            selecting fields from the ticket model, you should provide the string
4487
+	 *                                            'Datetime', indicating that the event model must first join to the
4488
+	 *                                            datetime model in order to find its relation to ticket model.
4489
+	 *                                            Also, when querying from the venue model and selecting fields from
4490
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4491
+	 *                                            indicating you need to join the venue model to the event model,
4492
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4493
+	 *                                            This string is used to deduce the prefix that gets added onto the
4494
+	 *                                            models' tables qualified columns
4495
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4496
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4497
+	 *                                            qualified column names
4498
+	 * @return array|string
4499
+	 */
4500
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4501
+	{
4502
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4503
+		$qualified_columns = array();
4504
+		foreach ($this->field_settings() as $field_name => $field) {
4505
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4506
+		}
4507
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4508
+	}
4509
+
4510
+
4511
+
4512
+	/**
4513
+	 * constructs the select use on special limit joins
4514
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4515
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4516
+	 * (as that is typically where the limits would be set).
4517
+	 *
4518
+	 * @param  string       $table_alias The table the select is being built for
4519
+	 * @param  mixed|string $limit       The limit for this select
4520
+	 * @return string                The final select join element for the query.
4521
+	 */
4522
+	public function _construct_limit_join_select($table_alias, $limit)
4523
+	{
4524
+		$SQL = '';
4525
+		foreach ($this->_tables as $table_obj) {
4526
+			if ($table_obj instanceof EE_Primary_Table) {
4527
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4528
+					? $table_obj->get_select_join_limit($limit)
4529
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4530
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4531
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4532
+					? $table_obj->get_select_join_limit_join($limit)
4533
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4534
+			}
4535
+		}
4536
+		return $SQL;
4537
+	}
4538
+
4539
+
4540
+
4541
+	/**
4542
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4543
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4544
+	 *
4545
+	 * @return string SQL
4546
+	 * @throws EE_Error
4547
+	 */
4548
+	public function _construct_internal_join()
4549
+	{
4550
+		$SQL = $this->_get_main_table()->get_table_sql();
4551
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4552
+		return $SQL;
4553
+	}
4554
+
4555
+
4556
+
4557
+	/**
4558
+	 * Constructs the SQL for joining all the tables on this model.
4559
+	 * Normally $alias should be the primary table's alias, but in cases where
4560
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4561
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4562
+	 * alias, this will construct SQL like:
4563
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4564
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4565
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4566
+	 *
4567
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4568
+	 * @return string
4569
+	 */
4570
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4571
+	{
4572
+		$SQL = '';
4573
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4574
+		foreach ($this->_tables as $table_obj) {
4575
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4576
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4577
+					//so we're joining to this table, meaning the table is already in
4578
+					//the FROM statement, BUT the primary table isn't. So we want
4579
+					//to add the inverse join sql
4580
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4581
+				} else {
4582
+					//just add a regular JOIN to this table from the primary table
4583
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4584
+				}
4585
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4586
+		}
4587
+		return $SQL;
4588
+	}
4589
+
4590
+
4591
+
4592
+	/**
4593
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4594
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4595
+	 * their data type (eg, '%s', '%d', etc)
4596
+	 *
4597
+	 * @return array
4598
+	 */
4599
+	public function _get_data_types()
4600
+	{
4601
+		$data_types = array();
4602
+		foreach ($this->field_settings() as $field_obj) {
4603
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4604
+			/** @var $field_obj EE_Model_Field_Base */
4605
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4606
+		}
4607
+		return $data_types;
4608
+	}
4609
+
4610
+
4611
+
4612
+	/**
4613
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4614
+	 *
4615
+	 * @param string $model_name
4616
+	 * @throws EE_Error
4617
+	 * @return EEM_Base
4618
+	 */
4619
+	public function get_related_model_obj($model_name)
4620
+	{
4621
+		$model_classname = "EEM_" . $model_name;
4622
+		if (! class_exists($model_classname)) {
4623
+			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",
4624
+				'event_espresso'), $model_name, $model_classname));
4625
+		}
4626
+		return call_user_func($model_classname . "::instance");
4627
+	}
4628
+
4629
+
4630
+
4631
+	/**
4632
+	 * Returns the array of EE_ModelRelations for this model.
4633
+	 *
4634
+	 * @return EE_Model_Relation_Base[]
4635
+	 */
4636
+	public function relation_settings()
4637
+	{
4638
+		return $this->_model_relations;
4639
+	}
4640
+
4641
+
4642
+
4643
+	/**
4644
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4645
+	 * because without THOSE models, this model probably doesn't have much purpose.
4646
+	 * (Eg, without an event, datetimes have little purpose.)
4647
+	 *
4648
+	 * @return EE_Belongs_To_Relation[]
4649
+	 */
4650
+	public function belongs_to_relations()
4651
+	{
4652
+		$belongs_to_relations = array();
4653
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4654
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4655
+				$belongs_to_relations[$model_name] = $relation_obj;
4656
+			}
4657
+		}
4658
+		return $belongs_to_relations;
4659
+	}
4660
+
4661
+
4662
+
4663
+	/**
4664
+	 * Returns the specified EE_Model_Relation, or throws an exception
4665
+	 *
4666
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4667
+	 * @throws EE_Error
4668
+	 * @return EE_Model_Relation_Base
4669
+	 */
4670
+	public function related_settings_for($relation_name)
4671
+	{
4672
+		$relatedModels = $this->relation_settings();
4673
+		if (! array_key_exists($relation_name, $relatedModels)) {
4674
+			throw new EE_Error(
4675
+				sprintf(
4676
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4677
+						'event_espresso'),
4678
+					$relation_name,
4679
+					$this->_get_class_name(),
4680
+					implode(', ', array_keys($relatedModels))
4681
+				)
4682
+			);
4683
+		}
4684
+		return $relatedModels[$relation_name];
4685
+	}
4686
+
4687
+
4688
+
4689
+	/**
4690
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4691
+	 * fields
4692
+	 *
4693
+	 * @param string $fieldName
4694
+	 * @throws EE_Error
4695
+	 * @return EE_Model_Field_Base
4696
+	 */
4697
+	public function field_settings_for($fieldName)
4698
+	{
4699
+		$fieldSettings = $this->field_settings(true);
4700
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4701
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4702
+				get_class($this)));
4703
+		}
4704
+		return $fieldSettings[$fieldName];
4705
+	}
4706
+
4707
+
4708
+
4709
+	/**
4710
+	 * Checks if this field exists on this model
4711
+	 *
4712
+	 * @param string $fieldName a key in the model's _field_settings array
4713
+	 * @return boolean
4714
+	 */
4715
+	public function has_field($fieldName)
4716
+	{
4717
+		$fieldSettings = $this->field_settings(true);
4718
+		if (isset($fieldSettings[$fieldName])) {
4719
+			return true;
4720
+		}
4721
+		return false;
4722
+	}
4723
+
4724
+
4725
+
4726
+	/**
4727
+	 * Returns whether or not this model has a relation to the specified model
4728
+	 *
4729
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4730
+	 * @return boolean
4731
+	 */
4732
+	public function has_relation($relation_name)
4733
+	{
4734
+		$relations = $this->relation_settings();
4735
+		if (isset($relations[$relation_name])) {
4736
+			return true;
4737
+		}
4738
+		return false;
4739
+	}
4740
+
4741
+
4742
+
4743
+	/**
4744
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4745
+	 * Eg, on EE_Answer that would be ANS_ID field object
4746
+	 *
4747
+	 * @param $field_obj
4748
+	 * @return boolean
4749
+	 */
4750
+	public function is_primary_key_field($field_obj)
4751
+	{
4752
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4753
+	}
4754
+
4755
+
4756
+
4757
+	/**
4758
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4759
+	 * Eg, on EE_Answer that would be ANS_ID field object
4760
+	 *
4761
+	 * @return EE_Model_Field_Base
4762
+	 * @throws EE_Error
4763
+	 */
4764
+	public function get_primary_key_field()
4765
+	{
4766
+		if ($this->_primary_key_field === null) {
4767
+			foreach ($this->field_settings(true) as $field_obj) {
4768
+				if ($this->is_primary_key_field($field_obj)) {
4769
+					$this->_primary_key_field = $field_obj;
4770
+					break;
4771
+				}
4772
+			}
4773
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4774
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4775
+					get_class($this)));
4776
+			}
4777
+		}
4778
+		return $this->_primary_key_field;
4779
+	}
4780
+
4781
+
4782
+
4783
+	/**
4784
+	 * Returns whether or not not there is a primary key on this model.
4785
+	 * Internally does some caching.
4786
+	 *
4787
+	 * @return boolean
4788
+	 */
4789
+	public function has_primary_key_field()
4790
+	{
4791
+		if ($this->_has_primary_key_field === null) {
4792
+			try {
4793
+				$this->get_primary_key_field();
4794
+				$this->_has_primary_key_field = true;
4795
+			} catch (EE_Error $e) {
4796
+				$this->_has_primary_key_field = false;
4797
+			}
4798
+		}
4799
+		return $this->_has_primary_key_field;
4800
+	}
4801
+
4802
+
4803
+
4804
+	/**
4805
+	 * Finds the first field of type $field_class_name.
4806
+	 *
4807
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4808
+	 *                                 EE_Foreign_Key_Field, etc
4809
+	 * @return EE_Model_Field_Base or null if none is found
4810
+	 */
4811
+	public function get_a_field_of_type($field_class_name)
4812
+	{
4813
+		foreach ($this->field_settings() as $field) {
4814
+			if ($field instanceof $field_class_name) {
4815
+				return $field;
4816
+			}
4817
+		}
4818
+		return null;
4819
+	}
4820
+
4821
+
4822
+
4823
+	/**
4824
+	 * Gets a foreign key field pointing to model.
4825
+	 *
4826
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4827
+	 * @return EE_Foreign_Key_Field_Base
4828
+	 * @throws EE_Error
4829
+	 */
4830
+	public function get_foreign_key_to($model_name)
4831
+	{
4832
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4833
+			foreach ($this->field_settings() as $field) {
4834
+				if (
4835
+					$field instanceof EE_Foreign_Key_Field_Base
4836
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4837
+				) {
4838
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4839
+					break;
4840
+				}
4841
+			}
4842
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4843
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4844
+					'event_espresso'), $model_name, get_class($this)));
4845
+			}
4846
+		}
4847
+		return $this->_cache_foreign_key_to_fields[$model_name];
4848
+	}
4849
+
4850
+
4851
+
4852
+	/**
4853
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4854
+	 *
4855
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4856
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4857
+	 *                            Either one works
4858
+	 * @return string
4859
+	 */
4860
+	public function get_table_for_alias($table_alias)
4861
+	{
4862
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4863
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4864
+	}
4865
+
4866
+
4867
+
4868
+	/**
4869
+	 * Returns a flat array of all field son this model, instead of organizing them
4870
+	 * by table_alias as they are in the constructor.
4871
+	 *
4872
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4873
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4874
+	 */
4875
+	public function field_settings($include_db_only_fields = false)
4876
+	{
4877
+		if ($include_db_only_fields) {
4878
+			if ($this->_cached_fields === null) {
4879
+				$this->_cached_fields = array();
4880
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4881
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4882
+						$this->_cached_fields[$field_name] = $field_obj;
4883
+					}
4884
+				}
4885
+			}
4886
+			return $this->_cached_fields;
4887
+		}
4888
+		if ($this->_cached_fields_non_db_only === null) {
4889
+			$this->_cached_fields_non_db_only = array();
4890
+			foreach ($this->_fields as $fields_corresponding_to_table) {
4891
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4892
+					/** @var $field_obj EE_Model_Field_Base */
4893
+					if (! $field_obj->is_db_only_field()) {
4894
+						$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4895
+					}
4896
+				}
4897
+			}
4898
+		}
4899
+		return $this->_cached_fields_non_db_only;
4900
+	}
4901
+
4902
+
4903
+
4904
+	/**
4905
+	 *        cycle though array of attendees and create objects out of each item
4906
+	 *
4907
+	 * @access        private
4908
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4909
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4910
+	 *                           numerically indexed)
4911
+	 * @throws EE_Error
4912
+	 */
4913
+	protected function _create_objects($rows = array())
4914
+	{
4915
+		$array_of_objects = array();
4916
+		if (empty($rows)) {
4917
+			return array();
4918
+		}
4919
+		$count_if_model_has_no_primary_key = 0;
4920
+		$has_primary_key = $this->has_primary_key_field();
4921
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4922
+		foreach ((array)$rows as $row) {
4923
+			if (empty($row)) {
4924
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4925
+				return array();
4926
+			}
4927
+			//check if we've already set this object in the results array,
4928
+			//in which case there's no need to process it further (again)
4929
+			if ($has_primary_key) {
4930
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4931
+					$row,
4932
+					$primary_key_field->get_qualified_column(),
4933
+					$primary_key_field->get_table_column()
4934
+				);
4935
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4936
+					continue;
4937
+				}
4938
+			}
4939
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4940
+			if (! $classInstance) {
4941
+				throw new EE_Error(
4942
+					sprintf(
4943
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4944
+						$this->get_this_model_name(),
4945
+						http_build_query($row)
4946
+					)
4947
+				);
4948
+			}
4949
+			//set the timezone on the instantiated objects
4950
+			$classInstance->set_timezone($this->_timezone);
4951
+			//make sure if there is any timezone setting present that we set the timezone for the object
4952
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4953
+			$array_of_objects[$key] = $classInstance;
4954
+			//also, for all the relations of type BelongsTo, see if we can cache
4955
+			//those related models
4956
+			//(we could do this for other relations too, but if there are conditions
4957
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4958
+			//so it requires a little more thought than just caching them immediately...)
4959
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4960
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4961
+					//check if this model's INFO is present. If so, cache it on the model
4962
+					$other_model = $relation_obj->get_other_model();
4963
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4964
+					//if we managed to make a model object from the results, cache it on the main model object
4965
+					if ($other_model_obj_maybe) {
4966
+						//set timezone on these other model objects if they are present
4967
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4968
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4969
+					}
4970
+				}
4971
+			}
4972
+		}
4973
+		return $array_of_objects;
4974
+	}
4975
+
4976
+
4977
+
4978
+	/**
4979
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4980
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4981
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4982
+	 * object (as set in the model_field!).
4983
+	 *
4984
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4985
+	 * @throws Exception
4986
+	 */
4987
+	public function create_default_object()
4988
+	{
4989
+		$this_model_fields_and_values = array();
4990
+		//setup the row using default values;
4991
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4992
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4993
+		}
4994
+		$classInstance = $this->_instantiate_new_instance_from_db(
4995
+			$this->_get_class_name(),
4996
+			$this_model_fields_and_values
4997
+		);
4998
+		return $classInstance;
4999
+	}
5000
+
5001
+
5002
+
5003
+	/**
5004
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5005
+	 *                             or an stdClass where each property is the name of a column,
5006
+	 * @return EE_Base_Class
5007
+	 * @throws Exception
5008
+	 * @throws EE_Error
5009
+	 */
5010
+	public function instantiate_class_from_array_or_object($cols_n_values)
5011
+	{
5012
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5013
+			$cols_n_values = get_object_vars($cols_n_values);
5014
+		}
5015
+		$primary_key = null;
5016
+		//make sure the array only has keys that are fields/columns on this model
5017
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5018
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5019
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5020
+		}
5021
+		//check we actually found results that we can use to build our model object
5022
+		//if not, return null
5023
+		if ($this->has_primary_key_field()) {
5024
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5025
+				return null;
5026
+			}
5027
+		} else if ($this->unique_indexes()) {
5028
+			$first_column = reset($this_model_fields_n_values);
5029
+			if (empty($first_column)) {
5030
+				return null;
5031
+			}
5032
+		}
5033
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5034
+		if ($primary_key) {
5035
+			$classInstance = $this->get_from_entity_map($primary_key);
5036
+			if (! $classInstance) {
5037
+				$classInstance = $this->_instantiate_new_instance_from_db(
5038
+					$this->_get_class_name(),
5039
+					$this_model_fields_n_values
5040
+				);
5041
+				// add this new object to the entity map
5042
+				$classInstance = $this->add_to_entity_map($classInstance);
5043
+			}
5044
+		} else {
5045
+			$classInstance = $this->_instantiate_new_instance_from_db(
5046
+				$this->_get_class_name(),
5047
+				$this_model_fields_n_values
5048
+			);
5049
+		}
5050
+		// it is entirely possible that the instantiated class object has a set
5051
+		// timezone_string db field and has set it's internal _timezone property accordingly
5052
+		// (see new_instance_from_db in model objects particularly EE_Event for example).
5053
+		// In this case, we want to make sure the model object doesn't have its timezone string
5054
+		// overwritten by any timezone property currently set here on the model so,
5055
+		// we intentionally override the model _timezone property with the model_object timezone property.
5056
+		$this->set_timezone($classInstance->get_timezone());
5057
+		return $classInstance;
5058
+	}
5059
+
5060
+
5061
+
5062
+	/**
5063
+	 * Gets the model object from the  entity map if it exists
5064
+	 *
5065
+	 * @param int|string $id the ID of the model object
5066
+	 * @return EE_Base_Class
5067
+	 */
5068
+	public function get_from_entity_map($id)
5069
+	{
5070
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5071
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5072
+	}
5073
+
5074
+
5075
+
5076
+	/**
5077
+	 * add_to_entity_map
5078
+	 * Adds the object to the model's entity mappings
5079
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5080
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5081
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5082
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5083
+	 *        then this method should be called immediately after the update query
5084
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5085
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5086
+	 *
5087
+	 * @param    EE_Base_Class $object
5088
+	 * @throws EE_Error
5089
+	 * @return \EE_Base_Class
5090
+	 */
5091
+	public function add_to_entity_map(EE_Base_Class $object)
5092
+	{
5093
+		$className = $this->_get_class_name();
5094
+		if (! $object instanceof $className) {
5095
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5096
+				is_object($object) ? get_class($object) : $object, $className));
5097
+		}
5098
+		/** @var $object EE_Base_Class */
5099
+		if (! $object->ID()) {
5100
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5101
+				"event_espresso"), get_class($this)));
5102
+		}
5103
+		// double check it's not already there
5104
+		$classInstance = $this->get_from_entity_map($object->ID());
5105
+		if ($classInstance) {
5106
+			return $classInstance;
5107
+		}
5108
+		$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5109
+		return $object;
5110
+	}
5111
+
5112
+
5113
+
5114
+	/**
5115
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5116
+	 * if no identifier is provided, then the entire entity map is emptied
5117
+	 *
5118
+	 * @param int|string $id the ID of the model object
5119
+	 * @return boolean
5120
+	 */
5121
+	public function clear_entity_map($id = null)
5122
+	{
5123
+		if (empty($id)) {
5124
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5125
+			return true;
5126
+		}
5127
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5128
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5129
+			return true;
5130
+		}
5131
+		return false;
5132
+	}
5133
+
5134
+
5135
+
5136
+	/**
5137
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5138
+	 * Given an array where keys are column (or column alias) names and values,
5139
+	 * returns an array of their corresponding field names and database values
5140
+	 *
5141
+	 * @param array $cols_n_values
5142
+	 * @return array
5143
+	 */
5144
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5145
+	{
5146
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5147
+	}
5148
+
5149
+
5150
+
5151
+	/**
5152
+	 * _deduce_fields_n_values_from_cols_n_values
5153
+	 * Given an array where keys are column (or column alias) names and values,
5154
+	 * returns an array of their corresponding field names and database values
5155
+	 *
5156
+	 * @param string $cols_n_values
5157
+	 * @return array
5158
+	 */
5159
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5160
+	{
5161
+		$this_model_fields_n_values = array();
5162
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5163
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5164
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5165
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5166
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5167
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5168
+					if (! $field_obj->is_db_only_field()) {
5169
+						//prepare field as if its coming from db
5170
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5171
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5172
+					}
5173
+				}
5174
+			} else {
5175
+				//the table's rows existed. Use their values
5176
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5177
+					if (! $field_obj->is_db_only_field()) {
5178
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5179
+							$cols_n_values, $field_obj->get_qualified_column(),
5180
+							$field_obj->get_table_column()
5181
+						);
5182
+					}
5183
+				}
5184
+			}
5185
+		}
5186
+		return $this_model_fields_n_values;
5187
+	}
5188
+
5189
+
5190
+
5191
+	/**
5192
+	 * @param $cols_n_values
5193
+	 * @param $qualified_column
5194
+	 * @param $regular_column
5195
+	 * @return null
5196
+	 */
5197
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5198
+	{
5199
+		$value = null;
5200
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5201
+		//does the field on the model relate to this column retrieved from the db?
5202
+		//or is it a db-only field? (not relating to the model)
5203
+		if (isset($cols_n_values[$qualified_column])) {
5204
+			$value = $cols_n_values[$qualified_column];
5205
+		} elseif (isset($cols_n_values[$regular_column])) {
5206
+			$value = $cols_n_values[$regular_column];
5207
+		}
5208
+		return $value;
5209
+	}
5210
+
5211
+
5212
+
5213
+	/**
5214
+	 * refresh_entity_map_from_db
5215
+	 * Makes sure the model object in the entity map at $id assumes the values
5216
+	 * of the database (opposite of EE_base_Class::save())
5217
+	 *
5218
+	 * @param int|string $id
5219
+	 * @return EE_Base_Class
5220
+	 * @throws EE_Error
5221
+	 */
5222
+	public function refresh_entity_map_from_db($id)
5223
+	{
5224
+		$obj_in_map = $this->get_from_entity_map($id);
5225
+		if ($obj_in_map) {
5226
+			$wpdb_results = $this->_get_all_wpdb_results(
5227
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5228
+			);
5229
+			if ($wpdb_results && is_array($wpdb_results)) {
5230
+				$one_row = reset($wpdb_results);
5231
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5232
+					$obj_in_map->set_from_db($field_name, $db_value);
5233
+				}
5234
+				//clear the cache of related model objects
5235
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5236
+					$obj_in_map->clear_cache($relation_name, null, true);
5237
+				}
5238
+			}
5239
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5240
+			return $obj_in_map;
5241
+		}
5242
+		return $this->get_one_by_ID($id);
5243
+	}
5244
+
5245
+
5246
+
5247
+	/**
5248
+	 * refresh_entity_map_with
5249
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5250
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5251
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5252
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5253
+	 *
5254
+	 * @param int|string    $id
5255
+	 * @param EE_Base_Class $replacing_model_obj
5256
+	 * @return \EE_Base_Class
5257
+	 * @throws EE_Error
5258
+	 */
5259
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5260
+	{
5261
+		$obj_in_map = $this->get_from_entity_map($id);
5262
+		if ($obj_in_map) {
5263
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5264
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5265
+					$obj_in_map->set($field_name, $value);
5266
+				}
5267
+				//make the model object in the entity map's cache match the $replacing_model_obj
5268
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5269
+					$obj_in_map->clear_cache($relation_name, null, true);
5270
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5271
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5272
+					}
5273
+				}
5274
+			}
5275
+			return $obj_in_map;
5276
+		}
5277
+		$this->add_to_entity_map($replacing_model_obj);
5278
+		return $replacing_model_obj;
5279
+	}
5280
+
5281
+
5282
+
5283
+	/**
5284
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5285
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5286
+	 * require_once($this->_getClassName().".class.php");
5287
+	 *
5288
+	 * @return string
5289
+	 */
5290
+	private function _get_class_name()
5291
+	{
5292
+		return "EE_" . $this->get_this_model_name();
5293
+	}
5294
+
5295
+
5296
+
5297
+	/**
5298
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5299
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5300
+	 * it would be 'Events'.
5301
+	 *
5302
+	 * @param int $quantity
5303
+	 * @return string
5304
+	 */
5305
+	public function item_name($quantity = 1)
5306
+	{
5307
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5308
+	}
5309
+
5310
+
5311
+
5312
+	/**
5313
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5314
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5315
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5316
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5317
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5318
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5319
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5320
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5321
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5322
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5323
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5324
+	 *        return $previousReturnValue.$returnString;
5325
+	 * }
5326
+	 * require('EEM_Answer.model.php');
5327
+	 * $answer=EEM_Answer::instance();
5328
+	 * echo $answer->my_callback('monkeys',100);
5329
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5330
+	 *
5331
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5332
+	 * @param array  $args       array of original arguments passed to the function
5333
+	 * @throws EE_Error
5334
+	 * @return mixed whatever the plugin which calls add_filter decides
5335
+	 */
5336
+	public function __call($methodName, $args)
5337
+	{
5338
+		$className = get_class($this);
5339
+		$tagName = "FHEE__{$className}__{$methodName}";
5340
+		if (! has_filter($tagName)) {
5341
+			throw new EE_Error(
5342
+				sprintf(
5343
+					__('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 );',
5344
+						'event_espresso'),
5345
+					$methodName,
5346
+					$className,
5347
+					$tagName,
5348
+					'<br />'
5349
+				)
5350
+			);
5351
+		}
5352
+		return apply_filters($tagName, null, $this, $args);
5353
+	}
5354
+
5355
+
5356
+
5357
+	/**
5358
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5359
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5360
+	 *
5361
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5362
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5363
+	 *                                                       the object's class name
5364
+	 *                                                       or object's ID
5365
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5366
+	 *                                                       exists in the database. If it does not, we add it
5367
+	 * @throws EE_Error
5368
+	 * @return EE_Base_Class
5369
+	 */
5370
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5371
+	{
5372
+		$className = $this->_get_class_name();
5373
+		if ($base_class_obj_or_id instanceof $className) {
5374
+			$model_object = $base_class_obj_or_id;
5375
+		} else {
5376
+			$primary_key_field = $this->get_primary_key_field();
5377
+			if (
5378
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5379
+				&& (
5380
+					is_int($base_class_obj_or_id)
5381
+					|| is_string($base_class_obj_or_id)
5382
+				)
5383
+			) {
5384
+				// assume it's an ID.
5385
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5386
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5387
+			} else if (
5388
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5389
+				&& is_string($base_class_obj_or_id)
5390
+			) {
5391
+				// assume its a string representation of the object
5392
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5393
+			} else {
5394
+				throw new EE_Error(
5395
+					sprintf(
5396
+						__(
5397
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5398
+							'event_espresso'
5399
+						),
5400
+						$base_class_obj_or_id,
5401
+						$this->_get_class_name(),
5402
+						print_r($base_class_obj_or_id, true)
5403
+					)
5404
+				);
5405
+			}
5406
+		}
5407
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5408
+			$model_object->save();
5409
+		}
5410
+		return $model_object;
5411
+	}
5412
+
5413
+
5414
+
5415
+	/**
5416
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5417
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5418
+	 * returns it ID.
5419
+	 *
5420
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5421
+	 * @return int|string depending on the type of this model object's ID
5422
+	 * @throws EE_Error
5423
+	 */
5424
+	public function ensure_is_ID($base_class_obj_or_id)
5425
+	{
5426
+		$className = $this->_get_class_name();
5427
+		if ($base_class_obj_or_id instanceof $className) {
5428
+			/** @var $base_class_obj_or_id EE_Base_Class */
5429
+			$id = $base_class_obj_or_id->ID();
5430
+		} elseif (is_int($base_class_obj_or_id)) {
5431
+			//assume it's an ID
5432
+			$id = $base_class_obj_or_id;
5433
+		} elseif (is_string($base_class_obj_or_id)) {
5434
+			//assume its a string representation of the object
5435
+			$id = $base_class_obj_or_id;
5436
+		} else {
5437
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5438
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5439
+				print_r($base_class_obj_or_id, true)));
5440
+		}
5441
+		return $id;
5442
+	}
5443
+
5444
+
5445
+
5446
+	/**
5447
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5448
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5449
+	 * been sanitized and converted into the appropriate domain.
5450
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5451
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5452
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5453
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5454
+	 * $EVT = EEM_Event::instance(); $old_setting =
5455
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5456
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5457
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5458
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5459
+	 *
5460
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5461
+	 * @return void
5462
+	 */
5463
+	public function assume_values_already_prepared_by_model_object(
5464
+		$values_already_prepared = self::not_prepared_by_model_object
5465
+	) {
5466
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5467
+	}
5468
+
5469
+
5470
+
5471
+	/**
5472
+	 * Read comments for assume_values_already_prepared_by_model_object()
5473
+	 *
5474
+	 * @return int
5475
+	 */
5476
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5477
+	{
5478
+		return $this->_values_already_prepared_by_model_object;
5479
+	}
5480
+
5481
+
5482
+
5483
+	/**
5484
+	 * Gets all the indexes on this model
5485
+	 *
5486
+	 * @return EE_Index[]
5487
+	 */
5488
+	public function indexes()
5489
+	{
5490
+		return $this->_indexes;
5491
+	}
5492
+
5493
+
5494
+
5495
+	/**
5496
+	 * Gets all the Unique Indexes on this model
5497
+	 *
5498
+	 * @return EE_Unique_Index[]
5499
+	 */
5500
+	public function unique_indexes()
5501
+	{
5502
+		$unique_indexes = array();
5503
+		foreach ($this->_indexes as $name => $index) {
5504
+			if ($index instanceof EE_Unique_Index) {
5505
+				$unique_indexes [$name] = $index;
5506
+			}
5507
+		}
5508
+		return $unique_indexes;
5509
+	}
5510
+
5511
+
5512
+
5513
+	/**
5514
+	 * Gets all the fields which, when combined, make the primary key.
5515
+	 * This is usually just an array with 1 element (the primary key), but in cases
5516
+	 * where there is no primary key, it's a combination of fields as defined
5517
+	 * on a primary index
5518
+	 *
5519
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5520
+	 * @throws EE_Error
5521
+	 */
5522
+	public function get_combined_primary_key_fields()
5523
+	{
5524
+		foreach ($this->indexes() as $index) {
5525
+			if ($index instanceof EE_Primary_Key_Index) {
5526
+				return $index->fields();
5527
+			}
5528
+		}
5529
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5530
+	}
5531
+
5532
+
5533
+
5534
+	/**
5535
+	 * Used to build a primary key string (when the model has no primary key),
5536
+	 * which can be used a unique string to identify this model object.
5537
+	 *
5538
+	 * @param array $cols_n_values keys are field names, values are their values
5539
+	 * @return string
5540
+	 * @throws EE_Error
5541
+	 */
5542
+	public function get_index_primary_key_string($cols_n_values)
5543
+	{
5544
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5545
+			$this->get_combined_primary_key_fields());
5546
+		return http_build_query($cols_n_values_for_primary_key_index);
5547
+	}
5548
+
5549
+
5550
+
5551
+	/**
5552
+	 * Gets the field values from the primary key string
5553
+	 *
5554
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5555
+	 * @param string $index_primary_key_string
5556
+	 * @return null|array
5557
+	 * @throws EE_Error
5558
+	 */
5559
+	public function parse_index_primary_key_string($index_primary_key_string)
5560
+	{
5561
+		$key_fields = $this->get_combined_primary_key_fields();
5562
+		//check all of them are in the $id
5563
+		$key_vals_in_combined_pk = array();
5564
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5565
+		foreach ($key_fields as $key_field_name => $field_obj) {
5566
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5567
+				return null;
5568
+			}
5569
+		}
5570
+		return $key_vals_in_combined_pk;
5571
+	}
5572
+
5573
+
5574
+
5575
+	/**
5576
+	 * verifies that an array of key-value pairs for model fields has a key
5577
+	 * for each field comprising the primary key index
5578
+	 *
5579
+	 * @param array $key_vals
5580
+	 * @return boolean
5581
+	 * @throws EE_Error
5582
+	 */
5583
+	public function has_all_combined_primary_key_fields($key_vals)
5584
+	{
5585
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5586
+		foreach ($keys_it_should_have as $key) {
5587
+			if (! isset($key_vals[$key])) {
5588
+				return false;
5589
+			}
5590
+		}
5591
+		return true;
5592
+	}
5593
+
5594
+
5595
+
5596
+	/**
5597
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5598
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5599
+	 *
5600
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5601
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5602
+	 * @throws EE_Error
5603
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5604
+	 *                                                              indexed)
5605
+	 */
5606
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5607
+	{
5608
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5609
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5610
+		} elseif (is_array($model_object_or_attributes_array)) {
5611
+			$attributes_array = $model_object_or_attributes_array;
5612
+		} else {
5613
+			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",
5614
+				"event_espresso"), $model_object_or_attributes_array));
5615
+		}
5616
+		//even copies obviously won't have the same ID, so remove the primary key
5617
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5618
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5619
+			unset($attributes_array[$this->primary_key_name()]);
5620
+		}
5621
+		if (isset($query_params[0])) {
5622
+			$query_params[0] = array_merge($attributes_array, $query_params);
5623
+		} else {
5624
+			$query_params[0] = $attributes_array;
5625
+		}
5626
+		return $this->get_all($query_params);
5627
+	}
5628
+
5629
+
5630
+
5631
+	/**
5632
+	 * Gets the first copy we find. See get_all_copies for more details
5633
+	 *
5634
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5635
+	 * @param array $query_params
5636
+	 * @return EE_Base_Class
5637
+	 * @throws EE_Error
5638
+	 */
5639
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5640
+	{
5641
+		if (! is_array($query_params)) {
5642
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5643
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5644
+					gettype($query_params)), '4.6.0');
5645
+			$query_params = array();
5646
+		}
5647
+		$query_params['limit'] = 1;
5648
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5649
+		if (is_array($copies)) {
5650
+			return array_shift($copies);
5651
+		}
5652
+		return null;
5653
+	}
5654
+
5655
+
5656
+
5657
+	/**
5658
+	 * Updates the item with the specified id. Ignores default query parameters because
5659
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5660
+	 *
5661
+	 * @param array      $fields_n_values keys are field names, values are their new values
5662
+	 * @param int|string $id              the value of the primary key to update
5663
+	 * @return int number of rows updated
5664
+	 * @throws EE_Error
5665
+	 */
5666
+	public function update_by_ID($fields_n_values, $id)
5667
+	{
5668
+		$query_params = array(
5669
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5670
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5671
+		);
5672
+		return $this->update($fields_n_values, $query_params);
5673
+	}
5674
+
5675
+
5676
+
5677
+	/**
5678
+	 * Changes an operator which was supplied to the models into one usable in SQL
5679
+	 *
5680
+	 * @param string $operator_supplied
5681
+	 * @return string an operator which can be used in SQL
5682
+	 * @throws EE_Error
5683
+	 */
5684
+	private function _prepare_operator_for_sql($operator_supplied)
5685
+	{
5686
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5687
+			: null;
5688
+		if ($sql_operator) {
5689
+			return $sql_operator;
5690
+		}
5691
+		throw new EE_Error(
5692
+			sprintf(
5693
+				__(
5694
+					"The operator '%s' is not in the list of valid operators: %s",
5695
+					"event_espresso"
5696
+				), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5697
+			)
5698
+		);
5699
+	}
5700
+
5701
+
5702
+
5703
+	/**
5704
+	 * Gets an array where keys are the primary keys and values are their 'names'
5705
+	 * (as determined by the model object's name() function, which is often overridden)
5706
+	 *
5707
+	 * @param array $query_params like get_all's
5708
+	 * @return string[]
5709
+	 * @throws EE_Error
5710
+	 */
5711
+	public function get_all_names($query_params = array())
5712
+	{
5713
+		$objs = $this->get_all($query_params);
5714
+		$names = array();
5715
+		foreach ($objs as $obj) {
5716
+			$names[$obj->ID()] = $obj->name();
5717
+		}
5718
+		return $names;
5719
+	}
5720
+
5721
+
5722
+
5723
+	/**
5724
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5725
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5726
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5727
+	 * array_keys() on $model_objects.
5728
+	 *
5729
+	 * @param \EE_Base_Class[] $model_objects
5730
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5731
+	 *                                               in the returned array
5732
+	 * @return array
5733
+	 * @throws EE_Error
5734
+	 */
5735
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5736
+	{
5737
+		if (! $this->has_primary_key_field()) {
5738
+			if (WP_DEBUG) {
5739
+				EE_Error::add_error(
5740
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5741
+					__FILE__,
5742
+					__FUNCTION__,
5743
+					__LINE__
5744
+				);
5745
+			}
5746
+		}
5747
+		$IDs = array();
5748
+		foreach ($model_objects as $model_object) {
5749
+			$id = $model_object->ID();
5750
+			if (! $id) {
5751
+				if ($filter_out_empty_ids) {
5752
+					continue;
5753
+				}
5754
+				if (WP_DEBUG) {
5755
+					EE_Error::add_error(
5756
+						__(
5757
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5758
+							'event_espresso'
5759
+						),
5760
+						__FILE__,
5761
+						__FUNCTION__,
5762
+						__LINE__
5763
+					);
5764
+				}
5765
+			}
5766
+			$IDs[] = $id;
5767
+		}
5768
+		return $IDs;
5769
+	}
5770
+
5771
+
5772
+
5773
+	/**
5774
+	 * Returns the string used in capabilities relating to this model. If there
5775
+	 * are no capabilities that relate to this model returns false
5776
+	 *
5777
+	 * @return string|false
5778
+	 */
5779
+	public function cap_slug()
5780
+	{
5781
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5782
+	}
5783
+
5784
+
5785
+
5786
+	/**
5787
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5788
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5789
+	 * only returns the cap restrictions array in that context (ie, the array
5790
+	 * at that key)
5791
+	 *
5792
+	 * @param string $context
5793
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5794
+	 * @throws EE_Error
5795
+	 */
5796
+	public function cap_restrictions($context = EEM_Base::caps_read)
5797
+	{
5798
+		EEM_Base::verify_is_valid_cap_context($context);
5799
+		//check if we ought to run the restriction generator first
5800
+		if (
5801
+			isset($this->_cap_restriction_generators[$context])
5802
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5803
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5804
+		) {
5805
+			$this->_cap_restrictions[$context] = array_merge(
5806
+				$this->_cap_restrictions[$context],
5807
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5808
+			);
5809
+		}
5810
+		//and make sure we've finalized the construction of each restriction
5811
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5812
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5813
+				$where_conditions_obj->_finalize_construct($this);
5814
+			}
5815
+		}
5816
+		return $this->_cap_restrictions[$context];
5817
+	}
5818
+
5819
+
5820
+
5821
+	/**
5822
+	 * Indicating whether or not this model thinks its a wp core model
5823
+	 *
5824
+	 * @return boolean
5825
+	 */
5826
+	public function is_wp_core_model()
5827
+	{
5828
+		return $this->_wp_core_model;
5829
+	}
5830
+
5831
+
5832
+
5833
+	/**
5834
+	 * Gets all the caps that are missing which impose a restriction on
5835
+	 * queries made in this context
5836
+	 *
5837
+	 * @param string $context one of EEM_Base::caps_ constants
5838
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5839
+	 * @throws EE_Error
5840
+	 */
5841
+	public function caps_missing($context = EEM_Base::caps_read)
5842
+	{
5843
+		$missing_caps = array();
5844
+		$cap_restrictions = $this->cap_restrictions($context);
5845
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5846
+			if (! EE_Capabilities::instance()
5847
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5848
+			) {
5849
+				$missing_caps[$cap] = $restriction_if_no_cap;
5850
+			}
5851
+		}
5852
+		return $missing_caps;
5853
+	}
5854
+
5855
+
5856
+
5857
+	/**
5858
+	 * Gets the mapping from capability contexts to action strings used in capability names
5859
+	 *
5860
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5861
+	 * one of 'read', 'edit', or 'delete'
5862
+	 */
5863
+	public function cap_contexts_to_cap_action_map()
5864
+	{
5865
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5866
+			$this);
5867
+	}
5868
+
5869
+
5870
+
5871
+	/**
5872
+	 * Gets the action string for the specified capability context
5873
+	 *
5874
+	 * @param string $context
5875
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5876
+	 * @throws EE_Error
5877
+	 */
5878
+	public function cap_action_for_context($context)
5879
+	{
5880
+		$mapping = $this->cap_contexts_to_cap_action_map();
5881
+		if (isset($mapping[$context])) {
5882
+			return $mapping[$context];
5883
+		}
5884
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5885
+			return $action;
5886
+		}
5887
+		throw new EE_Error(
5888
+			sprintf(
5889
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5890
+				$context,
5891
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5892
+			)
5893
+		);
5894
+	}
5895
+
5896
+
5897
+
5898
+	/**
5899
+	 * Returns all the capability contexts which are valid when querying models
5900
+	 *
5901
+	 * @return array
5902
+	 */
5903
+	public static function valid_cap_contexts()
5904
+	{
5905
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5906
+			self::caps_read,
5907
+			self::caps_read_admin,
5908
+			self::caps_edit,
5909
+			self::caps_delete,
5910
+		));
5911
+	}
5912
+
5913
+
5914
+
5915
+	/**
5916
+	 * Returns all valid options for 'default_where_conditions'
5917
+	 *
5918
+	 * @return array
5919
+	 */
5920
+	public static function valid_default_where_conditions()
5921
+	{
5922
+		return array(
5923
+			EEM_Base::default_where_conditions_all,
5924
+			EEM_Base::default_where_conditions_this_only,
5925
+			EEM_Base::default_where_conditions_others_only,
5926
+			EEM_Base::default_where_conditions_minimum_all,
5927
+			EEM_Base::default_where_conditions_minimum_others,
5928
+			EEM_Base::default_where_conditions_none
5929
+		);
5930
+	}
5931
+
5932
+	// public static function default_where_conditions_full
5933
+	/**
5934
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5935
+	 *
5936
+	 * @param string $context
5937
+	 * @return bool
5938
+	 * @throws EE_Error
5939
+	 */
5940
+	static public function verify_is_valid_cap_context($context)
5941
+	{
5942
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5943
+		if (in_array($context, $valid_cap_contexts)) {
5944
+			return true;
5945
+		}
5946
+		throw new EE_Error(
5947
+			sprintf(
5948
+				__(
5949
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5950
+					'event_espresso'
5951
+				),
5952
+				$context,
5953
+				'EEM_Base',
5954
+				implode(',', $valid_cap_contexts)
5955
+			)
5956
+		);
5957
+	}
5958
+
5959
+
5960
+
5961
+	/**
5962
+	 * Clears all the models field caches. This is only useful when a sub-class
5963
+	 * might have added a field or something and these caches might be invalidated
5964
+	 */
5965
+	protected function _invalidate_field_caches()
5966
+	{
5967
+		$this->_cache_foreign_key_to_fields = array();
5968
+		$this->_cached_fields = null;
5969
+		$this->_cached_fields_non_db_only = null;
5970
+	}
5971
+
5972
+
5973
+
5974
+	/**
5975
+	 * _instantiate_new_instance_from_db
5976
+	 *
5977
+	 * @param string $class_name
5978
+	 * @param array  $arguments
5979
+	 * @return \EE_Base_Class
5980
+	 * @throws Exception
5981
+	 */
5982
+	public function _instantiate_new_instance_from_db($class_name, $arguments)
5983
+	{
5984
+		if ( ! class_exists($class_name)) {
5985
+			throw new EE_Error(
5986
+				sprintf(
5987
+					__('The "%s" class does not exist. Please ensure that an autoloader is set.', 'event_espresso'),
5988
+					$class_name
5989
+				)
5990
+			);
5991
+		}
5992
+		return call_user_func_array(
5993
+			array($class_name, 'new_instance'),
5994
+			array((array)$arguments, $this->_timezone, array(), true)
5995
+		);
5996
+	}
5997
+
5998
+
5999
+	/**
6000
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6001
+	 * (eg "and", "or", "not").
6002
+	 *
6003
+	 * @return array
6004
+	 */
6005
+	public function logic_query_param_keys()
6006
+	{
6007
+		return $this->_logic_query_param_keys;
6008
+	}
6009
+
6010
+
6011
+
6012
+	/**
6013
+	 * Determines whether or not the where query param array key is for a logic query param.
6014
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6015
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6016
+	 *
6017
+	 * @param $query_param_key
6018
+	 * @return bool
6019
+	 */
6020
+	public function is_logic_query_param_key($query_param_key)
6021
+	{
6022
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6023
+			if ($query_param_key === $logic_query_param_key
6024
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6025
+			) {
6026
+				return true;
6027
+			}
6028
+		}
6029
+		return false;
6030
+	}
6031 6031
 
6032 6032
 
6033 6033
 
Please login to merge, or discard this patch.
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -519,8 +519,8 @@  discard block
 block discarded – undo
519 519
     protected function __construct($timezone = null)
520 520
     {
521 521
         // check that the model has not been loaded too soon
522
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
523
-            throw new EE_Error (
522
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
523
+            throw new EE_Error(
524 524
                 sprintf(
525 525
                     __('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.',
526 526
                         'event_espresso'),
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
          *
541 541
          * @var EE_Table_Base[] $_tables
542 542
          */
543
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
543
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
544 544
         foreach ($this->_tables as $table_alias => $table_obj) {
545 545
             /** @var $table_obj EE_Table_Base */
546 546
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -555,10 +555,10 @@  discard block
 block discarded – undo
555 555
          *
556 556
          * @param EE_Model_Field_Base[] $_fields
557 557
          */
558
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
558
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
559 559
         $this->_invalidate_field_caches();
560 560
         foreach ($this->_fields as $table_alias => $fields_for_table) {
561
-            if (! array_key_exists($table_alias, $this->_tables)) {
561
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
562 562
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
563 563
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
564 564
             }
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
          *
587 587
          * @param EE_Model_Relation_Base[] $_model_relations
588 588
          */
589
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
589
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
590 590
             $this->_model_relations);
591 591
         foreach ($this->_model_relations as $model_name => $relation_obj) {
592 592
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -598,12 +598,12 @@  discard block
 block discarded – undo
598 598
         }
599 599
         $this->set_timezone($timezone);
600 600
         //finalize default where condition strategy, or set default
601
-        if (! $this->_default_where_conditions_strategy) {
601
+        if ( ! $this->_default_where_conditions_strategy) {
602 602
             //nothing was set during child constructor, so set default
603 603
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
604 604
         }
605 605
         $this->_default_where_conditions_strategy->_finalize_construct($this);
606
-        if (! $this->_minimum_where_conditions_strategy) {
606
+        if ( ! $this->_minimum_where_conditions_strategy) {
607 607
             //nothing was set during child constructor, so set default
608 608
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
609 609
         }
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
         //initialize the standard cap restriction generators if none were specified by the child constructor
617 617
         if ($this->_cap_restriction_generators !== false) {
618 618
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
619
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
619
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
620 620
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
621 621
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
622 622
                         new EE_Restriction_Generator_Protected(),
@@ -629,10 +629,10 @@  discard block
 block discarded – undo
629 629
         //if there are cap restriction generators, use them to make the default cap restrictions
630 630
         if ($this->_cap_restriction_generators !== false) {
631 631
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
632
-                if (! $generator_object) {
632
+                if ( ! $generator_object) {
633 633
                     continue;
634 634
                 }
635
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
635
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
636 636
                     throw new EE_Error(
637 637
                         sprintf(
638 638
                             __('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.',
@@ -643,12 +643,12 @@  discard block
 block discarded – undo
643 643
                     );
644 644
                 }
645 645
                 $action = $this->cap_action_for_context($context);
646
-                if (! $generator_object->construction_finalized()) {
646
+                if ( ! $generator_object->construction_finalized()) {
647 647
                     $generator_object->_construct_finalize($this, $action);
648 648
                 }
649 649
             }
650 650
         }
651
-        do_action('AHEE__' . get_class($this) . '__construct__end');
651
+        do_action('AHEE__'.get_class($this).'__construct__end');
652 652
     }
653 653
 
654 654
 
@@ -683,7 +683,7 @@  discard block
 block discarded – undo
683 683
      */
684 684
     public static function set_model_query_blog_id($blog_id = 0)
685 685
     {
686
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
686
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
687 687
     }
688 688
 
689 689
 
@@ -717,7 +717,7 @@  discard block
 block discarded – undo
717 717
     public static function instance($timezone = null)
718 718
     {
719 719
         // check if instance of Espresso_model already exists
720
-        if (! static::$_instance instanceof static) {
720
+        if ( ! static::$_instance instanceof static) {
721 721
             // instantiate Espresso_model
722 722
             static::$_instance = new static(
723 723
                 $timezone,
@@ -756,7 +756,7 @@  discard block
 block discarded – undo
756 756
             foreach ($r->getDefaultProperties() as $property => $value) {
757 757
                 //don't set instance to null like it was originally,
758 758
                 //but it's static anyways, and we're ignoring static properties (for now at least)
759
-                if (! isset($static_properties[$property])) {
759
+                if ( ! isset($static_properties[$property])) {
760 760
                     static::$_instance->{$property} = $value;
761 761
                 }
762 762
             }
@@ -781,7 +781,7 @@  discard block
 block discarded – undo
781 781
      */
782 782
     public function status_array($translated = false)
783 783
     {
784
-        if (! array_key_exists('Status', $this->_model_relations)) {
784
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
785 785
             return array();
786 786
         }
787 787
         $model_name = $this->get_this_model_name();
@@ -984,17 +984,17 @@  discard block
 block discarded – undo
984 984
     public function wp_user_field_name()
985 985
     {
986 986
         try {
987
-            if (! empty($this->_model_chain_to_wp_user)) {
987
+            if ( ! empty($this->_model_chain_to_wp_user)) {
988 988
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
989 989
                 $last_model_name = end($models_to_follow_to_wp_users);
990 990
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
991
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
991
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
992 992
             } else {
993 993
                 $model_with_fk_to_wp_users = $this;
994 994
                 $model_chain_to_wp_user = '';
995 995
             }
996 996
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
997
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
997
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
998 998
         } catch (EE_Error $e) {
999 999
             return false;
1000 1000
         }
@@ -1065,12 +1065,12 @@  discard block
 block discarded – undo
1065 1065
         // remember the custom selections, if any, and type cast as array
1066 1066
         // (unless $columns_to_select is an object, then just set as an empty array)
1067 1067
         // Note: (array) 'some string' === array( 'some string' )
1068
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1068
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1069 1069
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1070 1070
         $select_expressions = $columns_to_select !== null
1071 1071
             ? $this->_construct_select_from_input($columns_to_select)
1072 1072
             : $this->_construct_default_select_sql($model_query_info);
1073
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1073
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1074 1074
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1075 1075
     }
1076 1076
 
@@ -1115,7 +1115,7 @@  discard block
 block discarded – undo
1115 1115
         if (is_array($columns_to_select)) {
1116 1116
             $select_sql_array = array();
1117 1117
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1118
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1118
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1119 1119
                     throw new EE_Error(
1120 1120
                         sprintf(
1121 1121
                             __(
@@ -1127,7 +1127,7 @@  discard block
 block discarded – undo
1127 1127
                         )
1128 1128
                     );
1129 1129
                 }
1130
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1130
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1131 1131
                     throw new EE_Error(
1132 1132
                         sprintf(
1133 1133
                             __(
@@ -1199,7 +1199,7 @@  discard block
 block discarded – undo
1199 1199
      */
1200 1200
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1201 1201
     {
1202
-        if (! isset($query_params[0])) {
1202
+        if ( ! isset($query_params[0])) {
1203 1203
             $query_params[0] = array();
1204 1204
         }
1205 1205
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1224,7 +1224,7 @@  discard block
 block discarded – undo
1224 1224
      */
1225 1225
     public function get_one($query_params = array())
1226 1226
     {
1227
-        if (! is_array($query_params)) {
1227
+        if ( ! is_array($query_params)) {
1228 1228
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1229 1229
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1230 1230
                     gettype($query_params)), '4.6.0');
@@ -1415,7 +1415,7 @@  discard block
 block discarded – undo
1415 1415
                 return array();
1416 1416
             }
1417 1417
         }
1418
-        if (! is_array($query_params)) {
1418
+        if ( ! is_array($query_params)) {
1419 1419
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1420 1420
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1421 1421
                     gettype($query_params)), '4.6.0');
@@ -1425,7 +1425,7 @@  discard block
 block discarded – undo
1425 1425
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1426 1426
         $query_params['limit'] = $limit;
1427 1427
         //set direction
1428
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1428
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1429 1429
         $query_params['order_by'] = $operand === '>'
1430 1430
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1431 1431
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1503,7 +1503,7 @@  discard block
 block discarded – undo
1503 1503
     {
1504 1504
         $field_settings = $this->field_settings_for($field_name);
1505 1505
         //if not a valid EE_Datetime_Field then throw error
1506
-        if (! $field_settings instanceof EE_Datetime_Field) {
1506
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1507 1507
             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.',
1508 1508
                 'event_espresso'), $field_name));
1509 1509
         }
@@ -1582,7 +1582,7 @@  discard block
 block discarded – undo
1582 1582
         //load EEH_DTT_Helper
1583 1583
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1584 1584
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1585
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1585
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1586 1586
     }
1587 1587
 
1588 1588
 
@@ -1650,7 +1650,7 @@  discard block
 block discarded – undo
1650 1650
      */
1651 1651
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1652 1652
     {
1653
-        if (! is_array($query_params)) {
1653
+        if ( ! is_array($query_params)) {
1654 1654
             EE_Error::doing_it_wrong('EEM_Base::update',
1655 1655
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1656 1656
                     gettype($query_params)), '4.6.0');
@@ -1672,7 +1672,7 @@  discard block
 block discarded – undo
1672 1672
          * @param EEM_Base $model           the model being queried
1673 1673
          * @param array    $query_params    see EEM_Base::get_all()
1674 1674
          */
1675
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1675
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1676 1676
             $query_params);
1677 1677
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1678 1678
         //to do that, for each table, verify that it's PK isn't null.
@@ -1686,7 +1686,7 @@  discard block
 block discarded – undo
1686 1686
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1687 1687
         foreach ($wpdb_select_results as $wpdb_result) {
1688 1688
             // type cast stdClass as array
1689
-            $wpdb_result = (array)$wpdb_result;
1689
+            $wpdb_result = (array) $wpdb_result;
1690 1690
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1691 1691
             if ($this->has_primary_key_field()) {
1692 1692
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1703,13 +1703,13 @@  discard block
 block discarded – undo
1703 1703
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1704 1704
                     //if there is no private key for this table on the results, it means there's no entry
1705 1705
                     //in this table, right? so insert a row in the current table, using any fields available
1706
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1706
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1707 1707
                            && $wpdb_result[$this_table_pk_column])
1708 1708
                     ) {
1709 1709
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1710 1710
                             $main_table_pk_value);
1711 1711
                         //if we died here, report the error
1712
-                        if (! $success) {
1712
+                        if ( ! $success) {
1713 1713
                             return false;
1714 1714
                         }
1715 1715
                     }
@@ -1740,7 +1740,7 @@  discard block
 block discarded – undo
1740 1740
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1741 1741
                 }
1742 1742
             }
1743
-            if (! $model_objs_affected_ids) {
1743
+            if ( ! $model_objs_affected_ids) {
1744 1744
                 //wait wait wait- if nothing was affected let's stop here
1745 1745
                 return 0;
1746 1746
             }
@@ -1767,7 +1767,7 @@  discard block
 block discarded – undo
1767 1767
                . $model_query_info->get_full_join_sql()
1768 1768
                . " SET "
1769 1769
                . $this->_construct_update_sql($fields_n_values)
1770
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1770
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1771 1771
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1772 1772
         /**
1773 1773
          * Action called after a model update call has been made.
@@ -1778,7 +1778,7 @@  discard block
 block discarded – undo
1778 1778
          * @param int      $rows_affected
1779 1779
          */
1780 1780
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1781
-        return $rows_affected;//how many supposedly got updated
1781
+        return $rows_affected; //how many supposedly got updated
1782 1782
     }
1783 1783
 
1784 1784
 
@@ -1806,7 +1806,7 @@  discard block
 block discarded – undo
1806 1806
         }
1807 1807
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1808 1808
         $select_expressions = $field->get_qualified_column();
1809
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1809
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1810 1810
         return $this->_do_wpdb_query('get_col', array($SQL));
1811 1811
     }
1812 1812
 
@@ -1824,7 +1824,7 @@  discard block
 block discarded – undo
1824 1824
     {
1825 1825
         $query_params['limit'] = 1;
1826 1826
         $col = $this->get_col($query_params, $field_to_select);
1827
-        if (! empty($col)) {
1827
+        if ( ! empty($col)) {
1828 1828
             return reset($col);
1829 1829
         }
1830 1830
         return null;
@@ -1855,7 +1855,7 @@  discard block
 block discarded – undo
1855 1855
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1856 1856
             $value_sql = $prepared_value === null ? 'NULL'
1857 1857
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1858
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1858
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1859 1859
         }
1860 1860
         return implode(",", $cols_n_values);
1861 1861
     }
@@ -2033,7 +2033,7 @@  discard block
 block discarded – undo
2033 2033
          * @param int      $rows_deleted
2034 2034
          */
2035 2035
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2036
-        return $rows_deleted;//how many supposedly got deleted
2036
+        return $rows_deleted; //how many supposedly got deleted
2037 2037
     }
2038 2038
 
2039 2039
 
@@ -2182,7 +2182,7 @@  discard block
 block discarded – undo
2182 2182
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2183 2183
                 //make sure we have unique $ids
2184 2184
                 $ids = array_unique($ids);
2185
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2185
+                $query[] = $column.' IN('.implode(',', $ids).')';
2186 2186
             }
2187 2187
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2188 2188
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2190,9 +2190,9 @@  discard block
 block discarded – undo
2190 2190
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2191 2191
                 $values_for_each_combined_primary_key_for_a_row = array();
2192 2192
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2193
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2193
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2194 2194
                 }
2195
-                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2195
+                $ways_to_identify_a_row[] = '('.implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2196 2196
             }
2197 2197
             $query_part = implode(' OR ', $ways_to_identify_a_row);
2198 2198
         }
@@ -2238,9 +2238,9 @@  discard block
 block discarded – undo
2238 2238
                 $column_to_count = '*';
2239 2239
             }
2240 2240
         }
2241
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2242
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2243
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2241
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2242
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2243
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2244 2244
     }
2245 2245
 
2246 2246
 
@@ -2262,14 +2262,14 @@  discard block
 block discarded – undo
2262 2262
             $field_obj = $this->get_primary_key_field();
2263 2263
         }
2264 2264
         $column_to_count = $field_obj->get_qualified_column();
2265
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2265
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2266 2266
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2267 2267
         $data_type = $field_obj->get_wpdb_data_type();
2268 2268
         if ($data_type === '%d' || $data_type === '%s') {
2269
-            return (float)$return_value;
2269
+            return (float) $return_value;
2270 2270
         }
2271 2271
         //must be %f
2272
-        return (float)$return_value;
2272
+        return (float) $return_value;
2273 2273
     }
2274 2274
 
2275 2275
 
@@ -2289,13 +2289,13 @@  discard block
 block discarded – undo
2289 2289
         //if we're in maintenance mode level 2, DON'T run any queries
2290 2290
         //because level 2 indicates the database needs updating and
2291 2291
         //is probably out of sync with the code
2292
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2292
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2293 2293
             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.",
2294 2294
                 "event_espresso")));
2295 2295
         }
2296 2296
         /** @type WPDB $wpdb */
2297 2297
         global $wpdb;
2298
-        if (! method_exists($wpdb, $wpdb_method)) {
2298
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2299 2299
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2300 2300
                 'event_espresso'), $wpdb_method));
2301 2301
         }
@@ -2307,7 +2307,7 @@  discard block
 block discarded – undo
2307 2307
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2308 2308
         if (WP_DEBUG) {
2309 2309
             $wpdb->show_errors($old_show_errors_value);
2310
-            if (! empty($wpdb->last_error)) {
2310
+            if ( ! empty($wpdb->last_error)) {
2311 2311
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2312 2312
             }
2313 2313
             if ($result === false) {
@@ -2368,7 +2368,7 @@  discard block
 block discarded – undo
2368 2368
                     return $result;
2369 2369
                     break;
2370 2370
             }
2371
-            if (! empty($error_message)) {
2371
+            if ( ! empty($error_message)) {
2372 2372
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2373 2373
                 trigger_error($error_message);
2374 2374
             }
@@ -2444,11 +2444,11 @@  discard block
 block discarded – undo
2444 2444
      */
2445 2445
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2446 2446
     {
2447
-        return " FROM " . $model_query_info->get_full_join_sql() .
2448
-               $model_query_info->get_where_sql() .
2449
-               $model_query_info->get_group_by_sql() .
2450
-               $model_query_info->get_having_sql() .
2451
-               $model_query_info->get_order_by_sql() .
2447
+        return " FROM ".$model_query_info->get_full_join_sql().
2448
+               $model_query_info->get_where_sql().
2449
+               $model_query_info->get_group_by_sql().
2450
+               $model_query_info->get_having_sql().
2451
+               $model_query_info->get_order_by_sql().
2452 2452
                $model_query_info->get_limit_sql();
2453 2453
     }
2454 2454
 
@@ -2644,12 +2644,12 @@  discard block
 block discarded – undo
2644 2644
         $related_model = $this->get_related_model_obj($model_name);
2645 2645
         //we're just going to use the query params on the related model's normal get_all query,
2646 2646
         //except add a condition to say to match the current mod
2647
-        if (! isset($query_params['default_where_conditions'])) {
2647
+        if ( ! isset($query_params['default_where_conditions'])) {
2648 2648
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2649 2649
         }
2650 2650
         $this_model_name = $this->get_this_model_name();
2651 2651
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2652
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2652
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2653 2653
         return $related_model->count($query_params, $field_to_count, $distinct);
2654 2654
     }
2655 2655
 
@@ -2669,7 +2669,7 @@  discard block
 block discarded – undo
2669 2669
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2670 2670
     {
2671 2671
         $related_model = $this->get_related_model_obj($model_name);
2672
-        if (! is_array($query_params)) {
2672
+        if ( ! is_array($query_params)) {
2673 2673
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2674 2674
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2675 2675
                     gettype($query_params)), '4.6.0');
@@ -2677,12 +2677,12 @@  discard block
 block discarded – undo
2677 2677
         }
2678 2678
         //we're just going to use the query params on the related model's normal get_all query,
2679 2679
         //except add a condition to say to match the current mod
2680
-        if (! isset($query_params['default_where_conditions'])) {
2680
+        if ( ! isset($query_params['default_where_conditions'])) {
2681 2681
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682 2682
         }
2683 2683
         $this_model_name = $this->get_this_model_name();
2684 2684
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2685
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2686 2686
         return $related_model->sum($query_params, $field_to_sum);
2687 2687
     }
2688 2688
 
@@ -2735,7 +2735,7 @@  discard block
 block discarded – undo
2735 2735
                 $field_with_model_name = $field;
2736 2736
             }
2737 2737
         }
2738
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2738
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2739 2739
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2740 2740
                 $this->get_this_model_name()));
2741 2741
         }
@@ -2768,7 +2768,7 @@  discard block
 block discarded – undo
2768 2768
          * @param array    $fields_n_values keys are the fields and values are their new values
2769 2769
          * @param EEM_Base $model           the model used
2770 2770
          */
2771
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2771
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2772 2772
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2773 2773
             $main_table = $this->_get_main_table();
2774 2774
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2875,7 +2875,7 @@  discard block
 block discarded – undo
2875 2875
         }
2876 2876
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2877 2877
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2878
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2878
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2879 2879
         }
2880 2880
         //if there is nothing to base this search on, then we shouldn't find anything
2881 2881
         if (empty($query_params)) {
@@ -2961,7 +2961,7 @@  discard block
 block discarded – undo
2961 2961
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2962 2962
             //so add the fk to the main table as a column
2963 2963
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2964
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2964
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2965 2965
         }
2966 2966
         //insert the new entry
2967 2967
         $result = $this->_do_wpdb_query('insert',
@@ -3165,7 +3165,7 @@  discard block
 block discarded – undo
3165 3165
                     $query_info_carrier,
3166 3166
                     'group_by'
3167 3167
                 );
3168
-            } elseif (! empty ($query_params['group_by'])) {
3168
+            } elseif ( ! empty ($query_params['group_by'])) {
3169 3169
                 $this->_extract_related_model_info_from_query_param(
3170 3170
                     $query_params['group_by'],
3171 3171
                     $query_info_carrier,
@@ -3187,7 +3187,7 @@  discard block
 block discarded – undo
3187 3187
                     $query_info_carrier,
3188 3188
                     'order_by'
3189 3189
                 );
3190
-            } elseif (! empty($query_params['order_by'])) {
3190
+            } elseif ( ! empty($query_params['order_by'])) {
3191 3191
                 $this->_extract_related_model_info_from_query_param(
3192 3192
                     $query_params['order_by'],
3193 3193
                     $query_info_carrier,
@@ -3222,8 +3222,8 @@  discard block
 block discarded – undo
3222 3222
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3223 3223
         $query_param_type
3224 3224
     ) {
3225
-        if (! empty($sub_query_params)) {
3226
-            $sub_query_params = (array)$sub_query_params;
3225
+        if ( ! empty($sub_query_params)) {
3226
+            $sub_query_params = (array) $sub_query_params;
3227 3227
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3228 3228
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3229 3229
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3234,7 +3234,7 @@  discard block
 block discarded – undo
3234 3234
                 //of array('Registration.TXN_ID'=>23)
3235 3235
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3236 3236
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3237
-                    if (! is_array($possibly_array_of_params)) {
3237
+                    if ( ! is_array($possibly_array_of_params)) {
3238 3238
                         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'))",
3239 3239
                             "event_espresso"),
3240 3240
                             $param, $possibly_array_of_params));
@@ -3251,7 +3251,7 @@  discard block
 block discarded – undo
3251 3251
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3252 3252
                     //indicating that $possible_array_of_params[1] is actually a field name,
3253 3253
                     //from which we should extract query parameters!
3254
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3254
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3255 3255
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3256 3256
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3257 3257
                     }
@@ -3281,8 +3281,8 @@  discard block
 block discarded – undo
3281 3281
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3282 3282
         $query_param_type
3283 3283
     ) {
3284
-        if (! empty($sub_query_params)) {
3285
-            if (! is_array($sub_query_params)) {
3284
+        if ( ! empty($sub_query_params)) {
3285
+            if ( ! is_array($sub_query_params)) {
3286 3286
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3287 3287
                     $sub_query_params));
3288 3288
             }
@@ -3311,7 +3311,7 @@  discard block
 block discarded – undo
3311 3311
      */
3312 3312
     public function _create_model_query_info_carrier($query_params)
3313 3313
     {
3314
-        if (! is_array($query_params)) {
3314
+        if ( ! is_array($query_params)) {
3315 3315
             EE_Error::doing_it_wrong(
3316 3316
                 'EEM_Base::_create_model_query_info_carrier',
3317 3317
                 sprintf(
@@ -3387,7 +3387,7 @@  discard block
 block discarded – undo
3387 3387
         //set limit
3388 3388
         if (array_key_exists('limit', $query_params)) {
3389 3389
             if (is_array($query_params['limit'])) {
3390
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3390
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3391 3391
                     $e = sprintf(
3392 3392
                         __(
3393 3393
                             "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)",
@@ -3395,12 +3395,12 @@  discard block
 block discarded – undo
3395 3395
                         ),
3396 3396
                         http_build_query($query_params['limit'])
3397 3397
                     );
3398
-                    throw new EE_Error($e . "|" . $e);
3398
+                    throw new EE_Error($e."|".$e);
3399 3399
                 }
3400 3400
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3401
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3402
-            } elseif (! empty ($query_params['limit'])) {
3403
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3401
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3402
+            } elseif ( ! empty ($query_params['limit'])) {
3403
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3404 3404
             }
3405 3405
         }
3406 3406
         //set order by
@@ -3432,10 +3432,10 @@  discard block
 block discarded – undo
3432 3432
                 $order_array = array();
3433 3433
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3434 3434
                     $order = $this->_extract_order($order);
3435
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3435
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3436 3436
                 }
3437
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3438
-            } elseif (! empty ($query_params['order_by'])) {
3437
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3438
+            } elseif ( ! empty ($query_params['order_by'])) {
3439 3439
                 $this->_extract_related_model_info_from_query_param(
3440 3440
                     $query_params['order_by'],
3441 3441
                     $query_object,
@@ -3446,18 +3446,18 @@  discard block
 block discarded – undo
3446 3446
                     ? $this->_extract_order($query_params['order'])
3447 3447
                     : 'DESC';
3448 3448
                 $query_object->set_order_by_sql(
3449
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3449
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3450 3450
                 );
3451 3451
             }
3452 3452
         }
3453 3453
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3454
-        if (! array_key_exists('order_by', $query_params)
3454
+        if ( ! array_key_exists('order_by', $query_params)
3455 3455
             && array_key_exists('order', $query_params)
3456 3456
             && ! empty($query_params['order'])
3457 3457
         ) {
3458 3458
             $pk_field = $this->get_primary_key_field();
3459 3459
             $order = $this->_extract_order($query_params['order']);
3460
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3460
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3461 3461
         }
3462 3462
         //set group by
3463 3463
         if (array_key_exists('group_by', $query_params)) {
@@ -3467,10 +3467,10 @@  discard block
 block discarded – undo
3467 3467
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3468 3468
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3469 3469
                 }
3470
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3471
-            } elseif (! empty ($query_params['group_by'])) {
3470
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3471
+            } elseif ( ! empty ($query_params['group_by'])) {
3472 3472
                 $query_object->set_group_by_sql(
3473
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3473
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3474 3474
                 );
3475 3475
             }
3476 3476
         }
@@ -3480,7 +3480,7 @@  discard block
 block discarded – undo
3480 3480
         }
3481 3481
         //now, just verify they didn't pass anything wack
3482 3482
         foreach ($query_params as $query_key => $query_value) {
3483
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3483
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3484 3484
                 throw new EE_Error(
3485 3485
                     sprintf(
3486 3486
                         __(
@@ -3579,22 +3579,22 @@  discard block
 block discarded – undo
3579 3579
         $where_query_params = array()
3580 3580
     ) {
3581 3581
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3582
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3582
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3583 3583
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3584 3584
                 "event_espresso"), $use_default_where_conditions,
3585 3585
                 implode(", ", $allowed_used_default_where_conditions_values)));
3586 3586
         }
3587 3587
         $universal_query_params = array();
3588
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3588
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3589 3589
             $universal_query_params = $this->_get_default_where_conditions();
3590
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3590
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3591 3591
             $universal_query_params = $this->_get_minimum_where_conditions();
3592 3592
         }
3593 3593
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3594 3594
             $related_model = $this->get_related_model_obj($model_name);
3595
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3595
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3596 3596
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3597
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3597
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3598 3598
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3599 3599
             } else {
3600 3600
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3627,7 +3627,7 @@  discard block
 block discarded – undo
3627 3627
      * @param bool $for_this_model false means this is for OTHER related models
3628 3628
      * @return bool
3629 3629
      */
3630
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3630
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3631 3631
     {
3632 3632
         return (
3633 3633
                    $for_this_model
@@ -3706,7 +3706,7 @@  discard block
 block discarded – undo
3706 3706
     ) {
3707 3707
         $null_friendly_where_conditions = array();
3708 3708
         $none_overridden = true;
3709
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3709
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3710 3710
         foreach ($default_where_conditions as $key => $val) {
3711 3711
             if (isset($provided_where_conditions[$key])) {
3712 3712
                 $none_overridden = false;
@@ -3824,7 +3824,7 @@  discard block
 block discarded – undo
3824 3824
             foreach ($tables as $table_obj) {
3825 3825
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3826 3826
                                        . $table_obj->get_fully_qualified_pk_column();
3827
-                if (! in_array($qualified_pk_column, $selects)) {
3827
+                if ( ! in_array($qualified_pk_column, $selects)) {
3828 3828
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3829 3829
                 }
3830 3830
             }
@@ -3918,9 +3918,9 @@  discard block
 block discarded – undo
3918 3918
         //and
3919 3919
         //check if it's a field on a related model
3920 3920
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3921
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3921
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3922 3922
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3923
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3923
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3924 3924
                 if ($query_param === '') {
3925 3925
                     //nothing left to $query_param
3926 3926
                     //we should actually end in a field name, not a model like this!
@@ -4008,7 +4008,7 @@  discard block
 block discarded – undo
4008 4008
     {
4009 4009
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4010 4010
         if ($SQL) {
4011
-            return " WHERE " . $SQL;
4011
+            return " WHERE ".$SQL;
4012 4012
         }
4013 4013
         return '';
4014 4014
     }
@@ -4027,7 +4027,7 @@  discard block
 block discarded – undo
4027 4027
     {
4028 4028
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4029 4029
         if ($SQL) {
4030
-            return " HAVING " . $SQL;
4030
+            return " HAVING ".$SQL;
4031 4031
         }
4032 4032
         return '';
4033 4033
     }
@@ -4046,11 +4046,11 @@  discard block
 block discarded – undo
4046 4046
      */
4047 4047
     protected function _get_field_on_model($field_name, $model_name)
4048 4048
     {
4049
-        $model_class = 'EEM_' . $model_name;
4050
-        $model_filepath = $model_class . ".model.php";
4049
+        $model_class = 'EEM_'.$model_name;
4050
+        $model_filepath = $model_class.".model.php";
4051 4051
         if (is_readable($model_filepath)) {
4052 4052
             require_once($model_filepath);
4053
-            $model_instance = call_user_func($model_name . "::instance");
4053
+            $model_instance = call_user_func($model_name."::instance");
4054 4054
             /* @var $model_instance EEM_Base */
4055 4055
             return $model_instance->field_settings_for($field_name);
4056 4056
         }
@@ -4079,7 +4079,7 @@  discard block
 block discarded – undo
4079 4079
     {
4080 4080
         $where_clauses = array();
4081 4081
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4082
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4082
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
4083 4083
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4084 4084
                 switch ($query_param) {
4085 4085
                     case 'not':
@@ -4107,7 +4107,7 @@  discard block
 block discarded – undo
4107 4107
             } else {
4108 4108
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4109 4109
                 //if it's not a normal field, maybe it's a custom selection?
4110
-                if (! $field_obj) {
4110
+                if ( ! $field_obj) {
4111 4111
                     if (isset($this->_custom_selections[$query_param][1])) {
4112 4112
                         $field_obj = $this->_custom_selections[$query_param][1];
4113 4113
                     } else {
@@ -4116,7 +4116,7 @@  discard block
 block discarded – undo
4116 4116
                     }
4117 4117
                 }
4118 4118
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4119
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4119
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4120 4120
             }
4121 4121
         }
4122 4122
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4137,7 +4137,7 @@  discard block
 block discarded – undo
4137 4137
         if ($field) {
4138 4138
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4139 4139
                 $query_param);
4140
-            return $table_alias_prefix . $field->get_qualified_column();
4140
+            return $table_alias_prefix.$field->get_qualified_column();
4141 4141
         }
4142 4142
         if (array_key_exists($query_param, $this->_custom_selections)) {
4143 4143
             //maybe it's custom selection item?
@@ -4189,7 +4189,7 @@  discard block
 block discarded – undo
4189 4189
     {
4190 4190
         if (is_array($op_and_value)) {
4191 4191
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4192
-            if (! $operator) {
4192
+            if ( ! $operator) {
4193 4193
                 $php_array_like_string = array();
4194 4194
                 foreach ($op_and_value as $key => $value) {
4195 4195
                     $php_array_like_string[] = "$key=>$value";
@@ -4211,14 +4211,14 @@  discard block
 block discarded – undo
4211 4211
         }
4212 4212
         //check to see if the value is actually another field
4213 4213
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4214
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4214
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4215 4215
         }
4216 4216
         if (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4217 4217
             //in this case, the value should be an array, or at least a comma-separated list
4218 4218
             //it will need to handle a little differently
4219 4219
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4220 4220
             //note: $cleaned_value has already been run through $wpdb->prepare()
4221
-            return $operator . SP . $cleaned_value;
4221
+            return $operator.SP.$cleaned_value;
4222 4222
         }
4223 4223
         if (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4224 4224
             //the value should be an array with count of two.
@@ -4234,7 +4234,7 @@  discard block
 block discarded – undo
4234 4234
                 );
4235 4235
             }
4236 4236
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4237
-            return $operator . SP . $cleaned_value;
4237
+            return $operator.SP.$cleaned_value;
4238 4238
         }
4239 4239
         if (in_array($operator, $this->_null_style_operators)) {
4240 4240
             if ($value !== null) {
@@ -4254,10 +4254,10 @@  discard block
 block discarded – undo
4254 4254
         if ($operator === 'LIKE' && ! is_array($value)) {
4255 4255
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4256 4256
             //remove other junk. So just treat it as a string.
4257
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4257
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4258 4258
         }
4259
-        if (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4260
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4259
+        if ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4260
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4261 4261
         }
4262 4262
         if (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4263 4263
             throw new EE_Error(
@@ -4271,7 +4271,7 @@  discard block
 block discarded – undo
4271 4271
                 )
4272 4272
             );
4273 4273
         }
4274
-        if (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4274
+        if ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4275 4275
             throw new EE_Error(
4276 4276
                 sprintf(
4277 4277
                     __(
@@ -4311,7 +4311,7 @@  discard block
 block discarded – undo
4311 4311
         foreach ($values as $value) {
4312 4312
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4313 4313
         }
4314
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4314
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4315 4315
     }
4316 4316
 
4317 4317
 
@@ -4352,7 +4352,7 @@  discard block
 block discarded – undo
4352 4352
                                 . $main_table->get_table_name()
4353 4353
                                 . " WHERE FALSE";
4354 4354
         }
4355
-        return "(" . implode(",", $cleaned_values) . ")";
4355
+        return "(".implode(",", $cleaned_values).")";
4356 4356
     }
4357 4357
 
4358 4358
 
@@ -4371,7 +4371,7 @@  discard block
 block discarded – undo
4371 4371
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4372 4372
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4373 4373
         } //$field_obj should really just be a data type
4374
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4374
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4375 4375
             throw new EE_Error(
4376 4376
                 sprintf(
4377 4377
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4499,10 +4499,10 @@  discard block
 block discarded – undo
4499 4499
      */
4500 4500
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4501 4501
     {
4502
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4502
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4503 4503
         $qualified_columns = array();
4504 4504
         foreach ($this->field_settings() as $field_name => $field) {
4505
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4505
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4506 4506
         }
4507 4507
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4508 4508
     }
@@ -4526,11 +4526,11 @@  discard block
 block discarded – undo
4526 4526
             if ($table_obj instanceof EE_Primary_Table) {
4527 4527
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4528 4528
                     ? $table_obj->get_select_join_limit($limit)
4529
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4529
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4530 4530
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4531 4531
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4532 4532
                     ? $table_obj->get_select_join_limit_join($limit)
4533
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4533
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4534 4534
             }
4535 4535
         }
4536 4536
         return $SQL;
@@ -4618,12 +4618,12 @@  discard block
 block discarded – undo
4618 4618
      */
4619 4619
     public function get_related_model_obj($model_name)
4620 4620
     {
4621
-        $model_classname = "EEM_" . $model_name;
4622
-        if (! class_exists($model_classname)) {
4621
+        $model_classname = "EEM_".$model_name;
4622
+        if ( ! class_exists($model_classname)) {
4623 4623
             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",
4624 4624
                 'event_espresso'), $model_name, $model_classname));
4625 4625
         }
4626
-        return call_user_func($model_classname . "::instance");
4626
+        return call_user_func($model_classname."::instance");
4627 4627
     }
4628 4628
 
4629 4629
 
@@ -4670,7 +4670,7 @@  discard block
 block discarded – undo
4670 4670
     public function related_settings_for($relation_name)
4671 4671
     {
4672 4672
         $relatedModels = $this->relation_settings();
4673
-        if (! array_key_exists($relation_name, $relatedModels)) {
4673
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4674 4674
             throw new EE_Error(
4675 4675
                 sprintf(
4676 4676
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4697,7 +4697,7 @@  discard block
 block discarded – undo
4697 4697
     public function field_settings_for($fieldName)
4698 4698
     {
4699 4699
         $fieldSettings = $this->field_settings(true);
4700
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4700
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4701 4701
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4702 4702
                 get_class($this)));
4703 4703
         }
@@ -4770,7 +4770,7 @@  discard block
 block discarded – undo
4770 4770
                     break;
4771 4771
                 }
4772 4772
             }
4773
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4773
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4774 4774
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4775 4775
                     get_class($this)));
4776 4776
             }
@@ -4829,7 +4829,7 @@  discard block
 block discarded – undo
4829 4829
      */
4830 4830
     public function get_foreign_key_to($model_name)
4831 4831
     {
4832
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4832
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4833 4833
             foreach ($this->field_settings() as $field) {
4834 4834
                 if (
4835 4835
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4839,7 +4839,7 @@  discard block
 block discarded – undo
4839 4839
                     break;
4840 4840
                 }
4841 4841
             }
4842
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4842
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4843 4843
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4844 4844
                     'event_espresso'), $model_name, get_class($this)));
4845 4845
             }
@@ -4890,7 +4890,7 @@  discard block
 block discarded – undo
4890 4890
             foreach ($this->_fields as $fields_corresponding_to_table) {
4891 4891
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4892 4892
                     /** @var $field_obj EE_Model_Field_Base */
4893
-                    if (! $field_obj->is_db_only_field()) {
4893
+                    if ( ! $field_obj->is_db_only_field()) {
4894 4894
                         $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4895 4895
                     }
4896 4896
                 }
@@ -4919,7 +4919,7 @@  discard block
 block discarded – undo
4919 4919
         $count_if_model_has_no_primary_key = 0;
4920 4920
         $has_primary_key = $this->has_primary_key_field();
4921 4921
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4922
-        foreach ((array)$rows as $row) {
4922
+        foreach ((array) $rows as $row) {
4923 4923
             if (empty($row)) {
4924 4924
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4925 4925
                 return array();
@@ -4937,7 +4937,7 @@  discard block
 block discarded – undo
4937 4937
                 }
4938 4938
             }
4939 4939
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4940
-            if (! $classInstance) {
4940
+            if ( ! $classInstance) {
4941 4941
                 throw new EE_Error(
4942 4942
                     sprintf(
4943 4943
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5009,7 +5009,7 @@  discard block
 block discarded – undo
5009 5009
      */
5010 5010
     public function instantiate_class_from_array_or_object($cols_n_values)
5011 5011
     {
5012
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5012
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5013 5013
             $cols_n_values = get_object_vars($cols_n_values);
5014 5014
         }
5015 5015
         $primary_key = null;
@@ -5033,7 +5033,7 @@  discard block
 block discarded – undo
5033 5033
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5034 5034
         if ($primary_key) {
5035 5035
             $classInstance = $this->get_from_entity_map($primary_key);
5036
-            if (! $classInstance) {
5036
+            if ( ! $classInstance) {
5037 5037
                 $classInstance = $this->_instantiate_new_instance_from_db(
5038 5038
                     $this->_get_class_name(),
5039 5039
                     $this_model_fields_n_values
@@ -5091,12 +5091,12 @@  discard block
 block discarded – undo
5091 5091
     public function add_to_entity_map(EE_Base_Class $object)
5092 5092
     {
5093 5093
         $className = $this->_get_class_name();
5094
-        if (! $object instanceof $className) {
5094
+        if ( ! $object instanceof $className) {
5095 5095
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5096 5096
                 is_object($object) ? get_class($object) : $object, $className));
5097 5097
         }
5098 5098
         /** @var $object EE_Base_Class */
5099
-        if (! $object->ID()) {
5099
+        if ( ! $object->ID()) {
5100 5100
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5101 5101
                 "event_espresso"), get_class($this)));
5102 5102
         }
@@ -5165,7 +5165,7 @@  discard block
 block discarded – undo
5165 5165
             //there is a primary key on this table and its not set. Use defaults for all its columns
5166 5166
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5167 5167
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5168
-                    if (! $field_obj->is_db_only_field()) {
5168
+                    if ( ! $field_obj->is_db_only_field()) {
5169 5169
                         //prepare field as if its coming from db
5170 5170
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5171 5171
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5174,7 +5174,7 @@  discard block
 block discarded – undo
5174 5174
             } else {
5175 5175
                 //the table's rows existed. Use their values
5176 5176
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5177
-                    if (! $field_obj->is_db_only_field()) {
5177
+                    if ( ! $field_obj->is_db_only_field()) {
5178 5178
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5179 5179
                             $cols_n_values, $field_obj->get_qualified_column(),
5180 5180
                             $field_obj->get_table_column()
@@ -5289,7 +5289,7 @@  discard block
 block discarded – undo
5289 5289
      */
5290 5290
     private function _get_class_name()
5291 5291
     {
5292
-        return "EE_" . $this->get_this_model_name();
5292
+        return "EE_".$this->get_this_model_name();
5293 5293
     }
5294 5294
 
5295 5295
 
@@ -5304,7 +5304,7 @@  discard block
 block discarded – undo
5304 5304
      */
5305 5305
     public function item_name($quantity = 1)
5306 5306
     {
5307
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5307
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5308 5308
     }
5309 5309
 
5310 5310
 
@@ -5337,7 +5337,7 @@  discard block
 block discarded – undo
5337 5337
     {
5338 5338
         $className = get_class($this);
5339 5339
         $tagName = "FHEE__{$className}__{$methodName}";
5340
-        if (! has_filter($tagName)) {
5340
+        if ( ! has_filter($tagName)) {
5341 5341
             throw new EE_Error(
5342 5342
                 sprintf(
5343 5343
                     __('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 );',
@@ -5563,7 +5563,7 @@  discard block
 block discarded – undo
5563 5563
         $key_vals_in_combined_pk = array();
5564 5564
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5565 5565
         foreach ($key_fields as $key_field_name => $field_obj) {
5566
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5566
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5567 5567
                 return null;
5568 5568
             }
5569 5569
         }
@@ -5584,7 +5584,7 @@  discard block
 block discarded – undo
5584 5584
     {
5585 5585
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5586 5586
         foreach ($keys_it_should_have as $key) {
5587
-            if (! isset($key_vals[$key])) {
5587
+            if ( ! isset($key_vals[$key])) {
5588 5588
                 return false;
5589 5589
             }
5590 5590
         }
@@ -5638,7 +5638,7 @@  discard block
 block discarded – undo
5638 5638
      */
5639 5639
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5640 5640
     {
5641
-        if (! is_array($query_params)) {
5641
+        if ( ! is_array($query_params)) {
5642 5642
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5643 5643
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5644 5644
                     gettype($query_params)), '4.6.0');
@@ -5734,7 +5734,7 @@  discard block
 block discarded – undo
5734 5734
      */
5735 5735
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5736 5736
     {
5737
-        if (! $this->has_primary_key_field()) {
5737
+        if ( ! $this->has_primary_key_field()) {
5738 5738
             if (WP_DEBUG) {
5739 5739
                 EE_Error::add_error(
5740 5740
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5747,7 +5747,7 @@  discard block
 block discarded – undo
5747 5747
         $IDs = array();
5748 5748
         foreach ($model_objects as $model_object) {
5749 5749
             $id = $model_object->ID();
5750
-            if (! $id) {
5750
+            if ( ! $id) {
5751 5751
                 if ($filter_out_empty_ids) {
5752 5752
                     continue;
5753 5753
                 }
@@ -5843,8 +5843,8 @@  discard block
 block discarded – undo
5843 5843
         $missing_caps = array();
5844 5844
         $cap_restrictions = $this->cap_restrictions($context);
5845 5845
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5846
-            if (! EE_Capabilities::instance()
5847
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5846
+            if ( ! EE_Capabilities::instance()
5847
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5848 5848
             ) {
5849 5849
                 $missing_caps[$cap] = $restriction_if_no_cap;
5850 5850
             }
@@ -5991,7 +5991,7 @@  discard block
 block discarded – undo
5991 5991
         }
5992 5992
         return call_user_func_array(
5993 5993
             array($class_name, 'new_instance'),
5994
-            array((array)$arguments, $this->_timezone, array(), true)
5994
+            array((array) $arguments, $this->_timezone, array(), true)
5995 5995
         );
5996 5996
     }
5997 5997
 
@@ -6021,7 +6021,7 @@  discard block
 block discarded – undo
6021 6021
     {
6022 6022
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6023 6023
             if ($query_param_key === $logic_query_param_key
6024
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6024
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6025 6025
             ) {
6026 6026
                 return true;
6027 6027
             }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 1 patch
Indentation   +2749 added lines, -2749 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 do_action('AHEE_log', __FILE__, ' FILE LOADED', '');
5 5
 
@@ -25,2754 +25,2754 @@  discard block
 block discarded – undo
25 25
 abstract class EE_Base_Class
26 26
 {
27 27
 
28
-    /**
29
-     * This is an array of the original properties and values provided during construction
30
-     * of this model object. (keys are model field names, values are their values).
31
-     * This list is important to remember so that when we are merging data from the db, we know
32
-     * which values to override and which to not override.
33
-     *
34
-     * @var array
35
-     */
36
-    protected $_props_n_values_provided_in_constructor;
37
-
38
-    /**
39
-     * Timezone
40
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
-     * access to it.
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_timezone;
48
-
49
-
50
-
51
-    /**
52
-     * date format
53
-     * pattern or format for displaying dates
54
-     *
55
-     * @var string $_dt_frmt
56
-     */
57
-    protected $_dt_frmt;
58
-
59
-
60
-
61
-    /**
62
-     * time format
63
-     * pattern or format for displaying time
64
-     *
65
-     * @var string $_tm_frmt
66
-     */
67
-    protected $_tm_frmt;
68
-
69
-
70
-
71
-    /**
72
-     * This property is for holding a cached array of object properties indexed by property name as the key.
73
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
74
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
-     *
77
-     * @var array
78
-     */
79
-    protected $_cached_properties = array();
80
-
81
-    /**
82
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
83
-     * single
84
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
-     * all others have an array)
87
-     *
88
-     * @var array
89
-     */
90
-    protected $_model_relations = array();
91
-
92
-    /**
93
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
-     *
96
-     * @var array
97
-     */
98
-    protected $_fields = array();
99
-
100
-    /**
101
-     * @var boolean indicating whether or not this model object is intended to ever be saved
102
-     * For example, we might create model objects intended to only be used for the duration
103
-     * of this request and to be thrown away, and if they were accidentally saved
104
-     * it would be a bug.
105
-     */
106
-    protected $_allow_persist = true;
107
-
108
-    /**
109
-     * @var boolean indicating whether or not this model object's properties have changed since construction
110
-     */
111
-    protected $_has_changes = false;
112
-
113
-    /**
114
-     * @var EEM_Base
115
-     */
116
-    protected $_model;
117
-
118
-
119
-
120
-    /**
121
-     * @param array  $fieldValues
122
-     * @param string $timezone
123
-     * @param array  $date_formats
124
-     * @param bool   $bydb
125
-     * @return \EE_Base_Class
126
-     * @throws \EE_Error
127
-     */
128
-    public static function new_instance(
129
-        array $fieldValues = array(),
130
-        $timezone = '',
131
-        array $date_formats = array(),
132
-        $bydb = false
133
-    )
134
-    {
135
-        $className = get_called_class();
136
-        if ( ! $bydb) {
137
-            $cached_object = \EE_Base_Class::_check_for_object($fieldValues, $className, $timezone, $date_formats);
138
-            if ($cached_object) {
139
-                return $cached_object;
140
-            }
141
-        }
142
-        return new static($fieldValues, $bydb, $timezone, $date_formats);
143
-    }
144
-
145
-
146
-
147
-    /**
148
-     * @deprecated
149
-     * @param array  $fieldValues
150
-     * @param string $timezone
151
-     * @param array  $date_formats
152
-     * @return \EE_Base_Class
153
-     * @throws \EE_Error
154
-     */
155
-    public static function new_instance_from_db(array $fieldValues = array(), $timezone = '', array $date_formats = array())
156
-    {
157
-        return static::new_instance($fieldValues, $timezone, $date_formats, true);
158
-    }
159
-
160
-
161
-    /**
162
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children play nice
163
-     *
164
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
165
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
166
-     *                                                         TXN_amount, QST_name, etc) and values are their values
167
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
168
-     *                                                         corresponding db model or not.
169
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
170
-     *                                                         be in when instantiating a EE_Base_Class object.
171
-     * @param array   $date_formats                            An array of date formats to set on construct where first
172
-     *                                                         value is the date_format and second value is the time
173
-     *                                                         format.
174
-     * @throws EE_Error
175
-     */
176
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
177
-    {
178
-        $className = get_class($this);
179
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
180
-        $model = $this->get_model();
181
-        $model_fields = $model->field_settings(false);
182
-        // ensure $fieldValues is an array
183
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
184
-        // EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
185
-        // verify client code has not passed any invalid field names
186
-        foreach ($fieldValues as $field_name => $field_value) {
187
-            if ( ! isset($model_fields[$field_name])) {
188
-                throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
189
-                    "event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
190
-            }
191
-        }
192
-        // EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
193
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
194
-        if ( ! empty($date_formats) && is_array($date_formats)) {
195
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
196
-        } else {
197
-            //set default formats for date and time
198
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
199
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
200
-        }
201
-        //if db model is instantiating
202
-        if ($bydb) {
203
-            //client code has indicated these field values are from the database
204
-            foreach ($model_fields as $fieldName => $field) {
205
-                $this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
206
-            }
207
-        } else {
208
-            //we're constructing a brand
209
-            //new instance of the model object. Generally, this means we'll need to do more field validation
210
-            foreach ($model_fields as $fieldName => $field) {
211
-                $this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
212
-            }
213
-        }
214
-        //remember what values were passed to this constructor
215
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
216
-        //remember in entity mapper
217
-        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
218
-            $model->add_to_entity_map($this);
219
-        }
220
-        //setup all the relations
221
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
222
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
223
-                $this->_model_relations[$relation_name] = null;
224
-            } else {
225
-                $this->_model_relations[$relation_name] = array();
226
-            }
227
-        }
228
-        /**
229
-         * Action done at the end of each model object construction
230
-         *
231
-         * @param EE_Base_Class $this the model object just created
232
-         */
233
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
234
-    }
235
-
236
-
237
-
238
-    /**
239
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
240
-     *
241
-     * @return boolean
242
-     */
243
-    public function allow_persist()
244
-    {
245
-        return $this->_allow_persist;
246
-    }
247
-
248
-
249
-
250
-    /**
251
-     * Sets whether or not this model object should be allowed to be saved to the DB.
252
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
253
-     * you got new information that somehow made you change your mind.
254
-     *
255
-     * @param boolean $allow_persist
256
-     * @return boolean
257
-     */
258
-    public function set_allow_persist($allow_persist)
259
-    {
260
-        return $this->_allow_persist = $allow_persist;
261
-    }
262
-
263
-
264
-
265
-    /**
266
-     * Gets the field's original value when this object was constructed during this request.
267
-     * This can be helpful when determining if a model object has changed or not
268
-     *
269
-     * @param string $field_name
270
-     * @return mixed|null
271
-     * @throws \EE_Error
272
-     */
273
-    public function get_original($field_name)
274
-    {
275
-        if (isset($this->_props_n_values_provided_in_constructor[$field_name])
276
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
277
-        ) {
278
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
279
-        } else {
280
-            return null;
281
-        }
282
-    }
283
-
284
-
285
-
286
-    /**
287
-     * @param EE_Base_Class $obj
288
-     * @return string
289
-     */
290
-    public function get_class($obj)
291
-    {
292
-        return get_class($obj);
293
-    }
294
-
295
-
296
-
297
-    /**
298
-     * Overrides parent because parent expects old models.
299
-     * This also doesn't do any validation, and won't work for serialized arrays
300
-     *
301
-     * @param    string $field_name
302
-     * @param    mixed  $field_value
303
-     * @param bool      $use_default
304
-     * @throws \EE_Error
305
-     */
306
-    public function set($field_name, $field_value, $use_default = false)
307
-    {
308
-        // if not using default and nothing has changed, and object has already been setup (has ID),
309
-        // then don't do anything
310
-        if (
311
-            ! $use_default
312
-            && $this->_fields[$field_name] === $field_value
313
-            && $this->ID()
314
-        ) {
315
-            return;
316
-        }
317
-        $model = $this->get_model();
318
-        $this->_has_changes = true;
319
-        $field_obj = $model->field_settings_for($field_name);
320
-        if ($field_obj instanceof EE_Model_Field_Base) {
321
-            //			if ( method_exists( $field_obj, 'set_timezone' )) {
322
-            if ($field_obj instanceof EE_Datetime_Field) {
323
-                $field_obj->set_timezone($this->_timezone);
324
-                $field_obj->set_date_format($this->_dt_frmt);
325
-                $field_obj->set_time_format($this->_tm_frmt);
326
-            }
327
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
328
-            //should the value be null?
329
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
330
-                $this->_fields[$field_name] = $field_obj->get_default_value();
331
-                /**
332
-                 * To save having to refactor all the models, if a default value is used for a
333
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
334
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
335
-                 * object.
336
-                 *
337
-                 * @since 4.6.10+
338
-                 */
339
-                if (
340
-                    $field_obj instanceof EE_Datetime_Field
341
-                    && $this->_fields[$field_name] !== null
342
-                    && ! $this->_fields[$field_name] instanceof DateTime
343
-                ) {
344
-                    empty($this->_fields[$field_name])
345
-                        ? $this->set($field_name, time())
346
-                        : $this->set($field_name, $this->_fields[$field_name]);
347
-                }
348
-            } else {
349
-                $this->_fields[$field_name] = $holder_of_value;
350
-            }
351
-            //if we're not in the constructor...
352
-            //now check if what we set was a primary key
353
-            if (
354
-                //note: props_n_values_provided_in_constructor is only set at the END of the constructor
355
-                $this->_props_n_values_provided_in_constructor
356
-                && $field_value
357
-                && $field_name === $model->primary_key_name()
358
-            ) {
359
-                //if so, we want all this object's fields to be filled either with
360
-                //what we've explicitly set on this model
361
-                //or what we have in the db
362
-                // echo "setting primary key!";
363
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
364
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
365
-                foreach ($fields_on_model as $field_obj) {
366
-                    if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
367
-                         && $field_obj->get_name() !== $field_name
368
-                    ) {
369
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
370
-                    }
371
-                }
372
-                //oh this model object has an ID? well make sure its in the entity mapper
373
-                $model->add_to_entity_map($this);
374
-            }
375
-            //let's unset any cache for this field_name from the $_cached_properties property.
376
-            $this->_clear_cached_property($field_name);
377
-        } else {
378
-            throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
379
-                "event_espresso"), $field_name));
380
-        }
381
-    }
382
-
383
-
384
-
385
-    /**
386
-     * This sets the field value on the db column if it exists for the given $column_name or
387
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
388
-     *
389
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
390
-     * @param string $field_name  Must be the exact column name.
391
-     * @param mixed  $field_value The value to set.
392
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
393
-     * @throws \EE_Error
394
-     */
395
-    public function set_field_or_extra_meta($field_name, $field_value)
396
-    {
397
-        if ($this->get_model()->has_field($field_name)) {
398
-            $this->set($field_name, $field_value);
399
-            return true;
400
-        } else {
401
-            //ensure this object is saved first so that extra meta can be properly related.
402
-            $this->save();
403
-            return $this->update_extra_meta($field_name, $field_value);
404
-        }
405
-    }
406
-
407
-
408
-
409
-    /**
410
-     * This retrieves the value of the db column set on this class or if that's not present
411
-     * it will attempt to retrieve from extra_meta if found.
412
-     * Example Usage:
413
-     * Via EE_Message child class:
414
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
415
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
416
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
417
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
418
-     * value for those extra fields dynamically via the EE_message object.
419
-     *
420
-     * @param  string $field_name expecting the fully qualified field name.
421
-     * @return mixed|null  value for the field if found.  null if not found.
422
-     * @throws \EE_Error
423
-     */
424
-    public function get_field_or_extra_meta($field_name)
425
-    {
426
-        if ($this->get_model()->has_field($field_name)) {
427
-            $column_value = $this->get($field_name);
428
-        } else {
429
-            //This isn't a column in the main table, let's see if it is in the extra meta.
430
-            $column_value = $this->get_extra_meta($field_name, true, null);
431
-        }
432
-        return $column_value;
433
-    }
434
-
435
-
436
-
437
-    /**
438
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
439
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
440
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
441
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
442
-     *
443
-     * @access public
444
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
445
-     * @return void
446
-     * @throws \EE_Error
447
-     */
448
-    public function set_timezone($timezone = '')
449
-    {
450
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
451
-        //make sure we clear all cached properties because they won't be relevant now
452
-        $this->_clear_cached_properties();
453
-        //make sure we update field settings and the date for all EE_Datetime_Fields
454
-        $model_fields = $this->get_model()->field_settings(false);
455
-        foreach ($model_fields as $field_name => $field_obj) {
456
-            if ($field_obj instanceof EE_Datetime_Field) {
457
-                $field_obj->set_timezone($this->_timezone);
458
-                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
459
-                    $this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
460
-                }
461
-            }
462
-        }
463
-    }
464
-
465
-
466
-
467
-    /**
468
-     * This just returns whatever is set for the current timezone.
469
-     *
470
-     * @access public
471
-     * @return string timezone string
472
-     */
473
-    public function get_timezone()
474
-    {
475
-        return $this->_timezone;
476
-    }
477
-
478
-
479
-
480
-    /**
481
-     * This sets the internal date format to what is sent in to be used as the new default for the class
482
-     * internally instead of wp set date format options
483
-     *
484
-     * @since 4.6
485
-     * @param string $format should be a format recognizable by PHP date() functions.
486
-     */
487
-    public function set_date_format($format)
488
-    {
489
-        $this->_dt_frmt = $format;
490
-        //clear cached_properties because they won't be relevant now.
491
-        $this->_clear_cached_properties();
492
-    }
493
-
494
-
495
-
496
-    /**
497
-     * This sets the internal time format string to what is sent in to be used as the new default for the
498
-     * class internally instead of wp set time format options.
499
-     *
500
-     * @since 4.6
501
-     * @param string $format should be a format recognizable by PHP date() functions.
502
-     */
503
-    public function set_time_format($format)
504
-    {
505
-        $this->_tm_frmt = $format;
506
-        //clear cached_properties because they won't be relevant now.
507
-        $this->_clear_cached_properties();
508
-    }
509
-
510
-
511
-
512
-    /**
513
-     * This returns the current internal set format for the date and time formats.
514
-     *
515
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
516
-     *                             where the first value is the date format and the second value is the time format.
517
-     * @return mixed string|array
518
-     */
519
-    public function get_format($full = true)
520
-    {
521
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
522
-    }
523
-
524
-
525
-
526
-    /**
527
-     * cache
528
-     * stores the passed model object on the current model object.
529
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
530
-     *
531
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
532
-     *                                       'Registration' associated with this model object
533
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
534
-     *                                       that could be a payment or a registration)
535
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
536
-     *                                       items which will be stored in an array on this object
537
-     * @throws EE_Error
538
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
539
-     *                  related thing, no array)
540
-     */
541
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
542
-    {
543
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
544
-        if ( ! $object_to_cache instanceof EE_Base_Class) {
545
-            return false;
546
-        }
547
-        // also get "how" the object is related, or throw an error
548
-        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
549
-            throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
550
-                $relationName, get_class($this)));
551
-        }
552
-        // how many things are related ?
553
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
554
-            // if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
555
-            // so for these model objects just set it to be cached
556
-            $this->_model_relations[$relationName] = $object_to_cache;
557
-            $return = true;
558
-        } else {
559
-            // otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
560
-            // eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
561
-            if ( ! is_array($this->_model_relations[$relationName])) {
562
-                // if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
563
-                $this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
564
-                    ? array($this->_model_relations[$relationName]) : array();
565
-            }
566
-            // first check for a cache_id which is normally empty
567
-            if ( ! empty($cache_id)) {
568
-                // if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
569
-                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
570
-                $return = $cache_id;
571
-            } elseif ($object_to_cache->ID()) {
572
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
573
-                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
574
-                $return = $object_to_cache->ID();
575
-            } else {
576
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
577
-                $this->_model_relations[$relationName][] = $object_to_cache;
578
-                // move the internal pointer to the end of the array
579
-                end($this->_model_relations[$relationName]);
580
-                // and grab the key so that we can return it
581
-                $return = key($this->_model_relations[$relationName]);
582
-            }
583
-        }
584
-        return $return;
585
-    }
586
-
587
-
588
-
589
-    /**
590
-     * For adding an item to the cached_properties property.
591
-     *
592
-     * @access protected
593
-     * @param string      $fieldname the property item the corresponding value is for.
594
-     * @param mixed       $value     The value we are caching.
595
-     * @param string|null $cache_type
596
-     * @return void
597
-     * @throws \EE_Error
598
-     */
599
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
600
-    {
601
-        //first make sure this property exists
602
-        $this->get_model()->field_settings_for($fieldname);
603
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
604
-        $this->_cached_properties[$fieldname][$cache_type] = $value;
605
-    }
606
-
607
-
608
-
609
-    /**
610
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
611
-     * This also SETS the cache if we return the actual property!
612
-     *
613
-     * @param string $fieldname        the name of the property we're trying to retrieve
614
-     * @param bool   $pretty
615
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
616
-     *                                 (in cases where the same property may be used for different outputs
617
-     *                                 - i.e. datetime, money etc.)
618
-     *                                 It can also accept certain pre-defined "schema" strings
619
-     *                                 to define how to output the property.
620
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
621
-     * @return mixed                   whatever the value for the property is we're retrieving
622
-     * @throws \EE_Error
623
-     */
624
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
625
-    {
626
-        //verify the field exists
627
-        $model = $this->get_model();
628
-        $model->field_settings_for($fieldname);
629
-        $cache_type = $pretty ? 'pretty' : 'standard';
630
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
631
-        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
632
-            return $this->_cached_properties[$fieldname][$cache_type];
633
-        }
634
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
635
-        $this->_set_cached_property($fieldname, $value, $cache_type);
636
-        return $value;
637
-    }
638
-
639
-
640
-
641
-    /**
642
-     * If the cache didn't fetch the needed item, this fetches it.
643
-     * @param string $fieldname
644
-     * @param bool $pretty
645
-     * @param string $extra_cache_ref
646
-     * @return mixed
647
-     */
648
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
649
-    {
650
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
651
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
652
-        if ($field_obj instanceof EE_Datetime_Field) {
653
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
654
-        }
655
-        if ( ! isset($this->_fields[$fieldname])) {
656
-            $this->_fields[$fieldname] = null;
657
-        }
658
-        $value = $pretty
659
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
660
-            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
661
-        return $value;
662
-    }
663
-
664
-
665
-
666
-    /**
667
-     * set timezone, formats, and output for EE_Datetime_Field objects
668
-     *
669
-     * @param \EE_Datetime_Field $datetime_field
670
-     * @param bool               $pretty
671
-     * @param null $date_or_time
672
-     * @return void
673
-     * @throws \EE_Error
674
-     */
675
-    protected function _prepare_datetime_field(
676
-        EE_Datetime_Field $datetime_field,
677
-        $pretty = false,
678
-        $date_or_time = null
679
-    ) {
680
-        $datetime_field->set_timezone($this->_timezone);
681
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
682
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
683
-        //set the output returned
684
-        switch ($date_or_time) {
685
-            case 'D' :
686
-                $datetime_field->set_date_time_output('date');
687
-                break;
688
-            case 'T' :
689
-                $datetime_field->set_date_time_output('time');
690
-                break;
691
-            default :
692
-                $datetime_field->set_date_time_output();
693
-        }
694
-    }
695
-
696
-
697
-
698
-    /**
699
-     * This just takes care of clearing out the cached_properties
700
-     *
701
-     * @return void
702
-     */
703
-    protected function _clear_cached_properties()
704
-    {
705
-        $this->_cached_properties = array();
706
-    }
707
-
708
-
709
-
710
-    /**
711
-     * This just clears out ONE property if it exists in the cache
712
-     *
713
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
714
-     * @return void
715
-     */
716
-    protected function _clear_cached_property($property_name)
717
-    {
718
-        if (isset($this->_cached_properties[$property_name])) {
719
-            unset($this->_cached_properties[$property_name]);
720
-        }
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * Ensures that this related thing is a model object.
727
-     *
728
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
729
-     * @param string $model_name   name of the related thing, eg 'Attendee',
730
-     * @return EE_Base_Class
731
-     * @throws \EE_Error
732
-     */
733
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
734
-    {
735
-        $other_model_instance = self::_get_model_instance_with_name(
736
-            self::_get_model_classname($model_name),
737
-            $this->_timezone
738
-        );
739
-        return $other_model_instance->ensure_is_obj($object_or_id);
740
-    }
741
-
742
-
743
-
744
-    /**
745
-     * Forgets the cached model of the given relation Name. So the next time we request it,
746
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
747
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
748
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
749
-     *
750
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
751
-     *                                                     Eg 'Registration'
752
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
753
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
754
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
755
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
756
-     *                                                     this is HasMany or HABTM.
757
-     * @throws EE_Error
758
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
759
-     *                       relation from all
760
-     */
761
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
762
-    {
763
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
764
-        $index_in_cache = '';
765
-        if ( ! $relationship_to_model) {
766
-            throw new EE_Error(
767
-                sprintf(
768
-                    __("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
769
-                    $relationName,
770
-                    get_class($this)
771
-                )
772
-            );
773
-        }
774
-        if ($clear_all) {
775
-            $obj_removed = true;
776
-            $this->_model_relations[$relationName] = null;
777
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
778
-            $obj_removed = $this->_model_relations[$relationName];
779
-            $this->_model_relations[$relationName] = null;
780
-        } else {
781
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
782
-                && $object_to_remove_or_index_into_array->ID()
783
-            ) {
784
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
785
-                if (is_array($this->_model_relations[$relationName])
786
-                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
787
-                ) {
788
-                    $index_found_at = null;
789
-                    //find this object in the array even though it has a different key
790
-                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
791
-                        if (
792
-                            $obj instanceof EE_Base_Class
793
-                            && (
794
-                                $obj == $object_to_remove_or_index_into_array
795
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
796
-                            )
797
-                        ) {
798
-                            $index_found_at = $index;
799
-                            break;
800
-                        }
801
-                    }
802
-                    if ($index_found_at) {
803
-                        $index_in_cache = $index_found_at;
804
-                    } else {
805
-                        //it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
806
-                        //if it wasn't in it to begin with. So we're done
807
-                        return $object_to_remove_or_index_into_array;
808
-                    }
809
-                }
810
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
811
-                //so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
812
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
813
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
814
-                        $index_in_cache = $index;
815
-                    }
816
-                }
817
-            } else {
818
-                $index_in_cache = $object_to_remove_or_index_into_array;
819
-            }
820
-            //supposedly we've found it. But it could just be that the client code
821
-            //provided a bad index/object
822
-            if (
823
-            isset(
824
-                $this->_model_relations[$relationName],
825
-                $this->_model_relations[$relationName][$index_in_cache]
826
-            )
827
-            ) {
828
-                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
829
-                unset($this->_model_relations[$relationName][$index_in_cache]);
830
-            } else {
831
-                //that thing was never cached anyways.
832
-                $obj_removed = null;
833
-            }
834
-        }
835
-        return $obj_removed;
836
-    }
837
-
838
-
839
-
840
-    /**
841
-     * update_cache_after_object_save
842
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
843
-     * obtained after being saved to the db
844
-     *
845
-     * @param string         $relationName       - the type of object that is cached
846
-     * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
847
-     * @param string         $current_cache_id   - the ID that was used when originally caching the object
848
-     * @return boolean TRUE on success, FALSE on fail
849
-     * @throws \EE_Error
850
-     */
851
-    public function update_cache_after_object_save(
852
-        $relationName,
853
-        EE_Base_Class $newly_saved_object,
854
-        $current_cache_id = ''
855
-    ) {
856
-        // verify that incoming object is of the correct type
857
-        $obj_class = 'EE_' . $relationName;
858
-        if ($newly_saved_object instanceof $obj_class) {
859
-            /* @type EE_Base_Class $newly_saved_object */
860
-            // now get the type of relation
861
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
862
-            // if this is a 1:1 relationship
863
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
864
-                // then just replace the cached object with the newly saved object
865
-                $this->_model_relations[$relationName] = $newly_saved_object;
866
-                return true;
867
-                // or if it's some kind of sordid feral polyamorous relationship...
868
-            } elseif (is_array($this->_model_relations[$relationName])
869
-                      && isset($this->_model_relations[$relationName][$current_cache_id])
870
-            ) {
871
-                // then remove the current cached item
872
-                unset($this->_model_relations[$relationName][$current_cache_id]);
873
-                // and cache the newly saved object using it's new ID
874
-                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
875
-                return true;
876
-            }
877
-        }
878
-        return false;
879
-    }
880
-
881
-
882
-
883
-    /**
884
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
885
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
886
-     *
887
-     * @param string $relationName
888
-     * @return EE_Base_Class
889
-     */
890
-    public function get_one_from_cache($relationName)
891
-    {
892
-        $cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
893
-            : null;
894
-        if (is_array($cached_array_or_object)) {
895
-            return array_shift($cached_array_or_object);
896
-        } else {
897
-            return $cached_array_or_object;
898
-        }
899
-    }
900
-
901
-
902
-
903
-    /**
904
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
905
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
906
-     *
907
-     * @param string $relationName
908
-     * @throws \EE_Error
909
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
910
-     */
911
-    public function get_all_from_cache($relationName)
912
-    {
913
-        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
914
-        // if the result is not an array, but exists, make it an array
915
-        $objects = is_array($objects) ? $objects : array($objects);
916
-        //bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
917
-        //basically, if this model object was stored in the session, and these cached model objects
918
-        //already have IDs, let's make sure they're in their model's entity mapper
919
-        //otherwise we will have duplicates next time we call
920
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
921
-        $model = EE_Registry::instance()->load_model($relationName);
922
-        foreach ($objects as $model_object) {
923
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
924
-                //ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
925
-                if ($model_object->ID()) {
926
-                    $model->add_to_entity_map($model_object);
927
-                }
928
-            } else {
929
-                throw new EE_Error(
930
-                    sprintf(
931
-                        __(
932
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
933
-                            'event_espresso'
934
-                        ),
935
-                        $relationName,
936
-                        gettype($model_object)
937
-                    )
938
-                );
939
-            }
940
-        }
941
-        return $objects;
942
-    }
943
-
944
-
945
-
946
-    /**
947
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
948
-     * matching the given query conditions.
949
-     *
950
-     * @param null  $field_to_order_by  What field is being used as the reference point.
951
-     * @param int   $limit              How many objects to return.
952
-     * @param array $query_params       Any additional conditions on the query.
953
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
954
-     *                                  you can indicate just the columns you want returned
955
-     * @return array|EE_Base_Class[]
956
-     * @throws \EE_Error
957
-     */
958
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
959
-    {
960
-        $model = $this->get_model();
961
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
962
-            ? $model->get_primary_key_field()->get_name()
963
-            : $field_to_order_by;
964
-        $current_value = ! empty($field) ? $this->get($field) : null;
965
-        if (empty($field) || empty($current_value)) {
966
-            return array();
967
-        }
968
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
969
-    }
970
-
971
-
972
-
973
-    /**
974
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
975
-     * matching the given query conditions.
976
-     *
977
-     * @param null  $field_to_order_by  What field is being used as the reference point.
978
-     * @param int   $limit              How many objects to return.
979
-     * @param array $query_params       Any additional conditions on the query.
980
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
981
-     *                                  you can indicate just the columns you want returned
982
-     * @return array|EE_Base_Class[]
983
-     * @throws \EE_Error
984
-     */
985
-    public function previous_x(
986
-        $field_to_order_by = null,
987
-        $limit = 1,
988
-        $query_params = array(),
989
-        $columns_to_select = null
990
-    ) {
991
-        $model = $this->get_model();
992
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
993
-            ? $model->get_primary_key_field()->get_name()
994
-            : $field_to_order_by;
995
-        $current_value = ! empty($field) ? $this->get($field) : null;
996
-        if (empty($field) || empty($current_value)) {
997
-            return array();
998
-        }
999
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1000
-    }
1001
-
1002
-
1003
-
1004
-    /**
1005
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1006
-     * matching the given query conditions.
1007
-     *
1008
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1009
-     * @param array $query_params       Any additional conditions on the query.
1010
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1011
-     *                                  you can indicate just the columns you want returned
1012
-     * @return array|EE_Base_Class
1013
-     * @throws \EE_Error
1014
-     */
1015
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1016
-    {
1017
-        $model = $this->get_model();
1018
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1019
-            ? $model->get_primary_key_field()->get_name()
1020
-            : $field_to_order_by;
1021
-        $current_value = ! empty($field) ? $this->get($field) : null;
1022
-        if (empty($field) || empty($current_value)) {
1023
-            return array();
1024
-        }
1025
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1026
-    }
1027
-
1028
-
1029
-
1030
-    /**
1031
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1032
-     * matching the given query conditions.
1033
-     *
1034
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1035
-     * @param array $query_params       Any additional conditions on the query.
1036
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1037
-     *                                  you can indicate just the column you want returned
1038
-     * @return array|EE_Base_Class
1039
-     * @throws \EE_Error
1040
-     */
1041
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1042
-    {
1043
-        $model = $this->get_model();
1044
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1045
-            ? $model->get_primary_key_field()->get_name()
1046
-            : $field_to_order_by;
1047
-        $current_value = ! empty($field) ? $this->get($field) : null;
1048
-        if (empty($field) || empty($current_value)) {
1049
-            return array();
1050
-        }
1051
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1052
-    }
1053
-
1054
-
1055
-
1056
-    /**
1057
-     * Overrides parent because parent expects old models.
1058
-     * This also doesn't do any validation, and won't work for serialized arrays
1059
-     *
1060
-     * @param string $field_name
1061
-     * @param mixed  $field_value_from_db
1062
-     * @throws \EE_Error
1063
-     */
1064
-    public function set_from_db($field_name, $field_value_from_db)
1065
-    {
1066
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1067
-        if ($field_obj instanceof EE_Model_Field_Base) {
1068
-            //you would think the DB has no NULLs for non-null label fields right? wrong!
1069
-            //eg, a CPT model object could have an entry in the posts table, but no
1070
-            //entry in the meta table. Meaning that all its columns in the meta table
1071
-            //are null! yikes! so when we find one like that, use defaults for its meta columns
1072
-            if ($field_value_from_db === null) {
1073
-                if ($field_obj->is_nullable()) {
1074
-                    //if the field allows nulls, then let it be null
1075
-                    $field_value = null;
1076
-                } else {
1077
-                    $field_value = $field_obj->get_default_value();
1078
-                }
1079
-            } else {
1080
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1081
-            }
1082
-            $this->_fields[$field_name] = $field_value;
1083
-            $this->_clear_cached_property($field_name);
1084
-        }
1085
-    }
1086
-
1087
-
1088
-
1089
-    /**
1090
-     * verifies that the specified field is of the correct type
1091
-     *
1092
-     * @param string $field_name
1093
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1094
-     *                                (in cases where the same property may be used for different outputs
1095
-     *                                - i.e. datetime, money etc.)
1096
-     * @return mixed
1097
-     * @throws \EE_Error
1098
-     */
1099
-    public function get($field_name, $extra_cache_ref = null)
1100
-    {
1101
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1102
-    }
1103
-
1104
-
1105
-
1106
-    /**
1107
-     * This method simply returns the RAW unprocessed value for the given property in this class
1108
-     *
1109
-     * @param  string $field_name A valid fieldname
1110
-     * @return mixed              Whatever the raw value stored on the property is.
1111
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1112
-     */
1113
-    public function get_raw($field_name)
1114
-    {
1115
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1116
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1117
-            ? $this->_fields[$field_name]->format('U')
1118
-            : $this->_fields[$field_name];
1119
-    }
1120
-
1121
-
1122
-
1123
-    /**
1124
-     * This is used to return the internal DateTime object used for a field that is a
1125
-     * EE_Datetime_Field.
1126
-     *
1127
-     * @param string $field_name               The field name retrieving the DateTime object.
1128
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1129
-     * @throws \EE_Error
1130
-     *                                         an error is set and false returned.  If the field IS an
1131
-     *                                         EE_Datetime_Field and but the field value is null, then
1132
-     *                                         just null is returned (because that indicates that likely
1133
-     *                                         this field is nullable).
1134
-     */
1135
-    public function get_DateTime_object($field_name)
1136
-    {
1137
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1138
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1139
-            EE_Error::add_error(
1140
-                sprintf(
1141
-                    __(
1142
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1143
-                        'event_espresso'
1144
-                    ),
1145
-                    $field_name
1146
-                ),
1147
-                __FILE__,
1148
-                __FUNCTION__,
1149
-                __LINE__
1150
-            );
1151
-            return false;
1152
-        }
1153
-        return $this->_fields[$field_name];
1154
-    }
1155
-
1156
-
1157
-
1158
-    /**
1159
-     * To be used in template to immediately echo out the value, and format it for output.
1160
-     * Eg, should call stripslashes and whatnot before echoing
1161
-     *
1162
-     * @param string $field_name      the name of the field as it appears in the DB
1163
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1164
-     *                                (in cases where the same property may be used for different outputs
1165
-     *                                - i.e. datetime, money etc.)
1166
-     * @return void
1167
-     * @throws \EE_Error
1168
-     */
1169
-    public function e($field_name, $extra_cache_ref = null)
1170
-    {
1171
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1172
-    }
1173
-
1174
-
1175
-
1176
-    /**
1177
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1178
-     * can be easily used as the value of form input.
1179
-     *
1180
-     * @param string $field_name
1181
-     * @return void
1182
-     * @throws \EE_Error
1183
-     */
1184
-    public function f($field_name)
1185
-    {
1186
-        $this->e($field_name, 'form_input');
1187
-    }
1188
-
1189
-
1190
-
1191
-    /**
1192
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1193
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1194
-     * to see what options are available.
1195
-     * @param string $field_name
1196
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1197
-     *                                (in cases where the same property may be used for different outputs
1198
-     *                                - i.e. datetime, money etc.)
1199
-     * @return mixed
1200
-     * @throws \EE_Error
1201
-     */
1202
-    public function get_pretty($field_name, $extra_cache_ref = null)
1203
-    {
1204
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1205
-    }
1206
-
1207
-
1208
-
1209
-    /**
1210
-     * This simply returns the datetime for the given field name
1211
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1212
-     * (and the equivalent e_date, e_time, e_datetime).
1213
-     *
1214
-     * @access   protected
1215
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1216
-     * @param string   $dt_frmt      valid datetime format used for date
1217
-     *                               (if '' then we just use the default on the field,
1218
-     *                               if NULL we use the last-used format)
1219
-     * @param string   $tm_frmt      Same as above except this is for time format
1220
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1221
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1222
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1223
-     *                               if field is not a valid dtt field, or void if echoing
1224
-     * @throws \EE_Error
1225
-     */
1226
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1227
-    {
1228
-        // clear cached property
1229
-        $this->_clear_cached_property($field_name);
1230
-        //reset format properties because they are used in get()
1231
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1232
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1233
-        if ($echo) {
1234
-            $this->e($field_name, $date_or_time);
1235
-            return '';
1236
-        }
1237
-        return $this->get($field_name, $date_or_time);
1238
-    }
1239
-
1240
-
1241
-
1242
-    /**
1243
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1244
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1245
-     * other echoes the pretty value for dtt)
1246
-     *
1247
-     * @param  string $field_name name of model object datetime field holding the value
1248
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1249
-     * @return string            datetime value formatted
1250
-     * @throws \EE_Error
1251
-     */
1252
-    public function get_date($field_name, $format = '')
1253
-    {
1254
-        return $this->_get_datetime($field_name, $format, null, 'D');
1255
-    }
1256
-
1257
-
1258
-
1259
-    /**
1260
-     * @param      $field_name
1261
-     * @param string $format
1262
-     * @throws \EE_Error
1263
-     */
1264
-    public function e_date($field_name, $format = '')
1265
-    {
1266
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1267
-    }
1268
-
1269
-
1270
-
1271
-    /**
1272
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1273
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1274
-     * other echoes the pretty value for dtt)
1275
-     *
1276
-     * @param  string $field_name name of model object datetime field holding the value
1277
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1278
-     * @return string             datetime value formatted
1279
-     * @throws \EE_Error
1280
-     */
1281
-    public function get_time($field_name, $format = '')
1282
-    {
1283
-        return $this->_get_datetime($field_name, null, $format, 'T');
1284
-    }
1285
-
1286
-
1287
-
1288
-    /**
1289
-     * @param      $field_name
1290
-     * @param string $format
1291
-     * @throws \EE_Error
1292
-     */
1293
-    public function e_time($field_name, $format = '')
1294
-    {
1295
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1296
-    }
1297
-
1298
-
1299
-
1300
-    /**
1301
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1302
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1303
-     * other echoes the pretty value for dtt)
1304
-     *
1305
-     * @param  string $field_name name of model object datetime field holding the value
1306
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1307
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1308
-     * @return string             datetime value formatted
1309
-     * @throws \EE_Error
1310
-     */
1311
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1312
-    {
1313
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1314
-    }
1315
-
1316
-
1317
-
1318
-    /**
1319
-     * @param string $field_name
1320
-     * @param string $dt_frmt
1321
-     * @param string $tm_frmt
1322
-     * @throws \EE_Error
1323
-     */
1324
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1325
-    {
1326
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1327
-    }
1328
-
1329
-
1330
-
1331
-    /**
1332
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1333
-     *
1334
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1335
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1336
-     *                           on the object will be used.
1337
-     * @return string Date and time string in set locale or false if no field exists for the given
1338
-     * @throws \EE_Error
1339
-     *                           field name.
1340
-     */
1341
-    public function get_i18n_datetime($field_name, $format = '')
1342
-    {
1343
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1344
-        return date_i18n(
1345
-            $format,
1346
-            EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1347
-        );
1348
-    }
1349
-
1350
-
1351
-
1352
-    /**
1353
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1354
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1355
-     * thrown.
1356
-     *
1357
-     * @param  string $field_name The field name being checked
1358
-     * @throws EE_Error
1359
-     * @return EE_Datetime_Field
1360
-     */
1361
-    protected function _get_dtt_field_settings($field_name)
1362
-    {
1363
-        $field = $this->get_model()->field_settings_for($field_name);
1364
-        //check if field is dtt
1365
-        if ($field instanceof EE_Datetime_Field) {
1366
-            return $field;
1367
-        } else {
1368
-            throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1369
-                'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1370
-        }
1371
-    }
1372
-
1373
-
1374
-
1375
-
1376
-    /**
1377
-     * NOTE ABOUT BELOW:
1378
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1379
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1380
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1381
-     * method and make sure you send the entire datetime value for setting.
1382
-     */
1383
-    /**
1384
-     * sets the time on a datetime property
1385
-     *
1386
-     * @access protected
1387
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1388
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1389
-     * @throws \EE_Error
1390
-     */
1391
-    protected function _set_time_for($time, $fieldname)
1392
-    {
1393
-        $this->_set_date_time('T', $time, $fieldname);
1394
-    }
1395
-
1396
-
1397
-
1398
-    /**
1399
-     * sets the date on a datetime property
1400
-     *
1401
-     * @access protected
1402
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1403
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1404
-     * @throws \EE_Error
1405
-     */
1406
-    protected function _set_date_for($date, $fieldname)
1407
-    {
1408
-        $this->_set_date_time('D', $date, $fieldname);
1409
-    }
1410
-
1411
-
1412
-
1413
-    /**
1414
-     * This takes care of setting a date or time independently on a given model object property. This method also
1415
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1416
-     *
1417
-     * @access protected
1418
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1419
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1420
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1421
-     *                                        EE_Datetime_Field property)
1422
-     * @throws \EE_Error
1423
-     */
1424
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1425
-    {
1426
-        $field = $this->_get_dtt_field_settings($fieldname);
1427
-        $field->set_timezone($this->_timezone);
1428
-        $field->set_date_format($this->_dt_frmt);
1429
-        $field->set_time_format($this->_tm_frmt);
1430
-        switch ($what) {
1431
-            case 'T' :
1432
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1433
-                    $datetime_value,
1434
-                    $this->_fields[$fieldname]
1435
-                );
1436
-                break;
1437
-            case 'D' :
1438
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1439
-                    $datetime_value,
1440
-                    $this->_fields[$fieldname]
1441
-                );
1442
-                break;
1443
-            case 'B' :
1444
-                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1445
-                break;
1446
-        }
1447
-        $this->_clear_cached_property($fieldname);
1448
-    }
1449
-
1450
-
1451
-
1452
-    /**
1453
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1454
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1455
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1456
-     * that could lead to some unexpected results!
1457
-     *
1458
-     * @access public
1459
-     * @param string               $field_name This is the name of the field on the object that contains the date/time
1460
-     *                                         value being returned.
1461
-     * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1462
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1463
-     * @param string               $prepend    You can include something to prepend on the timestamp
1464
-     * @param string               $append     You can include something to append on the timestamp
1465
-     * @throws EE_Error
1466
-     * @return string timestamp
1467
-     */
1468
-    public function display_in_my_timezone(
1469
-        $field_name,
1470
-        $callback = 'get_datetime',
1471
-        $args = null,
1472
-        $prepend = '',
1473
-        $append = ''
1474
-    ) {
1475
-        $timezone = EEH_DTT_Helper::get_timezone();
1476
-        if ($timezone === $this->_timezone) {
1477
-            return '';
1478
-        }
1479
-        $original_timezone = $this->_timezone;
1480
-        $this->set_timezone($timezone);
1481
-        $fn = (array)$field_name;
1482
-        $args = array_merge($fn, (array)$args);
1483
-        if ( ! method_exists($this, $callback)) {
1484
-            throw new EE_Error(
1485
-                sprintf(
1486
-                    __(
1487
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1488
-                        'event_espresso'
1489
-                    ),
1490
-                    $callback
1491
-                )
1492
-            );
1493
-        }
1494
-        $args = (array)$args;
1495
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1496
-        $this->set_timezone($original_timezone);
1497
-        return $return;
1498
-    }
1499
-
1500
-
1501
-
1502
-    /**
1503
-     * Deletes this model object.
1504
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1505
-     * override
1506
-     * `EE_Base_Class::_delete` NOT this class.
1507
-     *
1508
-     * @return boolean | int
1509
-     * @throws \EE_Error
1510
-     */
1511
-    public function delete()
1512
-    {
1513
-        /**
1514
-         * Called just before the `EE_Base_Class::_delete` method call.
1515
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1516
-         * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1517
-         * soft deletes (trash) the object and does not permanently delete it.
1518
-         *
1519
-         * @param EE_Base_Class $model_object about to be 'deleted'
1520
-         */
1521
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1522
-        $result = $this->_delete();
1523
-        /**
1524
-         * Called just after the `EE_Base_Class::_delete` method call.
1525
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1526
-         * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1527
-         * soft deletes (trash) the object and does not permanently delete it.
1528
-         *
1529
-         * @param EE_Base_Class $model_object that was just 'deleted'
1530
-         * @param boolean       $result
1531
-         */
1532
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1533
-        return $result;
1534
-    }
1535
-
1536
-
1537
-
1538
-    /**
1539
-     * Calls the specific delete method for the instantiated class.
1540
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1541
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1542
-     * `EE_Base_Class::delete`
1543
-     *
1544
-     * @return bool|int
1545
-     * @throws \EE_Error
1546
-     */
1547
-    protected function _delete()
1548
-    {
1549
-        return $this->delete_permanently();
1550
-    }
1551
-
1552
-
1553
-
1554
-    /**
1555
-     * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1556
-     * error)
1557
-     *
1558
-     * @return bool | int
1559
-     * @throws \EE_Error
1560
-     */
1561
-    public function delete_permanently()
1562
-    {
1563
-        /**
1564
-         * Called just before HARD deleting a model object
1565
-         *
1566
-         * @param EE_Base_Class $model_object about to be 'deleted'
1567
-         */
1568
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1569
-        $model = $this->get_model();
1570
-        $result = $model->delete_permanently_by_ID($this->ID());
1571
-        $this->refresh_cache_of_related_objects();
1572
-        /**
1573
-         * Called just after HARD deleting a model object
1574
-         *
1575
-         * @param EE_Base_Class $model_object that was just 'deleted'
1576
-         * @param boolean       $result
1577
-         */
1578
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1579
-        return $result;
1580
-    }
1581
-
1582
-
1583
-
1584
-    /**
1585
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1586
-     * related model objects
1587
-     *
1588
-     * @throws \EE_Error
1589
-     */
1590
-    public function refresh_cache_of_related_objects()
1591
-    {
1592
-        $model = $this->get_model();
1593
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1594
-            if ( ! empty($this->_model_relations[$relation_name])) {
1595
-                $related_objects = $this->_model_relations[$relation_name];
1596
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1597
-                    //this relation only stores a single model object, not an array
1598
-                    //but let's make it consistent
1599
-                    $related_objects = array($related_objects);
1600
-                }
1601
-                foreach ($related_objects as $related_object) {
1602
-                    //only refresh their cache if they're in memory
1603
-                    if ($related_object instanceof EE_Base_Class) {
1604
-                        $related_object->clear_cache($model->get_this_model_name(), $this);
1605
-                    }
1606
-                }
1607
-            }
1608
-        }
1609
-    }
1610
-
1611
-
1612
-
1613
-    /**
1614
-     *        Saves this object to the database. An array may be supplied to set some values on this
1615
-     * object just before saving.
1616
-     *
1617
-     * @access public
1618
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1619
-     *                                 if provided during the save() method (often client code will change the fields'
1620
-     *                                 values before calling save)
1621
-     * @throws \EE_Error
1622
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1623
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1624
-     */
1625
-    public function save($set_cols_n_values = array())
1626
-    {
1627
-        $model = $this->get_model();
1628
-        /**
1629
-         * Filters the fields we're about to save on the model object
1630
-         *
1631
-         * @param array         $set_cols_n_values
1632
-         * @param EE_Base_Class $model_object
1633
-         */
1634
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1635
-            $this);
1636
-        //set attributes as provided in $set_cols_n_values
1637
-        foreach ($set_cols_n_values as $column => $value) {
1638
-            $this->set($column, $value);
1639
-        }
1640
-        // no changes ? then don't do anything
1641
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1642
-            return 0;
1643
-        }
1644
-        /**
1645
-         * Saving a model object.
1646
-         * Before we perform a save, this action is fired.
1647
-         *
1648
-         * @param EE_Base_Class $model_object the model object about to be saved.
1649
-         */
1650
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1651
-        if ( ! $this->allow_persist()) {
1652
-            return 0;
1653
-        }
1654
-        //now get current attribute values
1655
-        $save_cols_n_values = $this->_fields;
1656
-        //if the object already has an ID, update it. Otherwise, insert it
1657
-        //also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1658
-        $old_assumption_concerning_value_preparation = $model
1659
-                                                            ->get_assumption_concerning_values_already_prepared_by_model_object();
1660
-        $model->assume_values_already_prepared_by_model_object(true);
1661
-        //does this model have an autoincrement PK?
1662
-        if ($model->has_primary_key_field()) {
1663
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1664
-                //ok check if it's set, if so: update; if not, insert
1665
-                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1666
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1667
-                } else {
1668
-                    unset($save_cols_n_values[$model->primary_key_name()]);
1669
-                    $results = $model->insert($save_cols_n_values);
1670
-                    if ($results) {
1671
-                        //if successful, set the primary key
1672
-                        //but don't use the normal SET method, because it will check if
1673
-                        //an item with the same ID exists in the mapper & db, then
1674
-                        //will find it in the db (because we just added it) and THAT object
1675
-                        //will get added to the mapper before we can add this one!
1676
-                        //but if we just avoid using the SET method, all that headache can be avoided
1677
-                        $pk_field_name = $model->primary_key_name();
1678
-                        $this->_fields[$pk_field_name] = $results;
1679
-                        $this->_clear_cached_property($pk_field_name);
1680
-                        $model->add_to_entity_map($this);
1681
-                        $this->_update_cached_related_model_objs_fks();
1682
-                    }
1683
-                }
1684
-            } else {//PK is NOT auto-increment
1685
-                //so check if one like it already exists in the db
1686
-                if ($model->exists_by_ID($this->ID())) {
1687
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1688
-                        throw new EE_Error(
1689
-                            sprintf(
1690
-                                __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1691
-                                    'event_espresso'),
1692
-                                get_class($this),
1693
-                                get_class($model) . '::instance()->add_to_entity_map()',
1694
-                                get_class($model) . '::instance()->get_one_by_ID()',
1695
-                                '<br />'
1696
-                            )
1697
-                        );
1698
-                    }
1699
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1700
-                } else {
1701
-                    $results = $model->insert($save_cols_n_values);
1702
-                    $this->_update_cached_related_model_objs_fks();
1703
-                }
1704
-            }
1705
-        } else {//there is NO primary key
1706
-            $already_in_db = false;
1707
-            foreach ($model->unique_indexes() as $index) {
1708
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1709
-                if ($model->exists(array($uniqueness_where_params))) {
1710
-                    $already_in_db = true;
1711
-                }
1712
-            }
1713
-            if ($already_in_db) {
1714
-                $combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1715
-                    $model->get_combined_primary_key_fields());
1716
-                $results = $model->update($save_cols_n_values, $combined_pk_fields_n_values);
1717
-            } else {
1718
-                $results = $model->insert($save_cols_n_values);
1719
-            }
1720
-        }
1721
-        //restore the old assumption about values being prepared by the model object
1722
-        $model
1723
-             ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1724
-        /**
1725
-         * After saving the model object this action is called
1726
-         *
1727
-         * @param EE_Base_Class $model_object which was just saved
1728
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1729
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1730
-         */
1731
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1732
-        $this->_has_changes = false;
1733
-        return $results;
1734
-    }
1735
-
1736
-
1737
-
1738
-    /**
1739
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1740
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1741
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1742
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1743
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1744
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1745
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1746
-     *
1747
-     * @return void
1748
-     * @throws \EE_Error
1749
-     */
1750
-    protected function _update_cached_related_model_objs_fks()
1751
-    {
1752
-        $model = $this->get_model();
1753
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1754
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1755
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1756
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1757
-                        $model->get_this_model_name()
1758
-                    );
1759
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1760
-                    if ($related_model_obj_in_cache->ID()) {
1761
-                        $related_model_obj_in_cache->save();
1762
-                    }
1763
-                }
1764
-            }
1765
-        }
1766
-    }
1767
-
1768
-
1769
-
1770
-    /**
1771
-     * Saves this model object and its NEW cached relations to the database.
1772
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1773
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1774
-     * because otherwise, there's a potential for infinite looping of saving
1775
-     * Saves the cached related model objects, and ensures the relation between them
1776
-     * and this object and properly setup
1777
-     *
1778
-     * @return int ID of new model object on save; 0 on failure+
1779
-     * @throws \EE_Error
1780
-     */
1781
-    public function save_new_cached_related_model_objs()
1782
-    {
1783
-        //make sure this has been saved
1784
-        if ( ! $this->ID()) {
1785
-            $id = $this->save();
1786
-        } else {
1787
-            $id = $this->ID();
1788
-        }
1789
-        //now save all the NEW cached model objects  (ie they don't exist in the DB)
1790
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1791
-            if ($this->_model_relations[$relationName]) {
1792
-                //is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1793
-                //or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1794
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1795
-                    //add a relation to that relation type (which saves the appropriate thing in the process)
1796
-                    //but ONLY if it DOES NOT exist in the DB
1797
-                    /* @var $related_model_obj EE_Base_Class */
1798
-                    $related_model_obj = $this->_model_relations[$relationName];
1799
-                    //					if( ! $related_model_obj->ID()){
1800
-                    $this->_add_relation_to($related_model_obj, $relationName);
1801
-                    $related_model_obj->save_new_cached_related_model_objs();
1802
-                    //					}
1803
-                } else {
1804
-                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1805
-                        //add a relation to that relation type (which saves the appropriate thing in the process)
1806
-                        //but ONLY if it DOES NOT exist in the DB
1807
-                        //						if( ! $related_model_obj->ID()){
1808
-                        $this->_add_relation_to($related_model_obj, $relationName);
1809
-                        $related_model_obj->save_new_cached_related_model_objs();
1810
-                        //						}
1811
-                    }
1812
-                }
1813
-            }
1814
-        }
1815
-        return $id;
1816
-    }
1817
-
1818
-
1819
-
1820
-    /**
1821
-     * for getting a model while instantiated.
1822
-     *
1823
-     * @return \EEM_Base | \EEM_CPT_Base
1824
-     */
1825
-    public function get_model()
1826
-    {
1827
-        if( ! $this->_model){
1828
-            $modelName = self::_get_model_classname(get_class($this));
1829
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
1830
-        } else {
1831
-            $this->_model->set_timezone($this->_timezone);
1832
-        }
1833
-
1834
-        return $this->_model;
1835
-    }
1836
-
1837
-
1838
-
1839
-    /**
1840
-     * @param $props_n_values
1841
-     * @param $classname
1842
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1843
-     * @throws \EE_Error
1844
-     */
1845
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1846
-    {
1847
-        //TODO: will not work for Term_Relationships because they have no PK!
1848
-        $primary_id_ref = self::_get_primary_key_name($classname);
1849
-        if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1850
-            $id = $props_n_values[$primary_id_ref];
1851
-            return self::_get_model($classname)->get_from_entity_map($id);
1852
-        }
1853
-        return false;
1854
-    }
1855
-
1856
-
1857
-
1858
-    /**
1859
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1860
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1861
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1862
-     * we return false.
1863
-     *
1864
-     * @param  array  $props_n_values   incoming array of properties and their values
1865
-     * @param  string $classname        the classname of the child class
1866
-     * @param null    $timezone
1867
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
1868
-     *                                  date_format and the second value is the time format
1869
-     * @return mixed (EE_Base_Class|bool)
1870
-     * @throws \EE_Error
1871
-     */
1872
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1873
-    {
1874
-        $existing = null;
1875
-        $model = self::_get_model($classname, $timezone);
1876
-        if ($model->has_primary_key_field()) {
1877
-            $primary_id_ref = self::_get_primary_key_name($classname);
1878
-            if (array_key_exists($primary_id_ref, $props_n_values)
1879
-                && ! empty($props_n_values[$primary_id_ref])
1880
-            ) {
1881
-                $existing = $model->get_one_by_ID(
1882
-                    $props_n_values[$primary_id_ref]
1883
-                );
1884
-            }
1885
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
1886
-            //no primary key on this model, but there's still a matching item in the DB
1887
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1888
-                self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1889
-            );
1890
-        }
1891
-        if ($existing) {
1892
-            //set date formats if present before setting values
1893
-            if ( ! empty($date_formats) && is_array($date_formats)) {
1894
-                $existing->set_date_format($date_formats[0]);
1895
-                $existing->set_time_format($date_formats[1]);
1896
-            } else {
1897
-                //set default formats for date and time
1898
-                $existing->set_date_format(get_option('date_format'));
1899
-                $existing->set_time_format(get_option('time_format'));
1900
-            }
1901
-            foreach ($props_n_values as $property => $field_value) {
1902
-                $existing->set($property, $field_value);
1903
-            }
1904
-            return $existing;
1905
-        } else {
1906
-            return false;
1907
-        }
1908
-    }
1909
-
1910
-
1911
-
1912
-    /**
1913
-     * Gets the EEM_*_Model for this class
1914
-     *
1915
-     * @access public now, as this is more convenient
1916
-     * @param      $classname
1917
-     * @param null $timezone
1918
-     * @throws EE_Error
1919
-     * @return EEM_Base
1920
-     */
1921
-    protected static function _get_model($classname, $timezone = null)
1922
-    {
1923
-        //find model for this class
1924
-        if ( ! $classname) {
1925
-            throw new EE_Error(
1926
-                sprintf(
1927
-                    __(
1928
-                        "What were you thinking calling _get_model(%s)?? You need to specify the class name",
1929
-                        "event_espresso"
1930
-                    ),
1931
-                    $classname
1932
-                )
1933
-            );
1934
-        }
1935
-        $modelName = self::_get_model_classname($classname);
1936
-        return self::_get_model_instance_with_name($modelName, $timezone);
1937
-    }
1938
-
1939
-
1940
-
1941
-    /**
1942
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1943
-     *
1944
-     * @param string $model_classname
1945
-     * @param null   $timezone
1946
-     * @return EEM_Base
1947
-     */
1948
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1949
-    {
1950
-        $model_classname = str_replace('EEM_', '', $model_classname);
1951
-        $model = EE_Registry::instance()->load_model($model_classname);
1952
-        $model->set_timezone($timezone);
1953
-        return $model;
1954
-    }
1955
-
1956
-
1957
-
1958
-    /**
1959
-     * If a model name is provided (eg Registration), gets the model classname for that model.
1960
-     * Also works if a model class's classname is provided (eg EE_Registration).
1961
-     *
1962
-     * @param null $model_name
1963
-     * @return string like EEM_Attendee
1964
-     */
1965
-    private static function _get_model_classname($model_name = null)
1966
-    {
1967
-        if (strpos($model_name, "EE_") === 0) {
1968
-            $model_classname = str_replace("EE_", "EEM_", $model_name);
1969
-        } else {
1970
-            $model_classname = "EEM_" . $model_name;
1971
-        }
1972
-        return $model_classname;
1973
-    }
1974
-
1975
-
1976
-
1977
-    /**
1978
-     * returns the name of the primary key attribute
1979
-     *
1980
-     * @param null $classname
1981
-     * @throws EE_Error
1982
-     * @return string
1983
-     */
1984
-    protected static function _get_primary_key_name($classname = null)
1985
-    {
1986
-        if ( ! $classname) {
1987
-            throw new EE_Error(
1988
-                sprintf(
1989
-                    __("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1990
-                    $classname
1991
-                )
1992
-            );
1993
-        }
1994
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
1995
-    }
1996
-
1997
-
1998
-
1999
-    /**
2000
-     * Gets the value of the primary key.
2001
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2002
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2003
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2004
-     *
2005
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2006
-     * @throws \EE_Error
2007
-     */
2008
-    public function ID()
2009
-    {
2010
-        $model = $this->get_model();
2011
-        //now that we know the name of the variable, use a variable variable to get its value and return its
2012
-        if ($model->has_primary_key_field()) {
2013
-            return $this->_fields[$model->primary_key_name()];
2014
-        } else {
2015
-            return $model->get_index_primary_key_string($this->_fields);
2016
-        }
2017
-    }
2018
-
2019
-
2020
-
2021
-    /**
2022
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2023
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2024
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2025
-     *
2026
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2027
-     * @param string $relationName                     eg 'Events','Question',etc.
2028
-     *                                                 an attendee to a group, you also want to specify which role they
2029
-     *                                                 will have in that group. So you would use this parameter to
2030
-     *                                                 specify array('role-column-name'=>'role-id')
2031
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2032
-     *                                                 allow you to further constrict the relation to being added.
2033
-     *                                                 However, keep in mind that the columns (keys) given must match a
2034
-     *                                                 column on the JOIN table and currently only the HABTM models
2035
-     *                                                 accept these additional conditions.  Also remember that if an
2036
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2037
-     *                                                 NEW row is created in the join table.
2038
-     * @param null   $cache_id
2039
-     * @throws EE_Error
2040
-     * @return EE_Base_Class the object the relation was added to
2041
-     */
2042
-    public function _add_relation_to(
2043
-        $otherObjectModelObjectOrID,
2044
-        $relationName,
2045
-        $extra_join_model_fields_n_values = array(),
2046
-        $cache_id = null
2047
-    ) {
2048
-        $model = $this->get_model();
2049
-        //if this thing exists in the DB, save the relation to the DB
2050
-        if ($this->ID()) {
2051
-            $otherObject = $model
2052
-                                ->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2053
-                                    $extra_join_model_fields_n_values);
2054
-            //clear cache so future get_many_related and get_first_related() return new results.
2055
-            $this->clear_cache($relationName, $otherObject, true);
2056
-            if ($otherObject instanceof EE_Base_Class) {
2057
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2058
-            }
2059
-        } else {
2060
-            //this thing doesn't exist in the DB,  so just cache it
2061
-            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2062
-                throw new EE_Error(sprintf(
2063
-                    __('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2064
-                        'event_espresso'),
2065
-                    $otherObjectModelObjectOrID,
2066
-                    get_class($this)
2067
-                ));
2068
-            } else {
2069
-                $otherObject = $otherObjectModelObjectOrID;
2070
-            }
2071
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2072
-        }
2073
-        if ($otherObject instanceof EE_Base_Class) {
2074
-            //fix the reciprocal relation too
2075
-            if ($otherObject->ID()) {
2076
-                //its saved so assumed relations exist in the DB, so we can just
2077
-                //clear the cache so future queries use the updated info in the DB
2078
-                $otherObject->clear_cache($model->get_this_model_name(), null, true);
2079
-            } else {
2080
-                //it's not saved, so it caches relations like this
2081
-                $otherObject->cache($model->get_this_model_name(), $this);
2082
-            }
2083
-        }
2084
-        return $otherObject;
2085
-    }
2086
-
2087
-
2088
-
2089
-    /**
2090
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2091
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2092
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2093
-     * from the cache
2094
-     *
2095
-     * @param mixed  $otherObjectModelObjectOrID
2096
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2097
-     *                to the DB yet
2098
-     * @param string $relationName
2099
-     * @param array  $where_query
2100
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2101
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2102
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2103
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2104
-     *                created in the join table.
2105
-     * @return EE_Base_Class the relation was removed from
2106
-     * @throws \EE_Error
2107
-     */
2108
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2109
-    {
2110
-        if ($this->ID()) {
2111
-            //if this exists in the DB, save the relation change to the DB too
2112
-            $otherObject = $this->get_model()
2113
-                                ->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2114
-                                    $where_query);
2115
-            $this->clear_cache($relationName, $otherObject);
2116
-        } else {
2117
-            //this doesn't exist in the DB, just remove it from the cache
2118
-            $otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2119
-        }
2120
-        if ($otherObject instanceof EE_Base_Class) {
2121
-            $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2122
-        }
2123
-        return $otherObject;
2124
-    }
2125
-
2126
-
2127
-
2128
-    /**
2129
-     * Removes ALL the related things for the $relationName.
2130
-     *
2131
-     * @param string $relationName
2132
-     * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2133
-     * @return EE_Base_Class
2134
-     * @throws \EE_Error
2135
-     */
2136
-    public function _remove_relations($relationName, $where_query_params = array())
2137
-    {
2138
-        if ($this->ID()) {
2139
-            //if this exists in the DB, save the relation change to the DB too
2140
-            $otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2141
-            $this->clear_cache($relationName, null, true);
2142
-        } else {
2143
-            //this doesn't exist in the DB, just remove it from the cache
2144
-            $otherObjects = $this->clear_cache($relationName, null, true);
2145
-        }
2146
-        if (is_array($otherObjects)) {
2147
-            foreach ($otherObjects as $otherObject) {
2148
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2149
-            }
2150
-        }
2151
-        return $otherObjects;
2152
-    }
2153
-
2154
-
2155
-
2156
-    /**
2157
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2158
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2159
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2160
-     * because we want to get even deleted items etc.
2161
-     *
2162
-     * @param string $relationName key in the model's _model_relations array
2163
-     * @param array  $query_params like EEM_Base::get_all
2164
-     * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2165
-     * @throws \EE_Error
2166
-     *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2167
-     *                             you want IDs
2168
-     */
2169
-    public function get_many_related($relationName, $query_params = array())
2170
-    {
2171
-        if ($this->ID()) {
2172
-            //this exists in the DB, so get the related things from either the cache or the DB
2173
-            //if there are query parameters, forget about caching the related model objects.
2174
-            if ($query_params) {
2175
-                $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2176
-            } else {
2177
-                //did we already cache the result of this query?
2178
-                $cached_results = $this->get_all_from_cache($relationName);
2179
-                if ( ! $cached_results) {
2180
-                    $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2181
-                    //if no query parameters were passed, then we got all the related model objects
2182
-                    //for that relation. We can cache them then.
2183
-                    foreach ($related_model_objects as $related_model_object) {
2184
-                        $this->cache($relationName, $related_model_object);
2185
-                    }
2186
-                } else {
2187
-                    $related_model_objects = $cached_results;
2188
-                }
2189
-            }
2190
-        } else {
2191
-            //this doesn't exist in the DB, so just get the related things from the cache
2192
-            $related_model_objects = $this->get_all_from_cache($relationName);
2193
-        }
2194
-        return $related_model_objects;
2195
-    }
2196
-
2197
-
2198
-
2199
-    /**
2200
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2201
-     * unless otherwise specified in the $query_params
2202
-     *
2203
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2204
-     * @param array  $query_params   like EEM_Base::get_all's
2205
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2206
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2207
-     *                               that by the setting $distinct to TRUE;
2208
-     * @return int
2209
-     */
2210
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2211
-    {
2212
-        return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2213
-    }
2214
-
2215
-
2216
-
2217
-    /**
2218
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2219
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2220
-     *
2221
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2222
-     * @param array  $query_params  like EEM_Base::get_all's
2223
-     * @param string $field_to_sum  name of field to count by.
2224
-     *                              By default, uses primary key (which doesn't make much sense, so you should probably
2225
-     *                              change it)
2226
-     * @return int
2227
-     */
2228
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2229
-    {
2230
-        return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2231
-    }
2232
-
2233
-
2234
-
2235
-    /**
2236
-     * Gets the first (ie, one) related model object of the specified type.
2237
-     *
2238
-     * @param string $relationName key in the model's _model_relations array
2239
-     * @param array  $query_params like EEM_Base::get_all
2240
-     * @return EE_Base_Class (not an array, a single object)
2241
-     * @throws \EE_Error
2242
-     */
2243
-    public function get_first_related($relationName, $query_params = array())
2244
-    {
2245
-        $model = $this->get_model();
2246
-        if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2247
-            //if they've provided some query parameters, don't bother trying to cache the result
2248
-            //also make sure we're not caching the result of get_first_related
2249
-            //on a relation which should have an array of objects (because the cache might have an array of objects)
2250
-            if ($query_params
2251
-                || ! $model->related_settings_for($relationName)
2252
-                     instanceof
2253
-                     EE_Belongs_To_Relation
2254
-            ) {
2255
-                $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2256
-            } else {
2257
-                //first, check if we've already cached the result of this query
2258
-                $cached_result = $this->get_one_from_cache($relationName);
2259
-                if ( ! $cached_result) {
2260
-                    $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2261
-                    $this->cache($relationName, $related_model_object);
2262
-                } else {
2263
-                    $related_model_object = $cached_result;
2264
-                }
2265
-            }
2266
-        } else {
2267
-            $related_model_object = null;
2268
-            //this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2269
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2270
-                $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2271
-            }
2272
-            //this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2273
-            if ( ! $related_model_object) {
2274
-                $related_model_object = $this->get_one_from_cache($relationName);
2275
-            }
2276
-        }
2277
-        return $related_model_object;
2278
-    }
2279
-
2280
-
2281
-
2282
-    /**
2283
-     * Does a delete on all related objects of type $relationName and removes
2284
-     * the current model object's relation to them. If they can't be deleted (because
2285
-     * of blocking related model objects) does nothing. If the related model objects are
2286
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2287
-     * If this model object doesn't exist yet in the DB, just removes its related things
2288
-     *
2289
-     * @param string $relationName
2290
-     * @param array  $query_params like EEM_Base::get_all's
2291
-     * @return int how many deleted
2292
-     * @throws \EE_Error
2293
-     */
2294
-    public function delete_related($relationName, $query_params = array())
2295
-    {
2296
-        if ($this->ID()) {
2297
-            $count = $this->get_model()->delete_related($this, $relationName, $query_params);
2298
-        } else {
2299
-            $count = count($this->get_all_from_cache($relationName));
2300
-            $this->clear_cache($relationName, null, true);
2301
-        }
2302
-        return $count;
2303
-    }
2304
-
2305
-
2306
-
2307
-    /**
2308
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2309
-     * the current model object's relation to them. If they can't be deleted (because
2310
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2311
-     * If the related thing isn't a soft-deletable model object, this function is identical
2312
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2313
-     *
2314
-     * @param string $relationName
2315
-     * @param array  $query_params like EEM_Base::get_all's
2316
-     * @return int how many deleted (including those soft deleted)
2317
-     * @throws \EE_Error
2318
-     */
2319
-    public function delete_related_permanently($relationName, $query_params = array())
2320
-    {
2321
-        if ($this->ID()) {
2322
-            $count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2323
-        } else {
2324
-            $count = count($this->get_all_from_cache($relationName));
2325
-        }
2326
-        $this->clear_cache($relationName, null, true);
2327
-        return $count;
2328
-    }
2329
-
2330
-
2331
-
2332
-    /**
2333
-     * is_set
2334
-     * Just a simple utility function children can use for checking if property exists
2335
-     *
2336
-     * @access  public
2337
-     * @param  string $field_name property to check
2338
-     * @return bool                              TRUE if existing,FALSE if not.
2339
-     */
2340
-    public function is_set($field_name)
2341
-    {
2342
-        return isset($this->_fields[$field_name]);
2343
-    }
2344
-
2345
-
2346
-
2347
-    /**
2348
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2349
-     * EE_Error exception if they don't
2350
-     *
2351
-     * @param  mixed (string|array) $properties properties to check
2352
-     * @throws EE_Error
2353
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2354
-     */
2355
-    protected function _property_exists($properties)
2356
-    {
2357
-        foreach ((array)$properties as $property_name) {
2358
-            //first make sure this property exists
2359
-            if ( ! $this->_fields[$property_name]) {
2360
-                throw new EE_Error(
2361
-                    sprintf(
2362
-                        __(
2363
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2364
-                            'event_espresso'
2365
-                        ),
2366
-                        $property_name
2367
-                    )
2368
-                );
2369
-            }
2370
-        }
2371
-        return true;
2372
-    }
2373
-
2374
-
2375
-
2376
-    /**
2377
-     * This simply returns an array of model fields for this object
2378
-     *
2379
-     * @return array
2380
-     * @throws \EE_Error
2381
-     */
2382
-    public function model_field_array()
2383
-    {
2384
-        $fields = $this->get_model()->field_settings(false);
2385
-        $properties = array();
2386
-        //remove prepended underscore
2387
-        foreach ($fields as $field_name => $settings) {
2388
-            $properties[$field_name] = $this->get($field_name);
2389
-        }
2390
-        return $properties;
2391
-    }
2392
-
2393
-
2394
-
2395
-    /**
2396
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2397
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2398
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2399
-     * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2400
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2401
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2402
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
2403
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
2404
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2405
-     * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2406
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2407
-     *        return $previousReturnValue.$returnString;
2408
-     * }
2409
-     * require('EE_Answer.class.php');
2410
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2411
-     * echo $answer->my_callback('monkeys',100);
2412
-     * //will output "you called my_callback! and passed args:monkeys,100"
2413
-     *
2414
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2415
-     * @param array  $args       array of original arguments passed to the function
2416
-     * @throws EE_Error
2417
-     * @return mixed whatever the plugin which calls add_filter decides
2418
-     */
2419
-    public function __call($methodName, $args)
2420
-    {
2421
-        $className = get_class($this);
2422
-        $tagName = "FHEE__{$className}__{$methodName}";
2423
-        if ( ! has_filter($tagName)) {
2424
-            throw new EE_Error(
2425
-                sprintf(
2426
-                    __(
2427
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2428
-                        "event_espresso"
2429
-                    ),
2430
-                    $methodName,
2431
-                    $className,
2432
-                    $tagName
2433
-                )
2434
-            );
2435
-        }
2436
-        return apply_filters($tagName, null, $this, $args);
2437
-    }
2438
-
2439
-
2440
-
2441
-    /**
2442
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2443
-     * A $previous_value can be specified in case there are many meta rows with the same key
2444
-     *
2445
-     * @param string $meta_key
2446
-     * @param mixed  $meta_value
2447
-     * @param mixed  $previous_value
2448
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2449
-     * @throws \EE_Error
2450
-     * NOTE: if the values haven't changed, returns 0
2451
-     */
2452
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2453
-    {
2454
-        $query_params = array(
2455
-            array(
2456
-                'EXM_key'  => $meta_key,
2457
-                'OBJ_ID'   => $this->ID(),
2458
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2459
-            ),
2460
-        );
2461
-        if ($previous_value !== null) {
2462
-            $query_params[0]['EXM_value'] = $meta_value;
2463
-        }
2464
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2465
-        if ( ! $existing_rows_like_that) {
2466
-            return $this->add_extra_meta($meta_key, $meta_value);
2467
-        }
2468
-        foreach ($existing_rows_like_that as $existing_row) {
2469
-            $existing_row->save(array('EXM_value' => $meta_value));
2470
-        }
2471
-        return count($existing_rows_like_that);
2472
-    }
2473
-
2474
-
2475
-
2476
-    /**
2477
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2478
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2479
-     * extra meta row was entered, false if not
2480
-     *
2481
-     * @param string  $meta_key
2482
-     * @param mixed   $meta_value
2483
-     * @param boolean $unique
2484
-     * @return boolean
2485
-     * @throws \EE_Error
2486
-     */
2487
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2488
-    {
2489
-        if ($unique) {
2490
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2491
-                array(
2492
-                    array(
2493
-                        'EXM_key'  => $meta_key,
2494
-                        'OBJ_ID'   => $this->ID(),
2495
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2496
-                    ),
2497
-                )
2498
-            );
2499
-            if ($existing_extra_meta) {
2500
-                return false;
2501
-            }
2502
-        }
2503
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2504
-            array(
2505
-                'EXM_key'   => $meta_key,
2506
-                'EXM_value' => $meta_value,
2507
-                'OBJ_ID'    => $this->ID(),
2508
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2509
-            )
2510
-        );
2511
-        $new_extra_meta->save();
2512
-        return true;
2513
-    }
2514
-
2515
-
2516
-
2517
-    /**
2518
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2519
-     * is specified, only deletes extra meta records with that value.
2520
-     *
2521
-     * @param string $meta_key
2522
-     * @param mixed  $meta_value
2523
-     * @return int number of extra meta rows deleted
2524
-     * @throws \EE_Error
2525
-     */
2526
-    public function delete_extra_meta($meta_key, $meta_value = null)
2527
-    {
2528
-        $query_params = array(
2529
-            array(
2530
-                'EXM_key'  => $meta_key,
2531
-                'OBJ_ID'   => $this->ID(),
2532
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2533
-            ),
2534
-        );
2535
-        if ($meta_value !== null) {
2536
-            $query_params[0]['EXM_value'] = $meta_value;
2537
-        }
2538
-        return EEM_Extra_Meta::instance()->delete($query_params);
2539
-    }
2540
-
2541
-
2542
-
2543
-    /**
2544
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2545
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2546
-     * You can specify $default is case you haven't found the extra meta
2547
-     *
2548
-     * @param string  $meta_key
2549
-     * @param boolean $single
2550
-     * @param mixed   $default if we don't find anything, what should we return?
2551
-     * @return mixed single value if $single; array if ! $single
2552
-     * @throws \EE_Error
2553
-     */
2554
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2555
-    {
2556
-        if ($single) {
2557
-            $result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2558
-            if ($result instanceof EE_Extra_Meta) {
2559
-                return $result->value();
2560
-            } else {
2561
-                return $default;
2562
-            }
2563
-        } else {
2564
-            $results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2565
-            if ($results) {
2566
-                $values = array();
2567
-                foreach ($results as $result) {
2568
-                    if ($result instanceof EE_Extra_Meta) {
2569
-                        $values[$result->ID()] = $result->value();
2570
-                    }
2571
-                }
2572
-                return $values;
2573
-            } else {
2574
-                return $default;
2575
-            }
2576
-        }
2577
-    }
2578
-
2579
-
2580
-
2581
-    /**
2582
-     * Returns a simple array of all the extra meta associated with this model object.
2583
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2584
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2585
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2586
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2587
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2588
-     * finally the extra meta's value as each sub-value. (eg
2589
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2590
-     *
2591
-     * @param boolean $one_of_each_key
2592
-     * @return array
2593
-     * @throws \EE_Error
2594
-     */
2595
-    public function all_extra_meta_array($one_of_each_key = true)
2596
-    {
2597
-        $return_array = array();
2598
-        if ($one_of_each_key) {
2599
-            $extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2600
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2601
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2602
-                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2603
-                }
2604
-            }
2605
-        } else {
2606
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2607
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2608
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2609
-                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2610
-                        $return_array[$extra_meta_obj->key()] = array();
2611
-                    }
2612
-                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2613
-                }
2614
-            }
2615
-        }
2616
-        return $return_array;
2617
-    }
2618
-
2619
-
2620
-
2621
-    /**
2622
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2623
-     *
2624
-     * @return string
2625
-     * @throws \EE_Error
2626
-     */
2627
-    public function name()
2628
-    {
2629
-        //find a field that's not a text field
2630
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2631
-        if ($field_we_can_use) {
2632
-            return $this->get($field_we_can_use->get_name());
2633
-        } else {
2634
-            $first_few_properties = $this->model_field_array();
2635
-            $first_few_properties = array_slice($first_few_properties, 0, 3);
2636
-            $name_parts = array();
2637
-            foreach ($first_few_properties as $name => $value) {
2638
-                $name_parts[] = "$name:$value";
2639
-            }
2640
-            return implode(",", $name_parts);
2641
-        }
2642
-    }
2643
-
2644
-
2645
-
2646
-    /**
2647
-     * in_entity_map
2648
-     * Checks if this model object has been proven to already be in the entity map
2649
-     *
2650
-     * @return boolean
2651
-     * @throws \EE_Error
2652
-     */
2653
-    public function in_entity_map()
2654
-    {
2655
-        if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2656
-            //well, if we looked, did we find it in the entity map?
2657
-            return true;
2658
-        } else {
2659
-            return false;
2660
-        }
2661
-    }
2662
-
2663
-
2664
-
2665
-    /**
2666
-     * refresh_from_db
2667
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
2668
-     *
2669
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2670
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2671
-     */
2672
-    public function refresh_from_db()
2673
-    {
2674
-        if ($this->ID() && $this->in_entity_map()) {
2675
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
2676
-        } else {
2677
-            //if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2678
-            //if it has an ID but it's not in the map, and you're asking me to refresh it
2679
-            //that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2680
-            //absolutely nothing in it for this ID
2681
-            if (WP_DEBUG) {
2682
-                throw new EE_Error(
2683
-                    sprintf(
2684
-                        __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2685
-                            'event_espresso'),
2686
-                        $this->ID(),
2687
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2688
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2689
-                    )
2690
-                );
2691
-            }
2692
-        }
2693
-    }
2694
-
2695
-
2696
-
2697
-    /**
2698
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2699
-     * (probably a bad assumption they have made, oh well)
2700
-     *
2701
-     * @return string
2702
-     */
2703
-    public function __toString()
2704
-    {
2705
-        try {
2706
-            return sprintf('%s (%s)', $this->name(), $this->ID());
2707
-        } catch (Exception $e) {
2708
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2709
-            return '';
2710
-        }
2711
-    }
2712
-
2713
-
2714
-
2715
-    /**
2716
-     * Clear related model objects if they're already in the DB, because otherwise when we
2717
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
2718
-     * This means if we have made changes to those related model objects, and want to unserialize
2719
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
2720
-     * Instead, those related model objects should be directly serialized and stored.
2721
-     * Eg, the following won't work:
2722
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2723
-     * $att = $reg->attendee();
2724
-     * $att->set( 'ATT_fname', 'Dirk' );
2725
-     * update_option( 'my_option', serialize( $reg ) );
2726
-     * //END REQUEST
2727
-     * //START NEXT REQUEST
2728
-     * $reg = get_option( 'my_option' );
2729
-     * $reg->attendee()->save();
2730
-     * And would need to be replace with:
2731
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2732
-     * $att = $reg->attendee();
2733
-     * $att->set( 'ATT_fname', 'Dirk' );
2734
-     * update_option( 'my_option', serialize( $reg ) );
2735
-     * //END REQUEST
2736
-     * //START NEXT REQUEST
2737
-     * $att = get_option( 'my_option' );
2738
-     * $att->save();
2739
-     *
2740
-     * @return array
2741
-     * @throws \EE_Error
2742
-     */
2743
-    public function __sleep()
2744
-    {
2745
-        $model = $this->get_model();
2746
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
2747
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
2748
-                $classname = 'EE_' . $model->get_this_model_name();
2749
-                if (
2750
-                    $this->get_one_from_cache($relation_name) instanceof $classname
2751
-                    && $this->get_one_from_cache($relation_name)->ID()
2752
-                ) {
2753
-                    $this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2754
-                }
2755
-            }
2756
-        }
2757
-        $this->_props_n_values_provided_in_constructor = array();
2758
-        $properties_to_serialize = get_object_vars($this);
2759
-        //don't serialize the model. It's big and that risks recursion
2760
-        unset($properties_to_serialize['_model']);
2761
-        return array_keys($properties_to_serialize);
2762
-    }
2763
-
2764
-
2765
-
2766
-    /**
2767
-     * restore _props_n_values_provided_in_constructor
2768
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2769
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
2770
-     * At best, you would only be able to detect if state change has occurred during THIS request.
2771
-     */
2772
-    public function __wakeup()
2773
-    {
2774
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
2775
-    }
28
+	/**
29
+	 * This is an array of the original properties and values provided during construction
30
+	 * of this model object. (keys are model field names, values are their values).
31
+	 * This list is important to remember so that when we are merging data from the db, we know
32
+	 * which values to override and which to not override.
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $_props_n_values_provided_in_constructor;
37
+
38
+	/**
39
+	 * Timezone
40
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
+	 * access to it.
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_timezone;
48
+
49
+
50
+
51
+	/**
52
+	 * date format
53
+	 * pattern or format for displaying dates
54
+	 *
55
+	 * @var string $_dt_frmt
56
+	 */
57
+	protected $_dt_frmt;
58
+
59
+
60
+
61
+	/**
62
+	 * time format
63
+	 * pattern or format for displaying time
64
+	 *
65
+	 * @var string $_tm_frmt
66
+	 */
67
+	protected $_tm_frmt;
68
+
69
+
70
+
71
+	/**
72
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
73
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
74
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
+	 *
77
+	 * @var array
78
+	 */
79
+	protected $_cached_properties = array();
80
+
81
+	/**
82
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
83
+	 * single
84
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
+	 * all others have an array)
87
+	 *
88
+	 * @var array
89
+	 */
90
+	protected $_model_relations = array();
91
+
92
+	/**
93
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
+	 *
96
+	 * @var array
97
+	 */
98
+	protected $_fields = array();
99
+
100
+	/**
101
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
102
+	 * For example, we might create model objects intended to only be used for the duration
103
+	 * of this request and to be thrown away, and if they were accidentally saved
104
+	 * it would be a bug.
105
+	 */
106
+	protected $_allow_persist = true;
107
+
108
+	/**
109
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
110
+	 */
111
+	protected $_has_changes = false;
112
+
113
+	/**
114
+	 * @var EEM_Base
115
+	 */
116
+	protected $_model;
117
+
118
+
119
+
120
+	/**
121
+	 * @param array  $fieldValues
122
+	 * @param string $timezone
123
+	 * @param array  $date_formats
124
+	 * @param bool   $bydb
125
+	 * @return \EE_Base_Class
126
+	 * @throws \EE_Error
127
+	 */
128
+	public static function new_instance(
129
+		array $fieldValues = array(),
130
+		$timezone = '',
131
+		array $date_formats = array(),
132
+		$bydb = false
133
+	)
134
+	{
135
+		$className = get_called_class();
136
+		if ( ! $bydb) {
137
+			$cached_object = \EE_Base_Class::_check_for_object($fieldValues, $className, $timezone, $date_formats);
138
+			if ($cached_object) {
139
+				return $cached_object;
140
+			}
141
+		}
142
+		return new static($fieldValues, $bydb, $timezone, $date_formats);
143
+	}
144
+
145
+
146
+
147
+	/**
148
+	 * @deprecated
149
+	 * @param array  $fieldValues
150
+	 * @param string $timezone
151
+	 * @param array  $date_formats
152
+	 * @return \EE_Base_Class
153
+	 * @throws \EE_Error
154
+	 */
155
+	public static function new_instance_from_db(array $fieldValues = array(), $timezone = '', array $date_formats = array())
156
+	{
157
+		return static::new_instance($fieldValues, $timezone, $date_formats, true);
158
+	}
159
+
160
+
161
+	/**
162
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children play nice
163
+	 *
164
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
165
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
166
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
167
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
168
+	 *                                                         corresponding db model or not.
169
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
170
+	 *                                                         be in when instantiating a EE_Base_Class object.
171
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
172
+	 *                                                         value is the date_format and second value is the time
173
+	 *                                                         format.
174
+	 * @throws EE_Error
175
+	 */
176
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
177
+	{
178
+		$className = get_class($this);
179
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
180
+		$model = $this->get_model();
181
+		$model_fields = $model->field_settings(false);
182
+		// ensure $fieldValues is an array
183
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
184
+		// EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
185
+		// verify client code has not passed any invalid field names
186
+		foreach ($fieldValues as $field_name => $field_value) {
187
+			if ( ! isset($model_fields[$field_name])) {
188
+				throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
189
+					"event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
190
+			}
191
+		}
192
+		// EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
193
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
194
+		if ( ! empty($date_formats) && is_array($date_formats)) {
195
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
196
+		} else {
197
+			//set default formats for date and time
198
+			$this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
199
+			$this->_tm_frmt = (string)get_option('time_format', 'g:i a');
200
+		}
201
+		//if db model is instantiating
202
+		if ($bydb) {
203
+			//client code has indicated these field values are from the database
204
+			foreach ($model_fields as $fieldName => $field) {
205
+				$this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
206
+			}
207
+		} else {
208
+			//we're constructing a brand
209
+			//new instance of the model object. Generally, this means we'll need to do more field validation
210
+			foreach ($model_fields as $fieldName => $field) {
211
+				$this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
212
+			}
213
+		}
214
+		//remember what values were passed to this constructor
215
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
216
+		//remember in entity mapper
217
+		if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
218
+			$model->add_to_entity_map($this);
219
+		}
220
+		//setup all the relations
221
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
222
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
223
+				$this->_model_relations[$relation_name] = null;
224
+			} else {
225
+				$this->_model_relations[$relation_name] = array();
226
+			}
227
+		}
228
+		/**
229
+		 * Action done at the end of each model object construction
230
+		 *
231
+		 * @param EE_Base_Class $this the model object just created
232
+		 */
233
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
234
+	}
235
+
236
+
237
+
238
+	/**
239
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
240
+	 *
241
+	 * @return boolean
242
+	 */
243
+	public function allow_persist()
244
+	{
245
+		return $this->_allow_persist;
246
+	}
247
+
248
+
249
+
250
+	/**
251
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
252
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
253
+	 * you got new information that somehow made you change your mind.
254
+	 *
255
+	 * @param boolean $allow_persist
256
+	 * @return boolean
257
+	 */
258
+	public function set_allow_persist($allow_persist)
259
+	{
260
+		return $this->_allow_persist = $allow_persist;
261
+	}
262
+
263
+
264
+
265
+	/**
266
+	 * Gets the field's original value when this object was constructed during this request.
267
+	 * This can be helpful when determining if a model object has changed or not
268
+	 *
269
+	 * @param string $field_name
270
+	 * @return mixed|null
271
+	 * @throws \EE_Error
272
+	 */
273
+	public function get_original($field_name)
274
+	{
275
+		if (isset($this->_props_n_values_provided_in_constructor[$field_name])
276
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
277
+		) {
278
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
279
+		} else {
280
+			return null;
281
+		}
282
+	}
283
+
284
+
285
+
286
+	/**
287
+	 * @param EE_Base_Class $obj
288
+	 * @return string
289
+	 */
290
+	public function get_class($obj)
291
+	{
292
+		return get_class($obj);
293
+	}
294
+
295
+
296
+
297
+	/**
298
+	 * Overrides parent because parent expects old models.
299
+	 * This also doesn't do any validation, and won't work for serialized arrays
300
+	 *
301
+	 * @param    string $field_name
302
+	 * @param    mixed  $field_value
303
+	 * @param bool      $use_default
304
+	 * @throws \EE_Error
305
+	 */
306
+	public function set($field_name, $field_value, $use_default = false)
307
+	{
308
+		// if not using default and nothing has changed, and object has already been setup (has ID),
309
+		// then don't do anything
310
+		if (
311
+			! $use_default
312
+			&& $this->_fields[$field_name] === $field_value
313
+			&& $this->ID()
314
+		) {
315
+			return;
316
+		}
317
+		$model = $this->get_model();
318
+		$this->_has_changes = true;
319
+		$field_obj = $model->field_settings_for($field_name);
320
+		if ($field_obj instanceof EE_Model_Field_Base) {
321
+			//			if ( method_exists( $field_obj, 'set_timezone' )) {
322
+			if ($field_obj instanceof EE_Datetime_Field) {
323
+				$field_obj->set_timezone($this->_timezone);
324
+				$field_obj->set_date_format($this->_dt_frmt);
325
+				$field_obj->set_time_format($this->_tm_frmt);
326
+			}
327
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
328
+			//should the value be null?
329
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
330
+				$this->_fields[$field_name] = $field_obj->get_default_value();
331
+				/**
332
+				 * To save having to refactor all the models, if a default value is used for a
333
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
334
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
335
+				 * object.
336
+				 *
337
+				 * @since 4.6.10+
338
+				 */
339
+				if (
340
+					$field_obj instanceof EE_Datetime_Field
341
+					&& $this->_fields[$field_name] !== null
342
+					&& ! $this->_fields[$field_name] instanceof DateTime
343
+				) {
344
+					empty($this->_fields[$field_name])
345
+						? $this->set($field_name, time())
346
+						: $this->set($field_name, $this->_fields[$field_name]);
347
+				}
348
+			} else {
349
+				$this->_fields[$field_name] = $holder_of_value;
350
+			}
351
+			//if we're not in the constructor...
352
+			//now check if what we set was a primary key
353
+			if (
354
+				//note: props_n_values_provided_in_constructor is only set at the END of the constructor
355
+				$this->_props_n_values_provided_in_constructor
356
+				&& $field_value
357
+				&& $field_name === $model->primary_key_name()
358
+			) {
359
+				//if so, we want all this object's fields to be filled either with
360
+				//what we've explicitly set on this model
361
+				//or what we have in the db
362
+				// echo "setting primary key!";
363
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
364
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
365
+				foreach ($fields_on_model as $field_obj) {
366
+					if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
367
+						 && $field_obj->get_name() !== $field_name
368
+					) {
369
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
370
+					}
371
+				}
372
+				//oh this model object has an ID? well make sure its in the entity mapper
373
+				$model->add_to_entity_map($this);
374
+			}
375
+			//let's unset any cache for this field_name from the $_cached_properties property.
376
+			$this->_clear_cached_property($field_name);
377
+		} else {
378
+			throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
379
+				"event_espresso"), $field_name));
380
+		}
381
+	}
382
+
383
+
384
+
385
+	/**
386
+	 * This sets the field value on the db column if it exists for the given $column_name or
387
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
388
+	 *
389
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
390
+	 * @param string $field_name  Must be the exact column name.
391
+	 * @param mixed  $field_value The value to set.
392
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
393
+	 * @throws \EE_Error
394
+	 */
395
+	public function set_field_or_extra_meta($field_name, $field_value)
396
+	{
397
+		if ($this->get_model()->has_field($field_name)) {
398
+			$this->set($field_name, $field_value);
399
+			return true;
400
+		} else {
401
+			//ensure this object is saved first so that extra meta can be properly related.
402
+			$this->save();
403
+			return $this->update_extra_meta($field_name, $field_value);
404
+		}
405
+	}
406
+
407
+
408
+
409
+	/**
410
+	 * This retrieves the value of the db column set on this class or if that's not present
411
+	 * it will attempt to retrieve from extra_meta if found.
412
+	 * Example Usage:
413
+	 * Via EE_Message child class:
414
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
415
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
416
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
417
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
418
+	 * value for those extra fields dynamically via the EE_message object.
419
+	 *
420
+	 * @param  string $field_name expecting the fully qualified field name.
421
+	 * @return mixed|null  value for the field if found.  null if not found.
422
+	 * @throws \EE_Error
423
+	 */
424
+	public function get_field_or_extra_meta($field_name)
425
+	{
426
+		if ($this->get_model()->has_field($field_name)) {
427
+			$column_value = $this->get($field_name);
428
+		} else {
429
+			//This isn't a column in the main table, let's see if it is in the extra meta.
430
+			$column_value = $this->get_extra_meta($field_name, true, null);
431
+		}
432
+		return $column_value;
433
+	}
434
+
435
+
436
+
437
+	/**
438
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
439
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
440
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
441
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
442
+	 *
443
+	 * @access public
444
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
445
+	 * @return void
446
+	 * @throws \EE_Error
447
+	 */
448
+	public function set_timezone($timezone = '')
449
+	{
450
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
451
+		//make sure we clear all cached properties because they won't be relevant now
452
+		$this->_clear_cached_properties();
453
+		//make sure we update field settings and the date for all EE_Datetime_Fields
454
+		$model_fields = $this->get_model()->field_settings(false);
455
+		foreach ($model_fields as $field_name => $field_obj) {
456
+			if ($field_obj instanceof EE_Datetime_Field) {
457
+				$field_obj->set_timezone($this->_timezone);
458
+				if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
459
+					$this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
460
+				}
461
+			}
462
+		}
463
+	}
464
+
465
+
466
+
467
+	/**
468
+	 * This just returns whatever is set for the current timezone.
469
+	 *
470
+	 * @access public
471
+	 * @return string timezone string
472
+	 */
473
+	public function get_timezone()
474
+	{
475
+		return $this->_timezone;
476
+	}
477
+
478
+
479
+
480
+	/**
481
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
482
+	 * internally instead of wp set date format options
483
+	 *
484
+	 * @since 4.6
485
+	 * @param string $format should be a format recognizable by PHP date() functions.
486
+	 */
487
+	public function set_date_format($format)
488
+	{
489
+		$this->_dt_frmt = $format;
490
+		//clear cached_properties because they won't be relevant now.
491
+		$this->_clear_cached_properties();
492
+	}
493
+
494
+
495
+
496
+	/**
497
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
498
+	 * class internally instead of wp set time format options.
499
+	 *
500
+	 * @since 4.6
501
+	 * @param string $format should be a format recognizable by PHP date() functions.
502
+	 */
503
+	public function set_time_format($format)
504
+	{
505
+		$this->_tm_frmt = $format;
506
+		//clear cached_properties because they won't be relevant now.
507
+		$this->_clear_cached_properties();
508
+	}
509
+
510
+
511
+
512
+	/**
513
+	 * This returns the current internal set format for the date and time formats.
514
+	 *
515
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
516
+	 *                             where the first value is the date format and the second value is the time format.
517
+	 * @return mixed string|array
518
+	 */
519
+	public function get_format($full = true)
520
+	{
521
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
522
+	}
523
+
524
+
525
+
526
+	/**
527
+	 * cache
528
+	 * stores the passed model object on the current model object.
529
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
530
+	 *
531
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
532
+	 *                                       'Registration' associated with this model object
533
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
534
+	 *                                       that could be a payment or a registration)
535
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
536
+	 *                                       items which will be stored in an array on this object
537
+	 * @throws EE_Error
538
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
539
+	 *                  related thing, no array)
540
+	 */
541
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
542
+	{
543
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
544
+		if ( ! $object_to_cache instanceof EE_Base_Class) {
545
+			return false;
546
+		}
547
+		// also get "how" the object is related, or throw an error
548
+		if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
549
+			throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
550
+				$relationName, get_class($this)));
551
+		}
552
+		// how many things are related ?
553
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
554
+			// if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
555
+			// so for these model objects just set it to be cached
556
+			$this->_model_relations[$relationName] = $object_to_cache;
557
+			$return = true;
558
+		} else {
559
+			// otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
560
+			// eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
561
+			if ( ! is_array($this->_model_relations[$relationName])) {
562
+				// if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
563
+				$this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
564
+					? array($this->_model_relations[$relationName]) : array();
565
+			}
566
+			// first check for a cache_id which is normally empty
567
+			if ( ! empty($cache_id)) {
568
+				// if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
569
+				$this->_model_relations[$relationName][$cache_id] = $object_to_cache;
570
+				$return = $cache_id;
571
+			} elseif ($object_to_cache->ID()) {
572
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
573
+				$this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
574
+				$return = $object_to_cache->ID();
575
+			} else {
576
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
577
+				$this->_model_relations[$relationName][] = $object_to_cache;
578
+				// move the internal pointer to the end of the array
579
+				end($this->_model_relations[$relationName]);
580
+				// and grab the key so that we can return it
581
+				$return = key($this->_model_relations[$relationName]);
582
+			}
583
+		}
584
+		return $return;
585
+	}
586
+
587
+
588
+
589
+	/**
590
+	 * For adding an item to the cached_properties property.
591
+	 *
592
+	 * @access protected
593
+	 * @param string      $fieldname the property item the corresponding value is for.
594
+	 * @param mixed       $value     The value we are caching.
595
+	 * @param string|null $cache_type
596
+	 * @return void
597
+	 * @throws \EE_Error
598
+	 */
599
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
600
+	{
601
+		//first make sure this property exists
602
+		$this->get_model()->field_settings_for($fieldname);
603
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
604
+		$this->_cached_properties[$fieldname][$cache_type] = $value;
605
+	}
606
+
607
+
608
+
609
+	/**
610
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
611
+	 * This also SETS the cache if we return the actual property!
612
+	 *
613
+	 * @param string $fieldname        the name of the property we're trying to retrieve
614
+	 * @param bool   $pretty
615
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
616
+	 *                                 (in cases where the same property may be used for different outputs
617
+	 *                                 - i.e. datetime, money etc.)
618
+	 *                                 It can also accept certain pre-defined "schema" strings
619
+	 *                                 to define how to output the property.
620
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
621
+	 * @return mixed                   whatever the value for the property is we're retrieving
622
+	 * @throws \EE_Error
623
+	 */
624
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
625
+	{
626
+		//verify the field exists
627
+		$model = $this->get_model();
628
+		$model->field_settings_for($fieldname);
629
+		$cache_type = $pretty ? 'pretty' : 'standard';
630
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
631
+		if (isset($this->_cached_properties[$fieldname][$cache_type])) {
632
+			return $this->_cached_properties[$fieldname][$cache_type];
633
+		}
634
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
635
+		$this->_set_cached_property($fieldname, $value, $cache_type);
636
+		return $value;
637
+	}
638
+
639
+
640
+
641
+	/**
642
+	 * If the cache didn't fetch the needed item, this fetches it.
643
+	 * @param string $fieldname
644
+	 * @param bool $pretty
645
+	 * @param string $extra_cache_ref
646
+	 * @return mixed
647
+	 */
648
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
649
+	{
650
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
651
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
652
+		if ($field_obj instanceof EE_Datetime_Field) {
653
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
654
+		}
655
+		if ( ! isset($this->_fields[$fieldname])) {
656
+			$this->_fields[$fieldname] = null;
657
+		}
658
+		$value = $pretty
659
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
660
+			: $field_obj->prepare_for_get($this->_fields[$fieldname]);
661
+		return $value;
662
+	}
663
+
664
+
665
+
666
+	/**
667
+	 * set timezone, formats, and output for EE_Datetime_Field objects
668
+	 *
669
+	 * @param \EE_Datetime_Field $datetime_field
670
+	 * @param bool               $pretty
671
+	 * @param null $date_or_time
672
+	 * @return void
673
+	 * @throws \EE_Error
674
+	 */
675
+	protected function _prepare_datetime_field(
676
+		EE_Datetime_Field $datetime_field,
677
+		$pretty = false,
678
+		$date_or_time = null
679
+	) {
680
+		$datetime_field->set_timezone($this->_timezone);
681
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
682
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
683
+		//set the output returned
684
+		switch ($date_or_time) {
685
+			case 'D' :
686
+				$datetime_field->set_date_time_output('date');
687
+				break;
688
+			case 'T' :
689
+				$datetime_field->set_date_time_output('time');
690
+				break;
691
+			default :
692
+				$datetime_field->set_date_time_output();
693
+		}
694
+	}
695
+
696
+
697
+
698
+	/**
699
+	 * This just takes care of clearing out the cached_properties
700
+	 *
701
+	 * @return void
702
+	 */
703
+	protected function _clear_cached_properties()
704
+	{
705
+		$this->_cached_properties = array();
706
+	}
707
+
708
+
709
+
710
+	/**
711
+	 * This just clears out ONE property if it exists in the cache
712
+	 *
713
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
714
+	 * @return void
715
+	 */
716
+	protected function _clear_cached_property($property_name)
717
+	{
718
+		if (isset($this->_cached_properties[$property_name])) {
719
+			unset($this->_cached_properties[$property_name]);
720
+		}
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * Ensures that this related thing is a model object.
727
+	 *
728
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
729
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
730
+	 * @return EE_Base_Class
731
+	 * @throws \EE_Error
732
+	 */
733
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
734
+	{
735
+		$other_model_instance = self::_get_model_instance_with_name(
736
+			self::_get_model_classname($model_name),
737
+			$this->_timezone
738
+		);
739
+		return $other_model_instance->ensure_is_obj($object_or_id);
740
+	}
741
+
742
+
743
+
744
+	/**
745
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
746
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
747
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
748
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
749
+	 *
750
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
751
+	 *                                                     Eg 'Registration'
752
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
753
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
754
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
755
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
756
+	 *                                                     this is HasMany or HABTM.
757
+	 * @throws EE_Error
758
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
759
+	 *                       relation from all
760
+	 */
761
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
762
+	{
763
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
764
+		$index_in_cache = '';
765
+		if ( ! $relationship_to_model) {
766
+			throw new EE_Error(
767
+				sprintf(
768
+					__("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
769
+					$relationName,
770
+					get_class($this)
771
+				)
772
+			);
773
+		}
774
+		if ($clear_all) {
775
+			$obj_removed = true;
776
+			$this->_model_relations[$relationName] = null;
777
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
778
+			$obj_removed = $this->_model_relations[$relationName];
779
+			$this->_model_relations[$relationName] = null;
780
+		} else {
781
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
782
+				&& $object_to_remove_or_index_into_array->ID()
783
+			) {
784
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
785
+				if (is_array($this->_model_relations[$relationName])
786
+					&& ! isset($this->_model_relations[$relationName][$index_in_cache])
787
+				) {
788
+					$index_found_at = null;
789
+					//find this object in the array even though it has a different key
790
+					foreach ($this->_model_relations[$relationName] as $index => $obj) {
791
+						if (
792
+							$obj instanceof EE_Base_Class
793
+							&& (
794
+								$obj == $object_to_remove_or_index_into_array
795
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
796
+							)
797
+						) {
798
+							$index_found_at = $index;
799
+							break;
800
+						}
801
+					}
802
+					if ($index_found_at) {
803
+						$index_in_cache = $index_found_at;
804
+					} else {
805
+						//it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
806
+						//if it wasn't in it to begin with. So we're done
807
+						return $object_to_remove_or_index_into_array;
808
+					}
809
+				}
810
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
811
+				//so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
812
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
813
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
814
+						$index_in_cache = $index;
815
+					}
816
+				}
817
+			} else {
818
+				$index_in_cache = $object_to_remove_or_index_into_array;
819
+			}
820
+			//supposedly we've found it. But it could just be that the client code
821
+			//provided a bad index/object
822
+			if (
823
+			isset(
824
+				$this->_model_relations[$relationName],
825
+				$this->_model_relations[$relationName][$index_in_cache]
826
+			)
827
+			) {
828
+				$obj_removed = $this->_model_relations[$relationName][$index_in_cache];
829
+				unset($this->_model_relations[$relationName][$index_in_cache]);
830
+			} else {
831
+				//that thing was never cached anyways.
832
+				$obj_removed = null;
833
+			}
834
+		}
835
+		return $obj_removed;
836
+	}
837
+
838
+
839
+
840
+	/**
841
+	 * update_cache_after_object_save
842
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
843
+	 * obtained after being saved to the db
844
+	 *
845
+	 * @param string         $relationName       - the type of object that is cached
846
+	 * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
847
+	 * @param string         $current_cache_id   - the ID that was used when originally caching the object
848
+	 * @return boolean TRUE on success, FALSE on fail
849
+	 * @throws \EE_Error
850
+	 */
851
+	public function update_cache_after_object_save(
852
+		$relationName,
853
+		EE_Base_Class $newly_saved_object,
854
+		$current_cache_id = ''
855
+	) {
856
+		// verify that incoming object is of the correct type
857
+		$obj_class = 'EE_' . $relationName;
858
+		if ($newly_saved_object instanceof $obj_class) {
859
+			/* @type EE_Base_Class $newly_saved_object */
860
+			// now get the type of relation
861
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
862
+			// if this is a 1:1 relationship
863
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
864
+				// then just replace the cached object with the newly saved object
865
+				$this->_model_relations[$relationName] = $newly_saved_object;
866
+				return true;
867
+				// or if it's some kind of sordid feral polyamorous relationship...
868
+			} elseif (is_array($this->_model_relations[$relationName])
869
+					  && isset($this->_model_relations[$relationName][$current_cache_id])
870
+			) {
871
+				// then remove the current cached item
872
+				unset($this->_model_relations[$relationName][$current_cache_id]);
873
+				// and cache the newly saved object using it's new ID
874
+				$this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
875
+				return true;
876
+			}
877
+		}
878
+		return false;
879
+	}
880
+
881
+
882
+
883
+	/**
884
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
885
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
886
+	 *
887
+	 * @param string $relationName
888
+	 * @return EE_Base_Class
889
+	 */
890
+	public function get_one_from_cache($relationName)
891
+	{
892
+		$cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
893
+			: null;
894
+		if (is_array($cached_array_or_object)) {
895
+			return array_shift($cached_array_or_object);
896
+		} else {
897
+			return $cached_array_or_object;
898
+		}
899
+	}
900
+
901
+
902
+
903
+	/**
904
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
905
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
906
+	 *
907
+	 * @param string $relationName
908
+	 * @throws \EE_Error
909
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
910
+	 */
911
+	public function get_all_from_cache($relationName)
912
+	{
913
+		$objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
914
+		// if the result is not an array, but exists, make it an array
915
+		$objects = is_array($objects) ? $objects : array($objects);
916
+		//bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
917
+		//basically, if this model object was stored in the session, and these cached model objects
918
+		//already have IDs, let's make sure they're in their model's entity mapper
919
+		//otherwise we will have duplicates next time we call
920
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
921
+		$model = EE_Registry::instance()->load_model($relationName);
922
+		foreach ($objects as $model_object) {
923
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
924
+				//ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
925
+				if ($model_object->ID()) {
926
+					$model->add_to_entity_map($model_object);
927
+				}
928
+			} else {
929
+				throw new EE_Error(
930
+					sprintf(
931
+						__(
932
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
933
+							'event_espresso'
934
+						),
935
+						$relationName,
936
+						gettype($model_object)
937
+					)
938
+				);
939
+			}
940
+		}
941
+		return $objects;
942
+	}
943
+
944
+
945
+
946
+	/**
947
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
948
+	 * matching the given query conditions.
949
+	 *
950
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
951
+	 * @param int   $limit              How many objects to return.
952
+	 * @param array $query_params       Any additional conditions on the query.
953
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
954
+	 *                                  you can indicate just the columns you want returned
955
+	 * @return array|EE_Base_Class[]
956
+	 * @throws \EE_Error
957
+	 */
958
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
959
+	{
960
+		$model = $this->get_model();
961
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
962
+			? $model->get_primary_key_field()->get_name()
963
+			: $field_to_order_by;
964
+		$current_value = ! empty($field) ? $this->get($field) : null;
965
+		if (empty($field) || empty($current_value)) {
966
+			return array();
967
+		}
968
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
969
+	}
970
+
971
+
972
+
973
+	/**
974
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
975
+	 * matching the given query conditions.
976
+	 *
977
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
978
+	 * @param int   $limit              How many objects to return.
979
+	 * @param array $query_params       Any additional conditions on the query.
980
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
981
+	 *                                  you can indicate just the columns you want returned
982
+	 * @return array|EE_Base_Class[]
983
+	 * @throws \EE_Error
984
+	 */
985
+	public function previous_x(
986
+		$field_to_order_by = null,
987
+		$limit = 1,
988
+		$query_params = array(),
989
+		$columns_to_select = null
990
+	) {
991
+		$model = $this->get_model();
992
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
993
+			? $model->get_primary_key_field()->get_name()
994
+			: $field_to_order_by;
995
+		$current_value = ! empty($field) ? $this->get($field) : null;
996
+		if (empty($field) || empty($current_value)) {
997
+			return array();
998
+		}
999
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1000
+	}
1001
+
1002
+
1003
+
1004
+	/**
1005
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1006
+	 * matching the given query conditions.
1007
+	 *
1008
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1009
+	 * @param array $query_params       Any additional conditions on the query.
1010
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1011
+	 *                                  you can indicate just the columns you want returned
1012
+	 * @return array|EE_Base_Class
1013
+	 * @throws \EE_Error
1014
+	 */
1015
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1016
+	{
1017
+		$model = $this->get_model();
1018
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1019
+			? $model->get_primary_key_field()->get_name()
1020
+			: $field_to_order_by;
1021
+		$current_value = ! empty($field) ? $this->get($field) : null;
1022
+		if (empty($field) || empty($current_value)) {
1023
+			return array();
1024
+		}
1025
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1026
+	}
1027
+
1028
+
1029
+
1030
+	/**
1031
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1032
+	 * matching the given query conditions.
1033
+	 *
1034
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1035
+	 * @param array $query_params       Any additional conditions on the query.
1036
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1037
+	 *                                  you can indicate just the column you want returned
1038
+	 * @return array|EE_Base_Class
1039
+	 * @throws \EE_Error
1040
+	 */
1041
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1042
+	{
1043
+		$model = $this->get_model();
1044
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1045
+			? $model->get_primary_key_field()->get_name()
1046
+			: $field_to_order_by;
1047
+		$current_value = ! empty($field) ? $this->get($field) : null;
1048
+		if (empty($field) || empty($current_value)) {
1049
+			return array();
1050
+		}
1051
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1052
+	}
1053
+
1054
+
1055
+
1056
+	/**
1057
+	 * Overrides parent because parent expects old models.
1058
+	 * This also doesn't do any validation, and won't work for serialized arrays
1059
+	 *
1060
+	 * @param string $field_name
1061
+	 * @param mixed  $field_value_from_db
1062
+	 * @throws \EE_Error
1063
+	 */
1064
+	public function set_from_db($field_name, $field_value_from_db)
1065
+	{
1066
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1067
+		if ($field_obj instanceof EE_Model_Field_Base) {
1068
+			//you would think the DB has no NULLs for non-null label fields right? wrong!
1069
+			//eg, a CPT model object could have an entry in the posts table, but no
1070
+			//entry in the meta table. Meaning that all its columns in the meta table
1071
+			//are null! yikes! so when we find one like that, use defaults for its meta columns
1072
+			if ($field_value_from_db === null) {
1073
+				if ($field_obj->is_nullable()) {
1074
+					//if the field allows nulls, then let it be null
1075
+					$field_value = null;
1076
+				} else {
1077
+					$field_value = $field_obj->get_default_value();
1078
+				}
1079
+			} else {
1080
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1081
+			}
1082
+			$this->_fields[$field_name] = $field_value;
1083
+			$this->_clear_cached_property($field_name);
1084
+		}
1085
+	}
1086
+
1087
+
1088
+
1089
+	/**
1090
+	 * verifies that the specified field is of the correct type
1091
+	 *
1092
+	 * @param string $field_name
1093
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1094
+	 *                                (in cases where the same property may be used for different outputs
1095
+	 *                                - i.e. datetime, money etc.)
1096
+	 * @return mixed
1097
+	 * @throws \EE_Error
1098
+	 */
1099
+	public function get($field_name, $extra_cache_ref = null)
1100
+	{
1101
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1102
+	}
1103
+
1104
+
1105
+
1106
+	/**
1107
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1108
+	 *
1109
+	 * @param  string $field_name A valid fieldname
1110
+	 * @return mixed              Whatever the raw value stored on the property is.
1111
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1112
+	 */
1113
+	public function get_raw($field_name)
1114
+	{
1115
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1116
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1117
+			? $this->_fields[$field_name]->format('U')
1118
+			: $this->_fields[$field_name];
1119
+	}
1120
+
1121
+
1122
+
1123
+	/**
1124
+	 * This is used to return the internal DateTime object used for a field that is a
1125
+	 * EE_Datetime_Field.
1126
+	 *
1127
+	 * @param string $field_name               The field name retrieving the DateTime object.
1128
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1129
+	 * @throws \EE_Error
1130
+	 *                                         an error is set and false returned.  If the field IS an
1131
+	 *                                         EE_Datetime_Field and but the field value is null, then
1132
+	 *                                         just null is returned (because that indicates that likely
1133
+	 *                                         this field is nullable).
1134
+	 */
1135
+	public function get_DateTime_object($field_name)
1136
+	{
1137
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1138
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1139
+			EE_Error::add_error(
1140
+				sprintf(
1141
+					__(
1142
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1143
+						'event_espresso'
1144
+					),
1145
+					$field_name
1146
+				),
1147
+				__FILE__,
1148
+				__FUNCTION__,
1149
+				__LINE__
1150
+			);
1151
+			return false;
1152
+		}
1153
+		return $this->_fields[$field_name];
1154
+	}
1155
+
1156
+
1157
+
1158
+	/**
1159
+	 * To be used in template to immediately echo out the value, and format it for output.
1160
+	 * Eg, should call stripslashes and whatnot before echoing
1161
+	 *
1162
+	 * @param string $field_name      the name of the field as it appears in the DB
1163
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1164
+	 *                                (in cases where the same property may be used for different outputs
1165
+	 *                                - i.e. datetime, money etc.)
1166
+	 * @return void
1167
+	 * @throws \EE_Error
1168
+	 */
1169
+	public function e($field_name, $extra_cache_ref = null)
1170
+	{
1171
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1172
+	}
1173
+
1174
+
1175
+
1176
+	/**
1177
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1178
+	 * can be easily used as the value of form input.
1179
+	 *
1180
+	 * @param string $field_name
1181
+	 * @return void
1182
+	 * @throws \EE_Error
1183
+	 */
1184
+	public function f($field_name)
1185
+	{
1186
+		$this->e($field_name, 'form_input');
1187
+	}
1188
+
1189
+
1190
+
1191
+	/**
1192
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1193
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1194
+	 * to see what options are available.
1195
+	 * @param string $field_name
1196
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1197
+	 *                                (in cases where the same property may be used for different outputs
1198
+	 *                                - i.e. datetime, money etc.)
1199
+	 * @return mixed
1200
+	 * @throws \EE_Error
1201
+	 */
1202
+	public function get_pretty($field_name, $extra_cache_ref = null)
1203
+	{
1204
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1205
+	}
1206
+
1207
+
1208
+
1209
+	/**
1210
+	 * This simply returns the datetime for the given field name
1211
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1212
+	 * (and the equivalent e_date, e_time, e_datetime).
1213
+	 *
1214
+	 * @access   protected
1215
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1216
+	 * @param string   $dt_frmt      valid datetime format used for date
1217
+	 *                               (if '' then we just use the default on the field,
1218
+	 *                               if NULL we use the last-used format)
1219
+	 * @param string   $tm_frmt      Same as above except this is for time format
1220
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1221
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1222
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1223
+	 *                               if field is not a valid dtt field, or void if echoing
1224
+	 * @throws \EE_Error
1225
+	 */
1226
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1227
+	{
1228
+		// clear cached property
1229
+		$this->_clear_cached_property($field_name);
1230
+		//reset format properties because they are used in get()
1231
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1232
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1233
+		if ($echo) {
1234
+			$this->e($field_name, $date_or_time);
1235
+			return '';
1236
+		}
1237
+		return $this->get($field_name, $date_or_time);
1238
+	}
1239
+
1240
+
1241
+
1242
+	/**
1243
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1244
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1245
+	 * other echoes the pretty value for dtt)
1246
+	 *
1247
+	 * @param  string $field_name name of model object datetime field holding the value
1248
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1249
+	 * @return string            datetime value formatted
1250
+	 * @throws \EE_Error
1251
+	 */
1252
+	public function get_date($field_name, $format = '')
1253
+	{
1254
+		return $this->_get_datetime($field_name, $format, null, 'D');
1255
+	}
1256
+
1257
+
1258
+
1259
+	/**
1260
+	 * @param      $field_name
1261
+	 * @param string $format
1262
+	 * @throws \EE_Error
1263
+	 */
1264
+	public function e_date($field_name, $format = '')
1265
+	{
1266
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1267
+	}
1268
+
1269
+
1270
+
1271
+	/**
1272
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1273
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1274
+	 * other echoes the pretty value for dtt)
1275
+	 *
1276
+	 * @param  string $field_name name of model object datetime field holding the value
1277
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1278
+	 * @return string             datetime value formatted
1279
+	 * @throws \EE_Error
1280
+	 */
1281
+	public function get_time($field_name, $format = '')
1282
+	{
1283
+		return $this->_get_datetime($field_name, null, $format, 'T');
1284
+	}
1285
+
1286
+
1287
+
1288
+	/**
1289
+	 * @param      $field_name
1290
+	 * @param string $format
1291
+	 * @throws \EE_Error
1292
+	 */
1293
+	public function e_time($field_name, $format = '')
1294
+	{
1295
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1296
+	}
1297
+
1298
+
1299
+
1300
+	/**
1301
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1302
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1303
+	 * other echoes the pretty value for dtt)
1304
+	 *
1305
+	 * @param  string $field_name name of model object datetime field holding the value
1306
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1307
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1308
+	 * @return string             datetime value formatted
1309
+	 * @throws \EE_Error
1310
+	 */
1311
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1312
+	{
1313
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1314
+	}
1315
+
1316
+
1317
+
1318
+	/**
1319
+	 * @param string $field_name
1320
+	 * @param string $dt_frmt
1321
+	 * @param string $tm_frmt
1322
+	 * @throws \EE_Error
1323
+	 */
1324
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1325
+	{
1326
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1327
+	}
1328
+
1329
+
1330
+
1331
+	/**
1332
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1333
+	 *
1334
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1335
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1336
+	 *                           on the object will be used.
1337
+	 * @return string Date and time string in set locale or false if no field exists for the given
1338
+	 * @throws \EE_Error
1339
+	 *                           field name.
1340
+	 */
1341
+	public function get_i18n_datetime($field_name, $format = '')
1342
+	{
1343
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1344
+		return date_i18n(
1345
+			$format,
1346
+			EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1347
+		);
1348
+	}
1349
+
1350
+
1351
+
1352
+	/**
1353
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1354
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1355
+	 * thrown.
1356
+	 *
1357
+	 * @param  string $field_name The field name being checked
1358
+	 * @throws EE_Error
1359
+	 * @return EE_Datetime_Field
1360
+	 */
1361
+	protected function _get_dtt_field_settings($field_name)
1362
+	{
1363
+		$field = $this->get_model()->field_settings_for($field_name);
1364
+		//check if field is dtt
1365
+		if ($field instanceof EE_Datetime_Field) {
1366
+			return $field;
1367
+		} else {
1368
+			throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1369
+				'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1370
+		}
1371
+	}
1372
+
1373
+
1374
+
1375
+
1376
+	/**
1377
+	 * NOTE ABOUT BELOW:
1378
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1379
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1380
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1381
+	 * method and make sure you send the entire datetime value for setting.
1382
+	 */
1383
+	/**
1384
+	 * sets the time on a datetime property
1385
+	 *
1386
+	 * @access protected
1387
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1388
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1389
+	 * @throws \EE_Error
1390
+	 */
1391
+	protected function _set_time_for($time, $fieldname)
1392
+	{
1393
+		$this->_set_date_time('T', $time, $fieldname);
1394
+	}
1395
+
1396
+
1397
+
1398
+	/**
1399
+	 * sets the date on a datetime property
1400
+	 *
1401
+	 * @access protected
1402
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1403
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1404
+	 * @throws \EE_Error
1405
+	 */
1406
+	protected function _set_date_for($date, $fieldname)
1407
+	{
1408
+		$this->_set_date_time('D', $date, $fieldname);
1409
+	}
1410
+
1411
+
1412
+
1413
+	/**
1414
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1415
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1416
+	 *
1417
+	 * @access protected
1418
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1419
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1420
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1421
+	 *                                        EE_Datetime_Field property)
1422
+	 * @throws \EE_Error
1423
+	 */
1424
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1425
+	{
1426
+		$field = $this->_get_dtt_field_settings($fieldname);
1427
+		$field->set_timezone($this->_timezone);
1428
+		$field->set_date_format($this->_dt_frmt);
1429
+		$field->set_time_format($this->_tm_frmt);
1430
+		switch ($what) {
1431
+			case 'T' :
1432
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1433
+					$datetime_value,
1434
+					$this->_fields[$fieldname]
1435
+				);
1436
+				break;
1437
+			case 'D' :
1438
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1439
+					$datetime_value,
1440
+					$this->_fields[$fieldname]
1441
+				);
1442
+				break;
1443
+			case 'B' :
1444
+				$this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1445
+				break;
1446
+		}
1447
+		$this->_clear_cached_property($fieldname);
1448
+	}
1449
+
1450
+
1451
+
1452
+	/**
1453
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1454
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1455
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1456
+	 * that could lead to some unexpected results!
1457
+	 *
1458
+	 * @access public
1459
+	 * @param string               $field_name This is the name of the field on the object that contains the date/time
1460
+	 *                                         value being returned.
1461
+	 * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1462
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1463
+	 * @param string               $prepend    You can include something to prepend on the timestamp
1464
+	 * @param string               $append     You can include something to append on the timestamp
1465
+	 * @throws EE_Error
1466
+	 * @return string timestamp
1467
+	 */
1468
+	public function display_in_my_timezone(
1469
+		$field_name,
1470
+		$callback = 'get_datetime',
1471
+		$args = null,
1472
+		$prepend = '',
1473
+		$append = ''
1474
+	) {
1475
+		$timezone = EEH_DTT_Helper::get_timezone();
1476
+		if ($timezone === $this->_timezone) {
1477
+			return '';
1478
+		}
1479
+		$original_timezone = $this->_timezone;
1480
+		$this->set_timezone($timezone);
1481
+		$fn = (array)$field_name;
1482
+		$args = array_merge($fn, (array)$args);
1483
+		if ( ! method_exists($this, $callback)) {
1484
+			throw new EE_Error(
1485
+				sprintf(
1486
+					__(
1487
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1488
+						'event_espresso'
1489
+					),
1490
+					$callback
1491
+				)
1492
+			);
1493
+		}
1494
+		$args = (array)$args;
1495
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1496
+		$this->set_timezone($original_timezone);
1497
+		return $return;
1498
+	}
1499
+
1500
+
1501
+
1502
+	/**
1503
+	 * Deletes this model object.
1504
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1505
+	 * override
1506
+	 * `EE_Base_Class::_delete` NOT this class.
1507
+	 *
1508
+	 * @return boolean | int
1509
+	 * @throws \EE_Error
1510
+	 */
1511
+	public function delete()
1512
+	{
1513
+		/**
1514
+		 * Called just before the `EE_Base_Class::_delete` method call.
1515
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1516
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1517
+		 * soft deletes (trash) the object and does not permanently delete it.
1518
+		 *
1519
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1520
+		 */
1521
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1522
+		$result = $this->_delete();
1523
+		/**
1524
+		 * Called just after the `EE_Base_Class::_delete` method call.
1525
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1526
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1527
+		 * soft deletes (trash) the object and does not permanently delete it.
1528
+		 *
1529
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1530
+		 * @param boolean       $result
1531
+		 */
1532
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1533
+		return $result;
1534
+	}
1535
+
1536
+
1537
+
1538
+	/**
1539
+	 * Calls the specific delete method for the instantiated class.
1540
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1541
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1542
+	 * `EE_Base_Class::delete`
1543
+	 *
1544
+	 * @return bool|int
1545
+	 * @throws \EE_Error
1546
+	 */
1547
+	protected function _delete()
1548
+	{
1549
+		return $this->delete_permanently();
1550
+	}
1551
+
1552
+
1553
+
1554
+	/**
1555
+	 * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1556
+	 * error)
1557
+	 *
1558
+	 * @return bool | int
1559
+	 * @throws \EE_Error
1560
+	 */
1561
+	public function delete_permanently()
1562
+	{
1563
+		/**
1564
+		 * Called just before HARD deleting a model object
1565
+		 *
1566
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1567
+		 */
1568
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1569
+		$model = $this->get_model();
1570
+		$result = $model->delete_permanently_by_ID($this->ID());
1571
+		$this->refresh_cache_of_related_objects();
1572
+		/**
1573
+		 * Called just after HARD deleting a model object
1574
+		 *
1575
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1576
+		 * @param boolean       $result
1577
+		 */
1578
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1579
+		return $result;
1580
+	}
1581
+
1582
+
1583
+
1584
+	/**
1585
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1586
+	 * related model objects
1587
+	 *
1588
+	 * @throws \EE_Error
1589
+	 */
1590
+	public function refresh_cache_of_related_objects()
1591
+	{
1592
+		$model = $this->get_model();
1593
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1594
+			if ( ! empty($this->_model_relations[$relation_name])) {
1595
+				$related_objects = $this->_model_relations[$relation_name];
1596
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1597
+					//this relation only stores a single model object, not an array
1598
+					//but let's make it consistent
1599
+					$related_objects = array($related_objects);
1600
+				}
1601
+				foreach ($related_objects as $related_object) {
1602
+					//only refresh their cache if they're in memory
1603
+					if ($related_object instanceof EE_Base_Class) {
1604
+						$related_object->clear_cache($model->get_this_model_name(), $this);
1605
+					}
1606
+				}
1607
+			}
1608
+		}
1609
+	}
1610
+
1611
+
1612
+
1613
+	/**
1614
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1615
+	 * object just before saving.
1616
+	 *
1617
+	 * @access public
1618
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1619
+	 *                                 if provided during the save() method (often client code will change the fields'
1620
+	 *                                 values before calling save)
1621
+	 * @throws \EE_Error
1622
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1623
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1624
+	 */
1625
+	public function save($set_cols_n_values = array())
1626
+	{
1627
+		$model = $this->get_model();
1628
+		/**
1629
+		 * Filters the fields we're about to save on the model object
1630
+		 *
1631
+		 * @param array         $set_cols_n_values
1632
+		 * @param EE_Base_Class $model_object
1633
+		 */
1634
+		$set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1635
+			$this);
1636
+		//set attributes as provided in $set_cols_n_values
1637
+		foreach ($set_cols_n_values as $column => $value) {
1638
+			$this->set($column, $value);
1639
+		}
1640
+		// no changes ? then don't do anything
1641
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1642
+			return 0;
1643
+		}
1644
+		/**
1645
+		 * Saving a model object.
1646
+		 * Before we perform a save, this action is fired.
1647
+		 *
1648
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1649
+		 */
1650
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1651
+		if ( ! $this->allow_persist()) {
1652
+			return 0;
1653
+		}
1654
+		//now get current attribute values
1655
+		$save_cols_n_values = $this->_fields;
1656
+		//if the object already has an ID, update it. Otherwise, insert it
1657
+		//also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1658
+		$old_assumption_concerning_value_preparation = $model
1659
+															->get_assumption_concerning_values_already_prepared_by_model_object();
1660
+		$model->assume_values_already_prepared_by_model_object(true);
1661
+		//does this model have an autoincrement PK?
1662
+		if ($model->has_primary_key_field()) {
1663
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1664
+				//ok check if it's set, if so: update; if not, insert
1665
+				if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1666
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1667
+				} else {
1668
+					unset($save_cols_n_values[$model->primary_key_name()]);
1669
+					$results = $model->insert($save_cols_n_values);
1670
+					if ($results) {
1671
+						//if successful, set the primary key
1672
+						//but don't use the normal SET method, because it will check if
1673
+						//an item with the same ID exists in the mapper & db, then
1674
+						//will find it in the db (because we just added it) and THAT object
1675
+						//will get added to the mapper before we can add this one!
1676
+						//but if we just avoid using the SET method, all that headache can be avoided
1677
+						$pk_field_name = $model->primary_key_name();
1678
+						$this->_fields[$pk_field_name] = $results;
1679
+						$this->_clear_cached_property($pk_field_name);
1680
+						$model->add_to_entity_map($this);
1681
+						$this->_update_cached_related_model_objs_fks();
1682
+					}
1683
+				}
1684
+			} else {//PK is NOT auto-increment
1685
+				//so check if one like it already exists in the db
1686
+				if ($model->exists_by_ID($this->ID())) {
1687
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1688
+						throw new EE_Error(
1689
+							sprintf(
1690
+								__('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1691
+									'event_espresso'),
1692
+								get_class($this),
1693
+								get_class($model) . '::instance()->add_to_entity_map()',
1694
+								get_class($model) . '::instance()->get_one_by_ID()',
1695
+								'<br />'
1696
+							)
1697
+						);
1698
+					}
1699
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1700
+				} else {
1701
+					$results = $model->insert($save_cols_n_values);
1702
+					$this->_update_cached_related_model_objs_fks();
1703
+				}
1704
+			}
1705
+		} else {//there is NO primary key
1706
+			$already_in_db = false;
1707
+			foreach ($model->unique_indexes() as $index) {
1708
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1709
+				if ($model->exists(array($uniqueness_where_params))) {
1710
+					$already_in_db = true;
1711
+				}
1712
+			}
1713
+			if ($already_in_db) {
1714
+				$combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1715
+					$model->get_combined_primary_key_fields());
1716
+				$results = $model->update($save_cols_n_values, $combined_pk_fields_n_values);
1717
+			} else {
1718
+				$results = $model->insert($save_cols_n_values);
1719
+			}
1720
+		}
1721
+		//restore the old assumption about values being prepared by the model object
1722
+		$model
1723
+			 ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1724
+		/**
1725
+		 * After saving the model object this action is called
1726
+		 *
1727
+		 * @param EE_Base_Class $model_object which was just saved
1728
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1729
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1730
+		 */
1731
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1732
+		$this->_has_changes = false;
1733
+		return $results;
1734
+	}
1735
+
1736
+
1737
+
1738
+	/**
1739
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1740
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1741
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1742
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1743
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1744
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1745
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1746
+	 *
1747
+	 * @return void
1748
+	 * @throws \EE_Error
1749
+	 */
1750
+	protected function _update_cached_related_model_objs_fks()
1751
+	{
1752
+		$model = $this->get_model();
1753
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1754
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1755
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1756
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1757
+						$model->get_this_model_name()
1758
+					);
1759
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1760
+					if ($related_model_obj_in_cache->ID()) {
1761
+						$related_model_obj_in_cache->save();
1762
+					}
1763
+				}
1764
+			}
1765
+		}
1766
+	}
1767
+
1768
+
1769
+
1770
+	/**
1771
+	 * Saves this model object and its NEW cached relations to the database.
1772
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1773
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1774
+	 * because otherwise, there's a potential for infinite looping of saving
1775
+	 * Saves the cached related model objects, and ensures the relation between them
1776
+	 * and this object and properly setup
1777
+	 *
1778
+	 * @return int ID of new model object on save; 0 on failure+
1779
+	 * @throws \EE_Error
1780
+	 */
1781
+	public function save_new_cached_related_model_objs()
1782
+	{
1783
+		//make sure this has been saved
1784
+		if ( ! $this->ID()) {
1785
+			$id = $this->save();
1786
+		} else {
1787
+			$id = $this->ID();
1788
+		}
1789
+		//now save all the NEW cached model objects  (ie they don't exist in the DB)
1790
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1791
+			if ($this->_model_relations[$relationName]) {
1792
+				//is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1793
+				//or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1794
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1795
+					//add a relation to that relation type (which saves the appropriate thing in the process)
1796
+					//but ONLY if it DOES NOT exist in the DB
1797
+					/* @var $related_model_obj EE_Base_Class */
1798
+					$related_model_obj = $this->_model_relations[$relationName];
1799
+					//					if( ! $related_model_obj->ID()){
1800
+					$this->_add_relation_to($related_model_obj, $relationName);
1801
+					$related_model_obj->save_new_cached_related_model_objs();
1802
+					//					}
1803
+				} else {
1804
+					foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1805
+						//add a relation to that relation type (which saves the appropriate thing in the process)
1806
+						//but ONLY if it DOES NOT exist in the DB
1807
+						//						if( ! $related_model_obj->ID()){
1808
+						$this->_add_relation_to($related_model_obj, $relationName);
1809
+						$related_model_obj->save_new_cached_related_model_objs();
1810
+						//						}
1811
+					}
1812
+				}
1813
+			}
1814
+		}
1815
+		return $id;
1816
+	}
1817
+
1818
+
1819
+
1820
+	/**
1821
+	 * for getting a model while instantiated.
1822
+	 *
1823
+	 * @return \EEM_Base | \EEM_CPT_Base
1824
+	 */
1825
+	public function get_model()
1826
+	{
1827
+		if( ! $this->_model){
1828
+			$modelName = self::_get_model_classname(get_class($this));
1829
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
1830
+		} else {
1831
+			$this->_model->set_timezone($this->_timezone);
1832
+		}
1833
+
1834
+		return $this->_model;
1835
+	}
1836
+
1837
+
1838
+
1839
+	/**
1840
+	 * @param $props_n_values
1841
+	 * @param $classname
1842
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1843
+	 * @throws \EE_Error
1844
+	 */
1845
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1846
+	{
1847
+		//TODO: will not work for Term_Relationships because they have no PK!
1848
+		$primary_id_ref = self::_get_primary_key_name($classname);
1849
+		if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1850
+			$id = $props_n_values[$primary_id_ref];
1851
+			return self::_get_model($classname)->get_from_entity_map($id);
1852
+		}
1853
+		return false;
1854
+	}
1855
+
1856
+
1857
+
1858
+	/**
1859
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1860
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1861
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1862
+	 * we return false.
1863
+	 *
1864
+	 * @param  array  $props_n_values   incoming array of properties and their values
1865
+	 * @param  string $classname        the classname of the child class
1866
+	 * @param null    $timezone
1867
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
1868
+	 *                                  date_format and the second value is the time format
1869
+	 * @return mixed (EE_Base_Class|bool)
1870
+	 * @throws \EE_Error
1871
+	 */
1872
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1873
+	{
1874
+		$existing = null;
1875
+		$model = self::_get_model($classname, $timezone);
1876
+		if ($model->has_primary_key_field()) {
1877
+			$primary_id_ref = self::_get_primary_key_name($classname);
1878
+			if (array_key_exists($primary_id_ref, $props_n_values)
1879
+				&& ! empty($props_n_values[$primary_id_ref])
1880
+			) {
1881
+				$existing = $model->get_one_by_ID(
1882
+					$props_n_values[$primary_id_ref]
1883
+				);
1884
+			}
1885
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
1886
+			//no primary key on this model, but there's still a matching item in the DB
1887
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1888
+				self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1889
+			);
1890
+		}
1891
+		if ($existing) {
1892
+			//set date formats if present before setting values
1893
+			if ( ! empty($date_formats) && is_array($date_formats)) {
1894
+				$existing->set_date_format($date_formats[0]);
1895
+				$existing->set_time_format($date_formats[1]);
1896
+			} else {
1897
+				//set default formats for date and time
1898
+				$existing->set_date_format(get_option('date_format'));
1899
+				$existing->set_time_format(get_option('time_format'));
1900
+			}
1901
+			foreach ($props_n_values as $property => $field_value) {
1902
+				$existing->set($property, $field_value);
1903
+			}
1904
+			return $existing;
1905
+		} else {
1906
+			return false;
1907
+		}
1908
+	}
1909
+
1910
+
1911
+
1912
+	/**
1913
+	 * Gets the EEM_*_Model for this class
1914
+	 *
1915
+	 * @access public now, as this is more convenient
1916
+	 * @param      $classname
1917
+	 * @param null $timezone
1918
+	 * @throws EE_Error
1919
+	 * @return EEM_Base
1920
+	 */
1921
+	protected static function _get_model($classname, $timezone = null)
1922
+	{
1923
+		//find model for this class
1924
+		if ( ! $classname) {
1925
+			throw new EE_Error(
1926
+				sprintf(
1927
+					__(
1928
+						"What were you thinking calling _get_model(%s)?? You need to specify the class name",
1929
+						"event_espresso"
1930
+					),
1931
+					$classname
1932
+				)
1933
+			);
1934
+		}
1935
+		$modelName = self::_get_model_classname($classname);
1936
+		return self::_get_model_instance_with_name($modelName, $timezone);
1937
+	}
1938
+
1939
+
1940
+
1941
+	/**
1942
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1943
+	 *
1944
+	 * @param string $model_classname
1945
+	 * @param null   $timezone
1946
+	 * @return EEM_Base
1947
+	 */
1948
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1949
+	{
1950
+		$model_classname = str_replace('EEM_', '', $model_classname);
1951
+		$model = EE_Registry::instance()->load_model($model_classname);
1952
+		$model->set_timezone($timezone);
1953
+		return $model;
1954
+	}
1955
+
1956
+
1957
+
1958
+	/**
1959
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
1960
+	 * Also works if a model class's classname is provided (eg EE_Registration).
1961
+	 *
1962
+	 * @param null $model_name
1963
+	 * @return string like EEM_Attendee
1964
+	 */
1965
+	private static function _get_model_classname($model_name = null)
1966
+	{
1967
+		if (strpos($model_name, "EE_") === 0) {
1968
+			$model_classname = str_replace("EE_", "EEM_", $model_name);
1969
+		} else {
1970
+			$model_classname = "EEM_" . $model_name;
1971
+		}
1972
+		return $model_classname;
1973
+	}
1974
+
1975
+
1976
+
1977
+	/**
1978
+	 * returns the name of the primary key attribute
1979
+	 *
1980
+	 * @param null $classname
1981
+	 * @throws EE_Error
1982
+	 * @return string
1983
+	 */
1984
+	protected static function _get_primary_key_name($classname = null)
1985
+	{
1986
+		if ( ! $classname) {
1987
+			throw new EE_Error(
1988
+				sprintf(
1989
+					__("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1990
+					$classname
1991
+				)
1992
+			);
1993
+		}
1994
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
1995
+	}
1996
+
1997
+
1998
+
1999
+	/**
2000
+	 * Gets the value of the primary key.
2001
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2002
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2003
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2004
+	 *
2005
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2006
+	 * @throws \EE_Error
2007
+	 */
2008
+	public function ID()
2009
+	{
2010
+		$model = $this->get_model();
2011
+		//now that we know the name of the variable, use a variable variable to get its value and return its
2012
+		if ($model->has_primary_key_field()) {
2013
+			return $this->_fields[$model->primary_key_name()];
2014
+		} else {
2015
+			return $model->get_index_primary_key_string($this->_fields);
2016
+		}
2017
+	}
2018
+
2019
+
2020
+
2021
+	/**
2022
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2023
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2024
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2025
+	 *
2026
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2027
+	 * @param string $relationName                     eg 'Events','Question',etc.
2028
+	 *                                                 an attendee to a group, you also want to specify which role they
2029
+	 *                                                 will have in that group. So you would use this parameter to
2030
+	 *                                                 specify array('role-column-name'=>'role-id')
2031
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2032
+	 *                                                 allow you to further constrict the relation to being added.
2033
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2034
+	 *                                                 column on the JOIN table and currently only the HABTM models
2035
+	 *                                                 accept these additional conditions.  Also remember that if an
2036
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2037
+	 *                                                 NEW row is created in the join table.
2038
+	 * @param null   $cache_id
2039
+	 * @throws EE_Error
2040
+	 * @return EE_Base_Class the object the relation was added to
2041
+	 */
2042
+	public function _add_relation_to(
2043
+		$otherObjectModelObjectOrID,
2044
+		$relationName,
2045
+		$extra_join_model_fields_n_values = array(),
2046
+		$cache_id = null
2047
+	) {
2048
+		$model = $this->get_model();
2049
+		//if this thing exists in the DB, save the relation to the DB
2050
+		if ($this->ID()) {
2051
+			$otherObject = $model
2052
+								->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2053
+									$extra_join_model_fields_n_values);
2054
+			//clear cache so future get_many_related and get_first_related() return new results.
2055
+			$this->clear_cache($relationName, $otherObject, true);
2056
+			if ($otherObject instanceof EE_Base_Class) {
2057
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2058
+			}
2059
+		} else {
2060
+			//this thing doesn't exist in the DB,  so just cache it
2061
+			if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2062
+				throw new EE_Error(sprintf(
2063
+					__('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2064
+						'event_espresso'),
2065
+					$otherObjectModelObjectOrID,
2066
+					get_class($this)
2067
+				));
2068
+			} else {
2069
+				$otherObject = $otherObjectModelObjectOrID;
2070
+			}
2071
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2072
+		}
2073
+		if ($otherObject instanceof EE_Base_Class) {
2074
+			//fix the reciprocal relation too
2075
+			if ($otherObject->ID()) {
2076
+				//its saved so assumed relations exist in the DB, so we can just
2077
+				//clear the cache so future queries use the updated info in the DB
2078
+				$otherObject->clear_cache($model->get_this_model_name(), null, true);
2079
+			} else {
2080
+				//it's not saved, so it caches relations like this
2081
+				$otherObject->cache($model->get_this_model_name(), $this);
2082
+			}
2083
+		}
2084
+		return $otherObject;
2085
+	}
2086
+
2087
+
2088
+
2089
+	/**
2090
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2091
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2092
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2093
+	 * from the cache
2094
+	 *
2095
+	 * @param mixed  $otherObjectModelObjectOrID
2096
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2097
+	 *                to the DB yet
2098
+	 * @param string $relationName
2099
+	 * @param array  $where_query
2100
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2101
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2102
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2103
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2104
+	 *                created in the join table.
2105
+	 * @return EE_Base_Class the relation was removed from
2106
+	 * @throws \EE_Error
2107
+	 */
2108
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2109
+	{
2110
+		if ($this->ID()) {
2111
+			//if this exists in the DB, save the relation change to the DB too
2112
+			$otherObject = $this->get_model()
2113
+								->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2114
+									$where_query);
2115
+			$this->clear_cache($relationName, $otherObject);
2116
+		} else {
2117
+			//this doesn't exist in the DB, just remove it from the cache
2118
+			$otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2119
+		}
2120
+		if ($otherObject instanceof EE_Base_Class) {
2121
+			$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2122
+		}
2123
+		return $otherObject;
2124
+	}
2125
+
2126
+
2127
+
2128
+	/**
2129
+	 * Removes ALL the related things for the $relationName.
2130
+	 *
2131
+	 * @param string $relationName
2132
+	 * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2133
+	 * @return EE_Base_Class
2134
+	 * @throws \EE_Error
2135
+	 */
2136
+	public function _remove_relations($relationName, $where_query_params = array())
2137
+	{
2138
+		if ($this->ID()) {
2139
+			//if this exists in the DB, save the relation change to the DB too
2140
+			$otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2141
+			$this->clear_cache($relationName, null, true);
2142
+		} else {
2143
+			//this doesn't exist in the DB, just remove it from the cache
2144
+			$otherObjects = $this->clear_cache($relationName, null, true);
2145
+		}
2146
+		if (is_array($otherObjects)) {
2147
+			foreach ($otherObjects as $otherObject) {
2148
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2149
+			}
2150
+		}
2151
+		return $otherObjects;
2152
+	}
2153
+
2154
+
2155
+
2156
+	/**
2157
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2158
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2159
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2160
+	 * because we want to get even deleted items etc.
2161
+	 *
2162
+	 * @param string $relationName key in the model's _model_relations array
2163
+	 * @param array  $query_params like EEM_Base::get_all
2164
+	 * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2165
+	 * @throws \EE_Error
2166
+	 *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2167
+	 *                             you want IDs
2168
+	 */
2169
+	public function get_many_related($relationName, $query_params = array())
2170
+	{
2171
+		if ($this->ID()) {
2172
+			//this exists in the DB, so get the related things from either the cache or the DB
2173
+			//if there are query parameters, forget about caching the related model objects.
2174
+			if ($query_params) {
2175
+				$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2176
+			} else {
2177
+				//did we already cache the result of this query?
2178
+				$cached_results = $this->get_all_from_cache($relationName);
2179
+				if ( ! $cached_results) {
2180
+					$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2181
+					//if no query parameters were passed, then we got all the related model objects
2182
+					//for that relation. We can cache them then.
2183
+					foreach ($related_model_objects as $related_model_object) {
2184
+						$this->cache($relationName, $related_model_object);
2185
+					}
2186
+				} else {
2187
+					$related_model_objects = $cached_results;
2188
+				}
2189
+			}
2190
+		} else {
2191
+			//this doesn't exist in the DB, so just get the related things from the cache
2192
+			$related_model_objects = $this->get_all_from_cache($relationName);
2193
+		}
2194
+		return $related_model_objects;
2195
+	}
2196
+
2197
+
2198
+
2199
+	/**
2200
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2201
+	 * unless otherwise specified in the $query_params
2202
+	 *
2203
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2204
+	 * @param array  $query_params   like EEM_Base::get_all's
2205
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2206
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2207
+	 *                               that by the setting $distinct to TRUE;
2208
+	 * @return int
2209
+	 */
2210
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2211
+	{
2212
+		return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2213
+	}
2214
+
2215
+
2216
+
2217
+	/**
2218
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2219
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2220
+	 *
2221
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2222
+	 * @param array  $query_params  like EEM_Base::get_all's
2223
+	 * @param string $field_to_sum  name of field to count by.
2224
+	 *                              By default, uses primary key (which doesn't make much sense, so you should probably
2225
+	 *                              change it)
2226
+	 * @return int
2227
+	 */
2228
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2229
+	{
2230
+		return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2231
+	}
2232
+
2233
+
2234
+
2235
+	/**
2236
+	 * Gets the first (ie, one) related model object of the specified type.
2237
+	 *
2238
+	 * @param string $relationName key in the model's _model_relations array
2239
+	 * @param array  $query_params like EEM_Base::get_all
2240
+	 * @return EE_Base_Class (not an array, a single object)
2241
+	 * @throws \EE_Error
2242
+	 */
2243
+	public function get_first_related($relationName, $query_params = array())
2244
+	{
2245
+		$model = $this->get_model();
2246
+		if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2247
+			//if they've provided some query parameters, don't bother trying to cache the result
2248
+			//also make sure we're not caching the result of get_first_related
2249
+			//on a relation which should have an array of objects (because the cache might have an array of objects)
2250
+			if ($query_params
2251
+				|| ! $model->related_settings_for($relationName)
2252
+					 instanceof
2253
+					 EE_Belongs_To_Relation
2254
+			) {
2255
+				$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2256
+			} else {
2257
+				//first, check if we've already cached the result of this query
2258
+				$cached_result = $this->get_one_from_cache($relationName);
2259
+				if ( ! $cached_result) {
2260
+					$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2261
+					$this->cache($relationName, $related_model_object);
2262
+				} else {
2263
+					$related_model_object = $cached_result;
2264
+				}
2265
+			}
2266
+		} else {
2267
+			$related_model_object = null;
2268
+			//this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2269
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2270
+				$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2271
+			}
2272
+			//this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2273
+			if ( ! $related_model_object) {
2274
+				$related_model_object = $this->get_one_from_cache($relationName);
2275
+			}
2276
+		}
2277
+		return $related_model_object;
2278
+	}
2279
+
2280
+
2281
+
2282
+	/**
2283
+	 * Does a delete on all related objects of type $relationName and removes
2284
+	 * the current model object's relation to them. If they can't be deleted (because
2285
+	 * of blocking related model objects) does nothing. If the related model objects are
2286
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2287
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2288
+	 *
2289
+	 * @param string $relationName
2290
+	 * @param array  $query_params like EEM_Base::get_all's
2291
+	 * @return int how many deleted
2292
+	 * @throws \EE_Error
2293
+	 */
2294
+	public function delete_related($relationName, $query_params = array())
2295
+	{
2296
+		if ($this->ID()) {
2297
+			$count = $this->get_model()->delete_related($this, $relationName, $query_params);
2298
+		} else {
2299
+			$count = count($this->get_all_from_cache($relationName));
2300
+			$this->clear_cache($relationName, null, true);
2301
+		}
2302
+		return $count;
2303
+	}
2304
+
2305
+
2306
+
2307
+	/**
2308
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2309
+	 * the current model object's relation to them. If they can't be deleted (because
2310
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2311
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2312
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2313
+	 *
2314
+	 * @param string $relationName
2315
+	 * @param array  $query_params like EEM_Base::get_all's
2316
+	 * @return int how many deleted (including those soft deleted)
2317
+	 * @throws \EE_Error
2318
+	 */
2319
+	public function delete_related_permanently($relationName, $query_params = array())
2320
+	{
2321
+		if ($this->ID()) {
2322
+			$count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2323
+		} else {
2324
+			$count = count($this->get_all_from_cache($relationName));
2325
+		}
2326
+		$this->clear_cache($relationName, null, true);
2327
+		return $count;
2328
+	}
2329
+
2330
+
2331
+
2332
+	/**
2333
+	 * is_set
2334
+	 * Just a simple utility function children can use for checking if property exists
2335
+	 *
2336
+	 * @access  public
2337
+	 * @param  string $field_name property to check
2338
+	 * @return bool                              TRUE if existing,FALSE if not.
2339
+	 */
2340
+	public function is_set($field_name)
2341
+	{
2342
+		return isset($this->_fields[$field_name]);
2343
+	}
2344
+
2345
+
2346
+
2347
+	/**
2348
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2349
+	 * EE_Error exception if they don't
2350
+	 *
2351
+	 * @param  mixed (string|array) $properties properties to check
2352
+	 * @throws EE_Error
2353
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2354
+	 */
2355
+	protected function _property_exists($properties)
2356
+	{
2357
+		foreach ((array)$properties as $property_name) {
2358
+			//first make sure this property exists
2359
+			if ( ! $this->_fields[$property_name]) {
2360
+				throw new EE_Error(
2361
+					sprintf(
2362
+						__(
2363
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2364
+							'event_espresso'
2365
+						),
2366
+						$property_name
2367
+					)
2368
+				);
2369
+			}
2370
+		}
2371
+		return true;
2372
+	}
2373
+
2374
+
2375
+
2376
+	/**
2377
+	 * This simply returns an array of model fields for this object
2378
+	 *
2379
+	 * @return array
2380
+	 * @throws \EE_Error
2381
+	 */
2382
+	public function model_field_array()
2383
+	{
2384
+		$fields = $this->get_model()->field_settings(false);
2385
+		$properties = array();
2386
+		//remove prepended underscore
2387
+		foreach ($fields as $field_name => $settings) {
2388
+			$properties[$field_name] = $this->get($field_name);
2389
+		}
2390
+		return $properties;
2391
+	}
2392
+
2393
+
2394
+
2395
+	/**
2396
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2397
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2398
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2399
+	 * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2400
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2401
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2402
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
2403
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
2404
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2405
+	 * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2406
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2407
+	 *        return $previousReturnValue.$returnString;
2408
+	 * }
2409
+	 * require('EE_Answer.class.php');
2410
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2411
+	 * echo $answer->my_callback('monkeys',100);
2412
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2413
+	 *
2414
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2415
+	 * @param array  $args       array of original arguments passed to the function
2416
+	 * @throws EE_Error
2417
+	 * @return mixed whatever the plugin which calls add_filter decides
2418
+	 */
2419
+	public function __call($methodName, $args)
2420
+	{
2421
+		$className = get_class($this);
2422
+		$tagName = "FHEE__{$className}__{$methodName}";
2423
+		if ( ! has_filter($tagName)) {
2424
+			throw new EE_Error(
2425
+				sprintf(
2426
+					__(
2427
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2428
+						"event_espresso"
2429
+					),
2430
+					$methodName,
2431
+					$className,
2432
+					$tagName
2433
+				)
2434
+			);
2435
+		}
2436
+		return apply_filters($tagName, null, $this, $args);
2437
+	}
2438
+
2439
+
2440
+
2441
+	/**
2442
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2443
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2444
+	 *
2445
+	 * @param string $meta_key
2446
+	 * @param mixed  $meta_value
2447
+	 * @param mixed  $previous_value
2448
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2449
+	 * @throws \EE_Error
2450
+	 * NOTE: if the values haven't changed, returns 0
2451
+	 */
2452
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2453
+	{
2454
+		$query_params = array(
2455
+			array(
2456
+				'EXM_key'  => $meta_key,
2457
+				'OBJ_ID'   => $this->ID(),
2458
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2459
+			),
2460
+		);
2461
+		if ($previous_value !== null) {
2462
+			$query_params[0]['EXM_value'] = $meta_value;
2463
+		}
2464
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2465
+		if ( ! $existing_rows_like_that) {
2466
+			return $this->add_extra_meta($meta_key, $meta_value);
2467
+		}
2468
+		foreach ($existing_rows_like_that as $existing_row) {
2469
+			$existing_row->save(array('EXM_value' => $meta_value));
2470
+		}
2471
+		return count($existing_rows_like_that);
2472
+	}
2473
+
2474
+
2475
+
2476
+	/**
2477
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2478
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2479
+	 * extra meta row was entered, false if not
2480
+	 *
2481
+	 * @param string  $meta_key
2482
+	 * @param mixed   $meta_value
2483
+	 * @param boolean $unique
2484
+	 * @return boolean
2485
+	 * @throws \EE_Error
2486
+	 */
2487
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2488
+	{
2489
+		if ($unique) {
2490
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2491
+				array(
2492
+					array(
2493
+						'EXM_key'  => $meta_key,
2494
+						'OBJ_ID'   => $this->ID(),
2495
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2496
+					),
2497
+				)
2498
+			);
2499
+			if ($existing_extra_meta) {
2500
+				return false;
2501
+			}
2502
+		}
2503
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2504
+			array(
2505
+				'EXM_key'   => $meta_key,
2506
+				'EXM_value' => $meta_value,
2507
+				'OBJ_ID'    => $this->ID(),
2508
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2509
+			)
2510
+		);
2511
+		$new_extra_meta->save();
2512
+		return true;
2513
+	}
2514
+
2515
+
2516
+
2517
+	/**
2518
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2519
+	 * is specified, only deletes extra meta records with that value.
2520
+	 *
2521
+	 * @param string $meta_key
2522
+	 * @param mixed  $meta_value
2523
+	 * @return int number of extra meta rows deleted
2524
+	 * @throws \EE_Error
2525
+	 */
2526
+	public function delete_extra_meta($meta_key, $meta_value = null)
2527
+	{
2528
+		$query_params = array(
2529
+			array(
2530
+				'EXM_key'  => $meta_key,
2531
+				'OBJ_ID'   => $this->ID(),
2532
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2533
+			),
2534
+		);
2535
+		if ($meta_value !== null) {
2536
+			$query_params[0]['EXM_value'] = $meta_value;
2537
+		}
2538
+		return EEM_Extra_Meta::instance()->delete($query_params);
2539
+	}
2540
+
2541
+
2542
+
2543
+	/**
2544
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2545
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2546
+	 * You can specify $default is case you haven't found the extra meta
2547
+	 *
2548
+	 * @param string  $meta_key
2549
+	 * @param boolean $single
2550
+	 * @param mixed   $default if we don't find anything, what should we return?
2551
+	 * @return mixed single value if $single; array if ! $single
2552
+	 * @throws \EE_Error
2553
+	 */
2554
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2555
+	{
2556
+		if ($single) {
2557
+			$result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2558
+			if ($result instanceof EE_Extra_Meta) {
2559
+				return $result->value();
2560
+			} else {
2561
+				return $default;
2562
+			}
2563
+		} else {
2564
+			$results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2565
+			if ($results) {
2566
+				$values = array();
2567
+				foreach ($results as $result) {
2568
+					if ($result instanceof EE_Extra_Meta) {
2569
+						$values[$result->ID()] = $result->value();
2570
+					}
2571
+				}
2572
+				return $values;
2573
+			} else {
2574
+				return $default;
2575
+			}
2576
+		}
2577
+	}
2578
+
2579
+
2580
+
2581
+	/**
2582
+	 * Returns a simple array of all the extra meta associated with this model object.
2583
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2584
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2585
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2586
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2587
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2588
+	 * finally the extra meta's value as each sub-value. (eg
2589
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2590
+	 *
2591
+	 * @param boolean $one_of_each_key
2592
+	 * @return array
2593
+	 * @throws \EE_Error
2594
+	 */
2595
+	public function all_extra_meta_array($one_of_each_key = true)
2596
+	{
2597
+		$return_array = array();
2598
+		if ($one_of_each_key) {
2599
+			$extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2600
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2601
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2602
+					$return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2603
+				}
2604
+			}
2605
+		} else {
2606
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2607
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2608
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2609
+					if ( ! isset($return_array[$extra_meta_obj->key()])) {
2610
+						$return_array[$extra_meta_obj->key()] = array();
2611
+					}
2612
+					$return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2613
+				}
2614
+			}
2615
+		}
2616
+		return $return_array;
2617
+	}
2618
+
2619
+
2620
+
2621
+	/**
2622
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2623
+	 *
2624
+	 * @return string
2625
+	 * @throws \EE_Error
2626
+	 */
2627
+	public function name()
2628
+	{
2629
+		//find a field that's not a text field
2630
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2631
+		if ($field_we_can_use) {
2632
+			return $this->get($field_we_can_use->get_name());
2633
+		} else {
2634
+			$first_few_properties = $this->model_field_array();
2635
+			$first_few_properties = array_slice($first_few_properties, 0, 3);
2636
+			$name_parts = array();
2637
+			foreach ($first_few_properties as $name => $value) {
2638
+				$name_parts[] = "$name:$value";
2639
+			}
2640
+			return implode(",", $name_parts);
2641
+		}
2642
+	}
2643
+
2644
+
2645
+
2646
+	/**
2647
+	 * in_entity_map
2648
+	 * Checks if this model object has been proven to already be in the entity map
2649
+	 *
2650
+	 * @return boolean
2651
+	 * @throws \EE_Error
2652
+	 */
2653
+	public function in_entity_map()
2654
+	{
2655
+		if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2656
+			//well, if we looked, did we find it in the entity map?
2657
+			return true;
2658
+		} else {
2659
+			return false;
2660
+		}
2661
+	}
2662
+
2663
+
2664
+
2665
+	/**
2666
+	 * refresh_from_db
2667
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
2668
+	 *
2669
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2670
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2671
+	 */
2672
+	public function refresh_from_db()
2673
+	{
2674
+		if ($this->ID() && $this->in_entity_map()) {
2675
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
2676
+		} else {
2677
+			//if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2678
+			//if it has an ID but it's not in the map, and you're asking me to refresh it
2679
+			//that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2680
+			//absolutely nothing in it for this ID
2681
+			if (WP_DEBUG) {
2682
+				throw new EE_Error(
2683
+					sprintf(
2684
+						__('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2685
+							'event_espresso'),
2686
+						$this->ID(),
2687
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2688
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2689
+					)
2690
+				);
2691
+			}
2692
+		}
2693
+	}
2694
+
2695
+
2696
+
2697
+	/**
2698
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2699
+	 * (probably a bad assumption they have made, oh well)
2700
+	 *
2701
+	 * @return string
2702
+	 */
2703
+	public function __toString()
2704
+	{
2705
+		try {
2706
+			return sprintf('%s (%s)', $this->name(), $this->ID());
2707
+		} catch (Exception $e) {
2708
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2709
+			return '';
2710
+		}
2711
+	}
2712
+
2713
+
2714
+
2715
+	/**
2716
+	 * Clear related model objects if they're already in the DB, because otherwise when we
2717
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
2718
+	 * This means if we have made changes to those related model objects, and want to unserialize
2719
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
2720
+	 * Instead, those related model objects should be directly serialized and stored.
2721
+	 * Eg, the following won't work:
2722
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2723
+	 * $att = $reg->attendee();
2724
+	 * $att->set( 'ATT_fname', 'Dirk' );
2725
+	 * update_option( 'my_option', serialize( $reg ) );
2726
+	 * //END REQUEST
2727
+	 * //START NEXT REQUEST
2728
+	 * $reg = get_option( 'my_option' );
2729
+	 * $reg->attendee()->save();
2730
+	 * And would need to be replace with:
2731
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2732
+	 * $att = $reg->attendee();
2733
+	 * $att->set( 'ATT_fname', 'Dirk' );
2734
+	 * update_option( 'my_option', serialize( $reg ) );
2735
+	 * //END REQUEST
2736
+	 * //START NEXT REQUEST
2737
+	 * $att = get_option( 'my_option' );
2738
+	 * $att->save();
2739
+	 *
2740
+	 * @return array
2741
+	 * @throws \EE_Error
2742
+	 */
2743
+	public function __sleep()
2744
+	{
2745
+		$model = $this->get_model();
2746
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
2747
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
2748
+				$classname = 'EE_' . $model->get_this_model_name();
2749
+				if (
2750
+					$this->get_one_from_cache($relation_name) instanceof $classname
2751
+					&& $this->get_one_from_cache($relation_name)->ID()
2752
+				) {
2753
+					$this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2754
+				}
2755
+			}
2756
+		}
2757
+		$this->_props_n_values_provided_in_constructor = array();
2758
+		$properties_to_serialize = get_object_vars($this);
2759
+		//don't serialize the model. It's big and that risks recursion
2760
+		unset($properties_to_serialize['_model']);
2761
+		return array_keys($properties_to_serialize);
2762
+	}
2763
+
2764
+
2765
+
2766
+	/**
2767
+	 * restore _props_n_values_provided_in_constructor
2768
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2769
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
2770
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
2771
+	 */
2772
+	public function __wakeup()
2773
+	{
2774
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
2775
+	}
2776 2776
 
2777 2777
 
2778 2778
 
Please login to merge, or discard this patch.