Completed
Branch BUG/3575-event-deletion-previe... (bbeda1)
by
unknown
06:40 queued 04:49
created
core/EE_Registry.core.php 2 patches
Spacing   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
         foreach ($i18n_js_strings as $key => $value) {
310 310
             if (is_scalar($value)) {
311 311
                 $decoded_value           = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
312
-                $i18n_js_strings[ $key ] = wp_strip_all_tags($decoded_value);
312
+                $i18n_js_strings[$key] = wp_strip_all_tags($decoded_value);
313 313
             }
314 314
         }
315 315
         return $i18n_js_strings;
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
     public static function localize_i18n_js_strings()
325 325
     {
326 326
         $i18n_js_strings = EE_Registry::sanitize_i18n_js_strings();
327
-        return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
327
+        return '/* <![CDATA[ */ var eei18n = '.wp_json_encode($i18n_js_strings).'; /* ]]> */';
328 328
     }
329 329
 
330 330
 
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
             $module_class = get_class($module);
344 344
             $this->modules->add($module_class, $module);
345 345
         } else {
346
-            if (! class_exists('EE_Module_Request_Router', false)) {
346
+            if ( ! class_exists('EE_Module_Request_Router', false)) {
347 347
                 $this->load_core('Module_Request_Router');
348 348
             }
349 349
             EE_Module_Request_Router::module_factory($module);
@@ -382,10 +382,10 @@  discard block
 block discarded – undo
382 382
                 EE_CORE,
383 383
                 EE_ADMIN,
384 384
                 EE_CPTS,
385
-                EE_CORE . 'data_migration_scripts/',
386
-                EE_CORE . 'capabilities/',
387
-                EE_CORE . 'request_stack/',
388
-                EE_CORE . 'middleware/',
385
+                EE_CORE.'data_migration_scripts/',
386
+                EE_CORE.'capabilities/',
387
+                EE_CORE.'request_stack/',
388
+                EE_CORE.'middleware/',
389 389
             )
390 390
         );
391 391
         // retrieve instantiated class
@@ -420,7 +420,7 @@  discard block
 block discarded – undo
420 420
         $service_paths = apply_filters(
421 421
             'FHEE__EE_Registry__load_service__service_paths',
422 422
             array(
423
-                EE_CORE . 'services/',
423
+                EE_CORE.'services/',
424 424
             )
425 425
         );
426 426
         // retrieve instantiated class
@@ -555,10 +555,10 @@  discard block
 block discarded – undo
555 555
     {
556 556
         $paths = array(
557 557
             EE_LIBRARIES,
558
-            EE_LIBRARIES . 'messages/',
559
-            EE_LIBRARIES . 'shortcodes/',
560
-            EE_LIBRARIES . 'qtips/',
561
-            EE_LIBRARIES . 'payment_methods/',
558
+            EE_LIBRARIES.'messages/',
559
+            EE_LIBRARIES.'shortcodes/',
560
+            EE_LIBRARIES.'qtips/',
561
+            EE_LIBRARIES.'payment_methods/',
562 562
         );
563 563
         // retrieve instantiated class
564 564
         return $this->_load(
@@ -626,10 +626,10 @@  discard block
 block discarded – undo
626 626
     public function load_model_class($class_name, $arguments = array(), $load_only = true)
627 627
     {
628 628
         $paths = array(
629
-            EE_MODELS . 'fields/',
630
-            EE_MODELS . 'helpers/',
631
-            EE_MODELS . 'relations/',
632
-            EE_MODELS . 'strategies/',
629
+            EE_MODELS.'fields/',
630
+            EE_MODELS.'helpers/',
631
+            EE_MODELS.'relations/',
632
+            EE_MODELS.'strategies/',
633 633
         );
634 634
         // retrieve instantiated class
635 635
         return $this->_load(
@@ -653,7 +653,7 @@  discard block
 block discarded – undo
653 653
      */
654 654
     public function is_model_name($model_name)
655 655
     {
656
-        return isset($this->models[ $model_name ]);
656
+        return isset($this->models[$model_name]);
657 657
     }
658 658
 
659 659
 
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
                 return $cached_class;
775 775
             }
776 776
         }// obtain the loader method from the dependency map
777
-        $loader = $this->_dependency_map->class_loader($class_name);// instantiate the requested object
777
+        $loader = $this->_dependency_map->class_loader($class_name); // instantiate the requested object
778 778
         if ($loader instanceof Closure) {
779 779
             $class_obj = $loader($arguments);
780 780
         } else {
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
             case 1:
817 817
                 // if it's a FQCN then maybe the class is registered with a preceding \
818 818
                 $class_name = strpos($class_name, '\\') !== false
819
-                    ? '\\' . ltrim($class_name, '\\')
819
+                    ? '\\'.ltrim($class_name, '\\')
820 820
                     : $class_name;
821 821
                 break;
822 822
             case 2:
@@ -870,11 +870,11 @@  discard block
 block discarded – undo
870 870
         // strip php file extension
871 871
         $class_name = str_replace('.php', '', trim($class_name));
872 872
         // does the class have a prefix ?
873
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
873
+        if ( ! empty($class_prefix) && $class_prefix !== 'addon') {
874 874
             // make sure $class_prefix is uppercase
875 875
             $class_prefix = strtoupper(trim($class_prefix));
876 876
             // add class prefix ONCE!!!
877
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
877
+            $class_name = $class_prefix.str_replace($class_prefix, '', $class_name);
878 878
         }
879 879
         $class_name = $this->class_cache->getFqnForAlias($class_name);
880 880
         $class_exists = class_exists($class_name, false);
@@ -894,7 +894,7 @@  discard block
 block discarded – undo
894 894
             }
895 895
         }
896 896
         // if the class doesn't already exist.. then we need to try and find the file and load it
897
-        if (! $class_exists) {
897
+        if ( ! $class_exists) {
898 898
             // get full path to file
899 899
             $path = $this->_resolve_path($class_name, $type, $file_paths);
900 900
             // load the file
@@ -905,7 +905,7 @@  discard block
 block discarded – undo
905 905
                 return $loaded;
906 906
             }
907 907
             // if an object was expected but loading failed, then return nothing
908
-            if (! $loaded) {
908
+            if ( ! $loaded) {
909 909
                 return null;
910 910
             }
911 911
         }
@@ -933,8 +933,8 @@  discard block
 block discarded – undo
933 933
      */
934 934
     protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
935 935
     {
936
-        return isset($this->_class_abbreviations[ $class_name ])
937
-            ? $this->_class_abbreviations[ $class_name ]
936
+        return isset($this->_class_abbreviations[$class_name])
937
+            ? $this->_class_abbreviations[$class_name]
938 938
             : $default;
939 939
     }
940 940
 
@@ -1068,7 +1068,7 @@  discard block
 block discarded – undo
1068 1068
             $this->addons->add($class_name, $class_obj);
1069 1069
             return;
1070 1070
         }
1071
-        if (! $from_db) {
1071
+        if ( ! $from_db) {
1072 1072
             $class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
1073 1073
             $this->LIB->add($class_name, $class_obj);
1074 1074
         }
@@ -1099,13 +1099,13 @@  discard block
 block discarded – undo
1099 1099
                 : EE_CLASSES;
1100 1100
             // prep file type
1101 1101
             $type = ! empty($type)
1102
-                ? trim($type, '.') . '.'
1102
+                ? trim($type, '.').'.'
1103 1103
                 : '';
1104 1104
             // build full file path
1105
-            $file_paths[ $key ] = rtrim($file_path, '/') . '/' . $class_name . '.' . $type . 'php';
1105
+            $file_paths[$key] = rtrim($file_path, '/').'/'.$class_name.'.'.$type.'php';
1106 1106
             // does the file exist and can be read ?
1107
-            if (is_readable($file_paths[ $key ])) {
1108
-                return $file_paths[ $key ];
1107
+            if (is_readable($file_paths[$key])) {
1108
+                return $file_paths[$key];
1109 1109
             }
1110 1110
         }
1111 1111
         return false;
@@ -1130,7 +1130,7 @@  discard block
 block discarded – undo
1130 1130
         // don't give up! you gotta...
1131 1131
         try {
1132 1132
             // does the file exist and can it be read ?
1133
-            if (! $path) {
1133
+            if ( ! $path) {
1134 1134
                 // just in case the file has already been autoloaded,
1135 1135
                 // but discrepancies in the naming schema are preventing it from
1136 1136
                 // being loaded via one of the EE_Registry::load_*() methods,
@@ -1148,7 +1148,7 @@  discard block
 block discarded – undo
1148 1148
                         ),
1149 1149
                         trim($type, '.'),
1150 1150
                         $class_name,
1151
-                        '<br />' . implode(',<br />', $file_paths)
1151
+                        '<br />'.implode(',<br />', $file_paths)
1152 1152
                     )
1153 1153
                 );
1154 1154
             }
@@ -1191,8 +1191,8 @@  discard block
 block discarded – undo
1191 1191
             $legacy_parent_class_map = array(
1192 1192
                 'EE_Payment_Processor' => 'core/business/EE_Processor_Base.class.php',
1193 1193
             );
1194
-            if (isset($legacy_parent_class_map[ $class_name ])) {
1195
-                require_once EE_PLUGIN_DIR_PATH . $legacy_parent_class_map[ $class_name ];
1194
+            if (isset($legacy_parent_class_map[$class_name])) {
1195
+                require_once EE_PLUGIN_DIR_PATH.$legacy_parent_class_map[$class_name];
1196 1196
             }
1197 1197
         } catch (Exception $exception) {
1198 1198
         }
@@ -1325,7 +1325,7 @@  discard block
 block discarded – undo
1325 1325
         // let's examine the constructor
1326 1326
         $constructor = $this->mirror->getConstructorFromReflection($reflector);
1327 1327
         // whu? huh? nothing?
1328
-        if (! $constructor) {
1328
+        if ( ! $constructor) {
1329 1329
             return $arguments;
1330 1330
         }
1331 1331
         // get constructor parameters
@@ -1355,7 +1355,7 @@  discard block
 block discarded – undo
1355 1355
                 $param_class === null
1356 1356
                 // and something already exists in the incoming arguments for this param
1357 1357
                 && array_key_exists($index, $argument_keys)
1358
-                && array_key_exists($argument_keys[ $index ], $arguments)
1358
+                && array_key_exists($argument_keys[$index], $arguments)
1359 1359
             ) {
1360 1360
                 // so let's skip this argument and move on to the next
1361 1361
                 continue;
@@ -1363,8 +1363,8 @@  discard block
 block discarded – undo
1363 1363
             if (
1364 1364
 // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1365 1365
                 $param_class !== null
1366
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
1367
-                && $arguments[ $argument_keys[ $index ] ] instanceof $param_class
1366
+                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1367
+                && $arguments[$argument_keys[$index]] instanceof $param_class
1368 1368
             ) {
1369 1369
                 // skip this argument and move on to the next
1370 1370
                 continue;
@@ -1381,8 +1381,8 @@  discard block
 block discarded – undo
1381 1381
                     $index
1382 1382
                 );
1383 1383
             }
1384
-            if (empty($arguments[ $index ])) {
1385
-                $arguments[ $index ] = $this->mirror->getParameterDefaultValue(
1384
+            if (empty($arguments[$index])) {
1385
+                $arguments[$index] = $this->mirror->getParameterDefaultValue(
1386 1386
                     $param,
1387 1387
                     $class_name,
1388 1388
                     $index
@@ -1444,7 +1444,7 @@  discard block
 block discarded – undo
1444 1444
         // did we successfully find the correct dependency ?
1445 1445
         if ($dependency instanceof $param_class) {
1446 1446
             // then let's inject it into the incoming array of arguments at the correct location
1447
-            $arguments[ $index ] = $dependency;
1447
+            $arguments[$index] = $dependency;
1448 1448
         }
1449 1449
         return $arguments;
1450 1450
     }
@@ -1539,7 +1539,7 @@  discard block
 block discarded – undo
1539 1539
     {
1540 1540
         $addons = array();
1541 1541
         foreach ($this->addons as $addon) {
1542
-            $addons[ $addon->name() ] = $addon;
1542
+            $addons[$addon->name()] = $addon;
1543 1543
         }
1544 1544
         return $addons;
1545 1545
     }
@@ -1558,11 +1558,11 @@  discard block
 block discarded – undo
1558 1558
         $model_class_name = strpos($model_name, 'EEM_') !== 0
1559 1559
             ? "EEM_{$model_name}"
1560 1560
             : $model_name;
1561
-        if (! $this->LIB->has($model_class_name)) {
1561
+        if ( ! $this->LIB->has($model_class_name)) {
1562 1562
             return null;
1563 1563
         }
1564 1564
         $model = $this->LIB->get($model_class_name);
1565
-        if (! $model instanceof EEM_Base) {
1565
+        if ( ! $model instanceof EEM_Base) {
1566 1566
             return null;
1567 1567
         }
1568 1568
         // get that model reset it and make sure we nuke the old reference to it
@@ -1652,7 +1652,7 @@  discard block
 block discarded – undo
1652 1652
      */
1653 1653
     private static function _reset_and_unset_object($object, $reset_models)
1654 1654
     {
1655
-        if (! is_object($object)) {
1655
+        if ( ! is_object($object)) {
1656 1656
             // don't unset anything that's not an object
1657 1657
             return false;
1658 1658
         }
@@ -1672,7 +1672,7 @@  discard block
 block discarded – undo
1672 1672
             $object->reset();
1673 1673
             return true;
1674 1674
         }
1675
-        if (! $object instanceof InterminableInterface) {
1675
+        if ( ! $object instanceof InterminableInterface) {
1676 1676
             return true;
1677 1677
         }
1678 1678
         return false;
@@ -1689,7 +1689,7 @@  discard block
 block discarded – undo
1689 1689
         $cpt_models = array();
1690 1690
         foreach ($this->non_abstract_db_models as $short_name => $classname) {
1691 1691
             if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1692
-                $cpt_models[ $short_name ] = $classname;
1692
+                $cpt_models[$short_name] = $classname;
1693 1693
             }
1694 1694
         }
1695 1695
         return $cpt_models;
Please login to merge, or discard this patch.
Indentation   +1689 added lines, -1689 removed lines patch added patch discarded remove patch
@@ -23,1697 +23,1697 @@
 block discarded – undo
23 23
 class EE_Registry implements ResettableInterface
24 24
 {
25 25
 
26
-    /**
27
-     * @var EE_Registry $_instance
28
-     */
29
-    private static $_instance;
30
-
31
-    /**
32
-     * @var EE_Dependency_Map $_dependency_map
33
-     */
34
-    protected $_dependency_map;
35
-
36
-    /**
37
-     * @var Mirror
38
-     */
39
-    private $mirror;
40
-
41
-    /**
42
-     * @var ClassInterfaceCache $class_cache
43
-     */
44
-    private $class_cache;
45
-
46
-    /**
47
-     * @var array $_class_abbreviations
48
-     */
49
-    protected $_class_abbreviations = array();
50
-
51
-    /**
52
-     * @var CommandBusInterface $BUS
53
-     */
54
-    public $BUS;
55
-
56
-    /**
57
-     * @var EE_Cart $CART
58
-     */
59
-    public $CART;
60
-
61
-    /**
62
-     * @var EE_Config $CFG
63
-     */
64
-    public $CFG;
65
-
66
-    /**
67
-     * @var EE_Network_Config $NET_CFG
68
-     */
69
-    public $NET_CFG;
70
-
71
-    /**
72
-     * RegistryContainer for storing library classes in
73
-     *
74
-     * @var RegistryContainer $LIB
75
-     */
76
-    public $LIB;
77
-
78
-    /**
79
-     * @var EE_Request_Handler $REQ
80
-     * @deprecated 4.10.14.p
81
-     */
82
-    public $REQ;
83
-
84
-    /**
85
-     * @var EE_Session $SSN
86
-     */
87
-    public $SSN;
88
-
89
-    /**
90
-     * @since 4.5.0
91
-     * @var EE_Capabilities $CAP
92
-     */
93
-    public $CAP;
94
-
95
-    /**
96
-     * @since 4.9.0
97
-     * @var EE_Message_Resource_Manager $MRM
98
-     */
99
-    public $MRM;
100
-
101
-    /**
102
-     * @var Registry $AssetsRegistry
103
-     */
104
-    public $AssetsRegistry;
105
-
106
-    /**
107
-     * RegistryContainer for holding addons which have registered themselves to work with EE core
108
-     *
109
-     * @var EE_Addon[] $addons
110
-     */
111
-    public $addons;
112
-
113
-    /**
114
-     * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
115
-     *
116
-     * @var EEM_Base[] $models
117
-     */
118
-    public $models = array();
119
-
120
-    /**
121
-     * @var EED_Module[] $modules
122
-     */
123
-    public $modules;
124
-
125
-    /**
126
-     * @var EES_Shortcode[] $shortcodes
127
-     */
128
-    public $shortcodes;
129
-
130
-    /**
131
-     * @var WP_Widget[] $widgets
132
-     */
133
-    public $widgets;
134
-
135
-    /**
136
-     * this is an array of all implemented model names (i.e. not the parent abstract models, or models
137
-     * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
138
-     * Keys are model "short names" (eg "Event") as used in model relations, and values are
139
-     * classnames (eg "EEM_Event")
140
-     *
141
-     * @var array $non_abstract_db_models
142
-     */
143
-    public $non_abstract_db_models = array();
144
-
145
-    /**
146
-     * internationalization for JS strings
147
-     *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
148
-     *    in js file:  var translatedString = eei18n.string_key;
149
-     *
150
-     * @var array $i18n_js_strings
151
-     */
152
-    public static $i18n_js_strings = array();
153
-
154
-    /**
155
-     * $main_file - path to espresso.php
156
-     *
157
-     * @var array $main_file
158
-     */
159
-    public $main_file;
160
-
161
-    /**
162
-     * array of ReflectionClass objects where the key is the class name
163
-     *
164
-     * @deprecated 4.9.62.p
165
-     * @var ReflectionClass[] $_reflectors
166
-     */
167
-    public $_reflectors;
168
-
169
-    /**
170
-     * boolean flag to indicate whether or not to load/save dependencies from/to the cache
171
-     *
172
-     * @var boolean $_cache_on
173
-     */
174
-    protected $_cache_on = true;
175
-
176
-    /**
177
-     * @var ObjectIdentifier
178
-     */
179
-    private $object_identifier;
180
-
181
-
182
-    /**
183
-     * @singleton method used to instantiate class object
184
-     * @param EE_Dependency_Map|null   $dependency_map
185
-     * @param Mirror|null              $mirror
186
-     * @param ClassInterfaceCache|null $class_cache
187
-     * @param ObjectIdentifier|null    $object_identifier
188
-     * @return EE_Registry instance
189
-     */
190
-    public static function instance(
191
-        EE_Dependency_Map $dependency_map = null,
192
-        Mirror $mirror = null,
193
-        ClassInterfaceCache $class_cache = null,
194
-        ObjectIdentifier $object_identifier = null
195
-    ) {
196
-        // check if class object is instantiated
197
-        if (
198
-            ! self::$_instance instanceof EE_Registry
199
-            && $dependency_map instanceof EE_Dependency_Map
200
-            && $mirror instanceof Mirror
201
-            && $class_cache instanceof ClassInterfaceCache
202
-            && $object_identifier instanceof ObjectIdentifier
203
-        ) {
204
-            self::$_instance = new self(
205
-                $dependency_map,
206
-                $mirror,
207
-                $class_cache,
208
-                $object_identifier
209
-            );
210
-        }
211
-        return self::$_instance;
212
-    }
213
-
214
-
215
-    /**
216
-     * protected constructor to prevent direct creation
217
-     *
218
-     * @Constructor
219
-     * @param  EE_Dependency_Map  $dependency_map
220
-     * @param Mirror              $mirror
221
-     * @param ClassInterfaceCache $class_cache
222
-     * @param ObjectIdentifier    $object_identifier
223
-     */
224
-    protected function __construct(
225
-        EE_Dependency_Map $dependency_map,
226
-        Mirror $mirror,
227
-        ClassInterfaceCache $class_cache,
228
-        ObjectIdentifier $object_identifier
229
-    ) {
230
-        $this->_dependency_map = $dependency_map;
231
-        $this->mirror = $mirror;
232
-        $this->class_cache = $class_cache;
233
-        $this->object_identifier = $object_identifier;
234
-        // $registry_container = new RegistryContainer();
235
-        $this->LIB = new RegistryContainer();
236
-        $this->addons = new RegistryContainer();
237
-        $this->modules = new RegistryContainer();
238
-        $this->shortcodes = new RegistryContainer();
239
-        $this->widgets = new RegistryContainer();
240
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
241
-    }
242
-
243
-
244
-    /**
245
-     * initialize
246
-     *
247
-     * @throws OutOfBoundsException
248
-     * @throws InvalidArgumentException
249
-     * @throws InvalidInterfaceException
250
-     * @throws InvalidDataTypeException
251
-     * @throws EE_Error
252
-     * @throws ReflectionException
253
-     */
254
-    public function initialize()
255
-    {
256
-        $this->_class_abbreviations = apply_filters(
257
-            'FHEE__EE_Registry____construct___class_abbreviations',
258
-            array(
259
-                'EE_Config'                                       => 'CFG',
260
-                'EE_Session'                                      => 'SSN',
261
-                'EE_Capabilities'                                 => 'CAP',
262
-                'EE_Cart'                                         => 'CART',
263
-                'EE_Network_Config'                               => 'NET_CFG',
264
-                'EE_Request_Handler'                              => 'REQ',
265
-                'EE_Message_Resource_Manager'                     => 'MRM',
266
-                'EventEspresso\core\services\commands\CommandBus' => 'BUS',
267
-                'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
268
-            )
269
-        );
270
-        $this->load_core('Base', array(), true);
271
-        // add our request and response objects to the cache
272
-        $request_loader = $this->_dependency_map->class_loader(
273
-            'EventEspresso\core\services\request\Request'
274
-        );
275
-        $this->_set_cached_class(
276
-            $request_loader(),
277
-            'EventEspresso\core\services\request\Request'
278
-        );
279
-        $response_loader = $this->_dependency_map->class_loader(
280
-            'EventEspresso\core\services\request\Response'
281
-        );
282
-        $this->_set_cached_class(
283
-            $response_loader(),
284
-            'EventEspresso\core\services\request\Response'
285
-        );
286
-        add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
287
-    }
288
-
289
-
290
-    /**
291
-     * @return void
292
-     */
293
-    public function init()
294
-    {
295
-        // Get current page protocol
296
-        $protocol = is_ssl() ? 'https://' : 'http://';
297
-        // Output admin-ajax.php URL with same protocol as current page
298
-        self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
299
-        self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') && WP_DEBUG;
300
-    }
301
-
302
-
303
-    /**
304
-     * @return array
305
-     */
306
-    public static function sanitize_i18n_js_strings()
307
-    {
308
-        $i18n_js_strings = (array) self::$i18n_js_strings;
309
-        foreach ($i18n_js_strings as $key => $value) {
310
-            if (is_scalar($value)) {
311
-                $decoded_value           = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
312
-                $i18n_js_strings[ $key ] = wp_strip_all_tags($decoded_value);
313
-            }
314
-        }
315
-        return $i18n_js_strings;
316
-    }
317
-
318
-
319
-    /**
320
-     * localize_i18n_js_strings
321
-     *
322
-     * @return string
323
-     */
324
-    public static function localize_i18n_js_strings()
325
-    {
326
-        $i18n_js_strings = EE_Registry::sanitize_i18n_js_strings();
327
-        return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
328
-    }
329
-
330
-
331
-    /**
332
-     * @param mixed string | EED_Module $module
333
-     * @throws OutOfBoundsException
334
-     * @throws InvalidArgumentException
335
-     * @throws InvalidInterfaceException
336
-     * @throws InvalidDataTypeException
337
-     * @throws EE_Error
338
-     * @throws ReflectionException
339
-     */
340
-    public function add_module($module)
341
-    {
342
-        if ($module instanceof EED_Module) {
343
-            $module_class = get_class($module);
344
-            $this->modules->add($module_class, $module);
345
-        } else {
346
-            if (! class_exists('EE_Module_Request_Router', false)) {
347
-                $this->load_core('Module_Request_Router');
348
-            }
349
-            EE_Module_Request_Router::module_factory($module);
350
-        }
351
-    }
352
-
353
-
354
-    /**
355
-     * @param string $module_name
356
-     * @return mixed EED_Module | NULL
357
-     */
358
-    public function get_module($module_name = '')
359
-    {
360
-        return $this->modules->get($module_name);
361
-    }
362
-
363
-
364
-    /**
365
-     * loads core classes - must be singletons
366
-     *
367
-     * @param string $class_name - simple class name ie: session
368
-     * @param mixed  $arguments
369
-     * @param bool   $load_only
370
-     * @return mixed
371
-     * @throws InvalidInterfaceException
372
-     * @throws InvalidDataTypeException
373
-     * @throws EE_Error
374
-     * @throws ReflectionException
375
-     * @throws InvalidArgumentException
376
-     */
377
-    public function load_core($class_name, $arguments = array(), $load_only = false)
378
-    {
379
-        $core_paths = apply_filters(
380
-            'FHEE__EE_Registry__load_core__core_paths',
381
-            array(
382
-                EE_CORE,
383
-                EE_ADMIN,
384
-                EE_CPTS,
385
-                EE_CORE . 'data_migration_scripts/',
386
-                EE_CORE . 'capabilities/',
387
-                EE_CORE . 'request_stack/',
388
-                EE_CORE . 'middleware/',
389
-            )
390
-        );
391
-        // retrieve instantiated class
392
-        return $this->_load(
393
-            $core_paths,
394
-            'EE_',
395
-            $class_name,
396
-            'core',
397
-            $arguments,
398
-            false,
399
-            true,
400
-            $load_only
401
-        );
402
-    }
403
-
404
-
405
-    /**
406
-     * loads service classes
407
-     *
408
-     * @param string $class_name - simple class name ie: session
409
-     * @param mixed  $arguments
410
-     * @param bool   $load_only
411
-     * @return mixed
412
-     * @throws InvalidInterfaceException
413
-     * @throws InvalidDataTypeException
414
-     * @throws EE_Error
415
-     * @throws ReflectionException
416
-     * @throws InvalidArgumentException
417
-     */
418
-    public function load_service($class_name, $arguments = array(), $load_only = false)
419
-    {
420
-        $service_paths = apply_filters(
421
-            'FHEE__EE_Registry__load_service__service_paths',
422
-            array(
423
-                EE_CORE . 'services/',
424
-            )
425
-        );
426
-        // retrieve instantiated class
427
-        return $this->_load(
428
-            $service_paths,
429
-            'EE_',
430
-            $class_name,
431
-            'class',
432
-            $arguments,
433
-            false,
434
-            true,
435
-            $load_only
436
-        );
437
-    }
438
-
439
-
440
-    /**
441
-     * loads data_migration_scripts
442
-     *
443
-     * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
444
-     * @param mixed  $arguments
445
-     * @return EE_Data_Migration_Script_Base|mixed
446
-     * @throws InvalidInterfaceException
447
-     * @throws InvalidDataTypeException
448
-     * @throws EE_Error
449
-     * @throws ReflectionException
450
-     * @throws InvalidArgumentException
451
-     */
452
-    public function load_dms($class_name, $arguments = array())
453
-    {
454
-        // retrieve instantiated class
455
-        return $this->_load(
456
-            EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
457
-            'EE_DMS_',
458
-            $class_name,
459
-            'dms',
460
-            $arguments,
461
-            false,
462
-            false
463
-        );
464
-    }
465
-
466
-
467
-    /**
468
-     * loads object creating classes - must be singletons
469
-     *
470
-     * @param string $class_name - simple class name ie: attendee
471
-     * @param mixed  $arguments  - an array of arguments to pass to the class
472
-     * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to
473
-     *                           instantiate
474
-     * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
475
-     *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
476
-     * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
477
-     *                           (default)
478
-     * @return EE_Base_Class | bool
479
-     * @throws InvalidInterfaceException
480
-     * @throws InvalidDataTypeException
481
-     * @throws EE_Error
482
-     * @throws ReflectionException
483
-     * @throws InvalidArgumentException
484
-     */
485
-    public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
486
-    {
487
-        $paths = apply_filters(
488
-            'FHEE__EE_Registry__load_class__paths',
489
-            array(
490
-                EE_CORE,
491
-                EE_CLASSES,
492
-                EE_BUSINESS,
493
-            )
494
-        );
495
-        // retrieve instantiated class
496
-        return $this->_load(
497
-            $paths,
498
-            'EE_',
499
-            $class_name,
500
-            'class',
501
-            $arguments,
502
-            $from_db,
503
-            $cache,
504
-            $load_only
505
-        );
506
-    }
507
-
508
-
509
-    /**
510
-     * loads helper classes - must be singletons
511
-     *
512
-     * @param string $class_name - simple class name ie: price
513
-     * @param mixed  $arguments
514
-     * @param bool   $load_only
515
-     * @return EEH_Base | bool
516
-     * @throws InvalidInterfaceException
517
-     * @throws InvalidDataTypeException
518
-     * @throws EE_Error
519
-     * @throws ReflectionException
520
-     * @throws InvalidArgumentException
521
-     */
522
-    public function load_helper($class_name, $arguments = array(), $load_only = true)
523
-    {
524
-        // todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
525
-        $helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
526
-        // retrieve instantiated class
527
-        return $this->_load(
528
-            $helper_paths,
529
-            'EEH_',
530
-            $class_name,
531
-            'helper',
532
-            $arguments,
533
-            false,
534
-            true,
535
-            $load_only
536
-        );
537
-    }
538
-
539
-
540
-    /**
541
-     * loads core classes - must be singletons
542
-     *
543
-     * @param string $class_name - simple class name ie: session
544
-     * @param mixed  $arguments
545
-     * @param bool   $load_only
546
-     * @param bool   $cache      whether to cache the object or not.
547
-     * @return mixed
548
-     * @throws InvalidInterfaceException
549
-     * @throws InvalidDataTypeException
550
-     * @throws EE_Error
551
-     * @throws ReflectionException
552
-     * @throws InvalidArgumentException
553
-     */
554
-    public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
555
-    {
556
-        $paths = array(
557
-            EE_LIBRARIES,
558
-            EE_LIBRARIES . 'messages/',
559
-            EE_LIBRARIES . 'shortcodes/',
560
-            EE_LIBRARIES . 'qtips/',
561
-            EE_LIBRARIES . 'payment_methods/',
562
-        );
563
-        // retrieve instantiated class
564
-        return $this->_load(
565
-            $paths,
566
-            'EE_',
567
-            $class_name,
568
-            'lib',
569
-            $arguments,
570
-            false,
571
-            $cache,
572
-            $load_only
573
-        );
574
-    }
575
-
576
-
577
-    /**
578
-     * loads model classes - must be singletons
579
-     *
580
-     * @param string $class_name - simple class name ie: price
581
-     * @param mixed  $arguments
582
-     * @param bool   $load_only
583
-     * @return EEM_Base | bool
584
-     * @throws InvalidInterfaceException
585
-     * @throws InvalidDataTypeException
586
-     * @throws EE_Error
587
-     * @throws ReflectionException
588
-     * @throws InvalidArgumentException
589
-     */
590
-    public function load_model($class_name, $arguments = array(), $load_only = false)
591
-    {
592
-        $paths = apply_filters(
593
-            'FHEE__EE_Registry__load_model__paths',
594
-            array(
595
-                EE_MODELS,
596
-                EE_CORE,
597
-            )
598
-        );
599
-        // retrieve instantiated class
600
-        return $this->_load(
601
-            $paths,
602
-            'EEM_',
603
-            $class_name,
604
-            'model',
605
-            $arguments,
606
-            false,
607
-            true,
608
-            $load_only
609
-        );
610
-    }
611
-
612
-
613
-    /**
614
-     * loads model classes - must be singletons
615
-     *
616
-     * @param string $class_name - simple class name ie: price
617
-     * @param mixed  $arguments
618
-     * @param bool   $load_only
619
-     * @return mixed | bool
620
-     * @throws InvalidInterfaceException
621
-     * @throws InvalidDataTypeException
622
-     * @throws EE_Error
623
-     * @throws ReflectionException
624
-     * @throws InvalidArgumentException
625
-     */
626
-    public function load_model_class($class_name, $arguments = array(), $load_only = true)
627
-    {
628
-        $paths = array(
629
-            EE_MODELS . 'fields/',
630
-            EE_MODELS . 'helpers/',
631
-            EE_MODELS . 'relations/',
632
-            EE_MODELS . 'strategies/',
633
-        );
634
-        // retrieve instantiated class
635
-        return $this->_load(
636
-            $paths,
637
-            'EE_',
638
-            $class_name,
639
-            '',
640
-            $arguments,
641
-            false,
642
-            true,
643
-            $load_only
644
-        );
645
-    }
646
-
647
-
648
-    /**
649
-     * Determines if $model_name is the name of an actual EE model.
650
-     *
651
-     * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
652
-     * @return boolean
653
-     */
654
-    public function is_model_name($model_name)
655
-    {
656
-        return isset($this->models[ $model_name ]);
657
-    }
658
-
659
-
660
-    /**
661
-     * generic class loader
662
-     *
663
-     * @param string $path_to_file - directory path to file location, not including filename
664
-     * @param string $file_name    - file name  ie:  my_file.php, including extension
665
-     * @param string $type         - file type - core? class? helper? model?
666
-     * @param mixed  $arguments
667
-     * @param bool   $load_only
668
-     * @return mixed
669
-     * @throws InvalidInterfaceException
670
-     * @throws InvalidDataTypeException
671
-     * @throws EE_Error
672
-     * @throws ReflectionException
673
-     * @throws InvalidArgumentException
674
-     */
675
-    public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
676
-    {
677
-        // retrieve instantiated class
678
-        return $this->_load(
679
-            $path_to_file,
680
-            '',
681
-            $file_name,
682
-            $type,
683
-            $arguments,
684
-            false,
685
-            true,
686
-            $load_only
687
-        );
688
-    }
689
-
690
-
691
-    /**
692
-     * @param string $path_to_file - directory path to file location, not including filename
693
-     * @param string $class_name   - full class name  ie:  My_Class
694
-     * @param string $type         - file type - core? class? helper? model?
695
-     * @param mixed  $arguments
696
-     * @param bool   $load_only
697
-     * @return bool|EE_Addon|object
698
-     * @throws InvalidInterfaceException
699
-     * @throws InvalidDataTypeException
700
-     * @throws EE_Error
701
-     * @throws ReflectionException
702
-     * @throws InvalidArgumentException
703
-     */
704
-    public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
705
-    {
706
-        // retrieve instantiated class
707
-        return $this->_load(
708
-            $path_to_file,
709
-            'addon',
710
-            $class_name,
711
-            $type,
712
-            $arguments,
713
-            false,
714
-            true,
715
-            $load_only
716
-        );
717
-    }
718
-
719
-
720
-    /**
721
-     * instantiates, caches, and automatically resolves dependencies
722
-     * for classes that use a Fully Qualified Class Name.
723
-     * if the class is not capable of being loaded using PSR-4 autoloading,
724
-     * then you need to use one of the existing load_*() methods
725
-     * which can resolve the classname and filepath from the passed arguments
726
-     *
727
-     * @param bool|string $class_name   Fully Qualified Class Name
728
-     * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
729
-     * @param bool        $cache        whether to cache the instantiated object for reuse
730
-     * @param bool        $from_db      some classes are instantiated from the db
731
-     *                                  and thus call a different method to instantiate
732
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
733
-     * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
734
-     * @return bool|null|mixed          null = failure to load or instantiate class object.
735
-     *                                  object = class loaded and instantiated successfully.
736
-     *                                  bool = fail or success when $load_only is true
737
-     * @throws InvalidInterfaceException
738
-     * @throws InvalidDataTypeException
739
-     * @throws EE_Error
740
-     * @throws ReflectionException
741
-     * @throws InvalidArgumentException
742
-     */
743
-    public function create(
744
-        $class_name = false,
745
-        $arguments = array(),
746
-        $cache = false,
747
-        $from_db = false,
748
-        $load_only = false,
749
-        $addon = false
750
-    ) {
751
-        $class_name = ltrim($class_name, '\\');
752
-        $class_name = $this->class_cache->getFqnForAlias($class_name);
753
-        $class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
754
-        // if a non-FQCN was passed, then
755
-        // verifyClassExists() might return an object
756
-        // or it could return null if the class just could not be found anywhere
757
-        if ($class_exists instanceof $class_name || $class_exists === null) {
758
-            // either way, return the results
759
-            return $class_exists;
760
-        }
761
-        $class_name = $class_exists;
762
-        // if we're only loading the class and it already exists, then let's just return true immediately
763
-        if ($load_only) {
764
-            return true;
765
-        }
766
-        $addon = $addon ? 'addon' : '';
767
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
768
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
769
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
770
-        if ($this->_cache_on && $cache && ! $load_only) {
771
-            // return object if it's already cached
772
-            $cached_class = $this->_get_cached_class($class_name, $addon, $arguments);
773
-            if ($cached_class !== null) {
774
-                return $cached_class;
775
-            }
776
-        }// obtain the loader method from the dependency map
777
-        $loader = $this->_dependency_map->class_loader($class_name);// instantiate the requested object
778
-        if ($loader instanceof Closure) {
779
-            $class_obj = $loader($arguments);
780
-        } else {
781
-            if ($loader && method_exists($this, $loader)) {
782
-                $class_obj = $this->{$loader}($class_name, $arguments);
783
-            } else {
784
-                $class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
785
-            }
786
-        }
787
-        if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
788
-            // save it for later... kinda like gum  { : $
789
-            $this->_set_cached_class(
790
-                $class_obj,
791
-                $class_name,
792
-                $addon,
793
-                $from_db,
794
-                $arguments
795
-            );
796
-        }
797
-        $this->_cache_on = true;
798
-        return $class_obj;
799
-    }
800
-
801
-
802
-    /**
803
-     * Recursively checks that a class exists and potentially attempts to load classes with non-FQCNs
804
-     *
805
-     * @param string|object $class_name
806
-     * @param array         $arguments
807
-     * @param int           $attempt
808
-     * @return mixed
809
-     */
810
-    private function loadOrVerifyClassExists($class_name, array $arguments, $attempt = 1)
811
-    {
812
-        if (is_object($class_name) || class_exists($class_name)) {
813
-            return $class_name;
814
-        }
815
-        switch ($attempt) {
816
-            case 1:
817
-                // if it's a FQCN then maybe the class is registered with a preceding \
818
-                $class_name = strpos($class_name, '\\') !== false
819
-                    ? '\\' . ltrim($class_name, '\\')
820
-                    : $class_name;
821
-                break;
822
-            case 2:
823
-                //
824
-                $loader = $this->_dependency_map->class_loader($class_name);
825
-                if ($loader && method_exists($this, $loader)) {
826
-                    return $this->{$loader}($class_name, $arguments);
827
-                }
828
-                break;
829
-            case 3:
830
-            default:
831
-                return null;
832
-        }
833
-        $attempt++;
834
-        return $this->loadOrVerifyClassExists($class_name, $arguments, $attempt);
835
-    }
836
-
837
-
838
-    /**
839
-     * instantiates, caches, and injects dependencies for classes
840
-     *
841
-     * @param array       $file_paths   an array of paths to folders to look in
842
-     * @param string      $class_prefix EE  or EEM or... ???
843
-     * @param bool|string $class_name   $class name
844
-     * @param string      $type         file type - core? class? helper? model?
845
-     * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
846
-     * @param bool        $from_db      some classes are instantiated from the db
847
-     *                                  and thus call a different method to instantiate
848
-     * @param bool        $cache        whether to cache the instantiated object for reuse
849
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
850
-     * @return bool|null|object null = failure to load or instantiate class object.
851
-     *                                  object = class loaded and instantiated successfully.
852
-     *                                  bool = fail or success when $load_only is true
853
-     * @throws EE_Error
854
-     * @throws ReflectionException
855
-     * @throws InvalidInterfaceException
856
-     * @throws InvalidDataTypeException
857
-     * @throws InvalidArgumentException
858
-     */
859
-    protected function _load(
860
-        $file_paths = array(),
861
-        $class_prefix = 'EE_',
862
-        $class_name = false,
863
-        $type = 'class',
864
-        $arguments = array(),
865
-        $from_db = false,
866
-        $cache = true,
867
-        $load_only = false
868
-    ) {
869
-        $class_name = ltrim($class_name, '\\');
870
-        // strip php file extension
871
-        $class_name = str_replace('.php', '', trim($class_name));
872
-        // does the class have a prefix ?
873
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
874
-            // make sure $class_prefix is uppercase
875
-            $class_prefix = strtoupper(trim($class_prefix));
876
-            // add class prefix ONCE!!!
877
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
878
-        }
879
-        $class_name = $this->class_cache->getFqnForAlias($class_name);
880
-        $class_exists = class_exists($class_name, false);
881
-        // if we're only loading the class and it already exists, then let's just return true immediately
882
-        if ($load_only && $class_exists) {
883
-            return true;
884
-        }
885
-        $arguments = is_array($arguments) ? $arguments : array($arguments);
886
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
887
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
888
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
889
-        if ($this->_cache_on && $cache && ! $load_only) {
890
-            // return object if it's already cached
891
-            $cached_class = $this->_get_cached_class($class_name, $class_prefix, $arguments);
892
-            if ($cached_class !== null) {
893
-                return $cached_class;
894
-            }
895
-        }
896
-        // if the class doesn't already exist.. then we need to try and find the file and load it
897
-        if (! $class_exists) {
898
-            // get full path to file
899
-            $path = $this->_resolve_path($class_name, $type, $file_paths);
900
-            // load the file
901
-            $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
902
-            // if we are only loading a file but NOT instantiating an object
903
-            // then return boolean for whether class was loaded or not
904
-            if ($load_only) {
905
-                return $loaded;
906
-            }
907
-            // if an object was expected but loading failed, then return nothing
908
-            if (! $loaded) {
909
-                return null;
910
-            }
911
-        }
912
-        // instantiate the requested object
913
-        $class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
914
-        if ($this->_cache_on && $cache) {
915
-            // save it for later... kinda like gum  { : $
916
-            $this->_set_cached_class(
917
-                $class_obj,
918
-                $class_name,
919
-                $class_prefix,
920
-                $from_db,
921
-                $arguments
922
-            );
923
-        }
924
-        $this->_cache_on = true;
925
-        return $class_obj;
926
-    }
927
-
928
-
929
-    /**
930
-     * @param string $class_name
931
-     * @param string $default have to specify something, but not anything that will conflict
932
-     * @return mixed|string
933
-     */
934
-    protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
935
-    {
936
-        return isset($this->_class_abbreviations[ $class_name ])
937
-            ? $this->_class_abbreviations[ $class_name ]
938
-            : $default;
939
-    }
940
-
941
-
942
-    /**
943
-     * attempts to find a cached version of the requested class
944
-     * by looking in the following places:
945
-     *        $this->{$class_abbreviation}            ie:    $this->CART
946
-     *        $this->{$class_name}                        ie:    $this->Some_Class
947
-     *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
948
-     *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
949
-     *
950
-     * @param string $class_name
951
-     * @param string $class_prefix
952
-     * @param array  $arguments
953
-     * @return mixed
954
-     */
955
-    protected function _get_cached_class(
956
-        $class_name,
957
-        $class_prefix = '',
958
-        $arguments = array()
959
-    ) {
960
-        if ($class_name === 'EE_Registry') {
961
-            return $this;
962
-        }
963
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
964
-        // check if class has already been loaded, and return it if it has been
965
-        if (isset($this->{$class_abbreviation})) {
966
-            return $this->{$class_abbreviation};
967
-        }
968
-        $class_name = str_replace('\\', '_', $class_name);
969
-        if (isset($this->{$class_name})) {
970
-            return $this->{$class_name};
971
-        }
972
-        if ($class_prefix === 'addon' && $this->addons->has($class_name)) {
973
-            return $this->addons->get($class_name);
974
-        }
975
-        $object_identifier = $this->object_identifier->getIdentifier($class_name, $arguments);
976
-        if ($this->LIB->has($object_identifier)) {
977
-            return $this->LIB->get($object_identifier);
978
-        }
979
-        foreach ($this->LIB as $key => $object) {
980
-            if (
26
+	/**
27
+	 * @var EE_Registry $_instance
28
+	 */
29
+	private static $_instance;
30
+
31
+	/**
32
+	 * @var EE_Dependency_Map $_dependency_map
33
+	 */
34
+	protected $_dependency_map;
35
+
36
+	/**
37
+	 * @var Mirror
38
+	 */
39
+	private $mirror;
40
+
41
+	/**
42
+	 * @var ClassInterfaceCache $class_cache
43
+	 */
44
+	private $class_cache;
45
+
46
+	/**
47
+	 * @var array $_class_abbreviations
48
+	 */
49
+	protected $_class_abbreviations = array();
50
+
51
+	/**
52
+	 * @var CommandBusInterface $BUS
53
+	 */
54
+	public $BUS;
55
+
56
+	/**
57
+	 * @var EE_Cart $CART
58
+	 */
59
+	public $CART;
60
+
61
+	/**
62
+	 * @var EE_Config $CFG
63
+	 */
64
+	public $CFG;
65
+
66
+	/**
67
+	 * @var EE_Network_Config $NET_CFG
68
+	 */
69
+	public $NET_CFG;
70
+
71
+	/**
72
+	 * RegistryContainer for storing library classes in
73
+	 *
74
+	 * @var RegistryContainer $LIB
75
+	 */
76
+	public $LIB;
77
+
78
+	/**
79
+	 * @var EE_Request_Handler $REQ
80
+	 * @deprecated 4.10.14.p
81
+	 */
82
+	public $REQ;
83
+
84
+	/**
85
+	 * @var EE_Session $SSN
86
+	 */
87
+	public $SSN;
88
+
89
+	/**
90
+	 * @since 4.5.0
91
+	 * @var EE_Capabilities $CAP
92
+	 */
93
+	public $CAP;
94
+
95
+	/**
96
+	 * @since 4.9.0
97
+	 * @var EE_Message_Resource_Manager $MRM
98
+	 */
99
+	public $MRM;
100
+
101
+	/**
102
+	 * @var Registry $AssetsRegistry
103
+	 */
104
+	public $AssetsRegistry;
105
+
106
+	/**
107
+	 * RegistryContainer for holding addons which have registered themselves to work with EE core
108
+	 *
109
+	 * @var EE_Addon[] $addons
110
+	 */
111
+	public $addons;
112
+
113
+	/**
114
+	 * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
115
+	 *
116
+	 * @var EEM_Base[] $models
117
+	 */
118
+	public $models = array();
119
+
120
+	/**
121
+	 * @var EED_Module[] $modules
122
+	 */
123
+	public $modules;
124
+
125
+	/**
126
+	 * @var EES_Shortcode[] $shortcodes
127
+	 */
128
+	public $shortcodes;
129
+
130
+	/**
131
+	 * @var WP_Widget[] $widgets
132
+	 */
133
+	public $widgets;
134
+
135
+	/**
136
+	 * this is an array of all implemented model names (i.e. not the parent abstract models, or models
137
+	 * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
138
+	 * Keys are model "short names" (eg "Event") as used in model relations, and values are
139
+	 * classnames (eg "EEM_Event")
140
+	 *
141
+	 * @var array $non_abstract_db_models
142
+	 */
143
+	public $non_abstract_db_models = array();
144
+
145
+	/**
146
+	 * internationalization for JS strings
147
+	 *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
148
+	 *    in js file:  var translatedString = eei18n.string_key;
149
+	 *
150
+	 * @var array $i18n_js_strings
151
+	 */
152
+	public static $i18n_js_strings = array();
153
+
154
+	/**
155
+	 * $main_file - path to espresso.php
156
+	 *
157
+	 * @var array $main_file
158
+	 */
159
+	public $main_file;
160
+
161
+	/**
162
+	 * array of ReflectionClass objects where the key is the class name
163
+	 *
164
+	 * @deprecated 4.9.62.p
165
+	 * @var ReflectionClass[] $_reflectors
166
+	 */
167
+	public $_reflectors;
168
+
169
+	/**
170
+	 * boolean flag to indicate whether or not to load/save dependencies from/to the cache
171
+	 *
172
+	 * @var boolean $_cache_on
173
+	 */
174
+	protected $_cache_on = true;
175
+
176
+	/**
177
+	 * @var ObjectIdentifier
178
+	 */
179
+	private $object_identifier;
180
+
181
+
182
+	/**
183
+	 * @singleton method used to instantiate class object
184
+	 * @param EE_Dependency_Map|null   $dependency_map
185
+	 * @param Mirror|null              $mirror
186
+	 * @param ClassInterfaceCache|null $class_cache
187
+	 * @param ObjectIdentifier|null    $object_identifier
188
+	 * @return EE_Registry instance
189
+	 */
190
+	public static function instance(
191
+		EE_Dependency_Map $dependency_map = null,
192
+		Mirror $mirror = null,
193
+		ClassInterfaceCache $class_cache = null,
194
+		ObjectIdentifier $object_identifier = null
195
+	) {
196
+		// check if class object is instantiated
197
+		if (
198
+			! self::$_instance instanceof EE_Registry
199
+			&& $dependency_map instanceof EE_Dependency_Map
200
+			&& $mirror instanceof Mirror
201
+			&& $class_cache instanceof ClassInterfaceCache
202
+			&& $object_identifier instanceof ObjectIdentifier
203
+		) {
204
+			self::$_instance = new self(
205
+				$dependency_map,
206
+				$mirror,
207
+				$class_cache,
208
+				$object_identifier
209
+			);
210
+		}
211
+		return self::$_instance;
212
+	}
213
+
214
+
215
+	/**
216
+	 * protected constructor to prevent direct creation
217
+	 *
218
+	 * @Constructor
219
+	 * @param  EE_Dependency_Map  $dependency_map
220
+	 * @param Mirror              $mirror
221
+	 * @param ClassInterfaceCache $class_cache
222
+	 * @param ObjectIdentifier    $object_identifier
223
+	 */
224
+	protected function __construct(
225
+		EE_Dependency_Map $dependency_map,
226
+		Mirror $mirror,
227
+		ClassInterfaceCache $class_cache,
228
+		ObjectIdentifier $object_identifier
229
+	) {
230
+		$this->_dependency_map = $dependency_map;
231
+		$this->mirror = $mirror;
232
+		$this->class_cache = $class_cache;
233
+		$this->object_identifier = $object_identifier;
234
+		// $registry_container = new RegistryContainer();
235
+		$this->LIB = new RegistryContainer();
236
+		$this->addons = new RegistryContainer();
237
+		$this->modules = new RegistryContainer();
238
+		$this->shortcodes = new RegistryContainer();
239
+		$this->widgets = new RegistryContainer();
240
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
241
+	}
242
+
243
+
244
+	/**
245
+	 * initialize
246
+	 *
247
+	 * @throws OutOfBoundsException
248
+	 * @throws InvalidArgumentException
249
+	 * @throws InvalidInterfaceException
250
+	 * @throws InvalidDataTypeException
251
+	 * @throws EE_Error
252
+	 * @throws ReflectionException
253
+	 */
254
+	public function initialize()
255
+	{
256
+		$this->_class_abbreviations = apply_filters(
257
+			'FHEE__EE_Registry____construct___class_abbreviations',
258
+			array(
259
+				'EE_Config'                                       => 'CFG',
260
+				'EE_Session'                                      => 'SSN',
261
+				'EE_Capabilities'                                 => 'CAP',
262
+				'EE_Cart'                                         => 'CART',
263
+				'EE_Network_Config'                               => 'NET_CFG',
264
+				'EE_Request_Handler'                              => 'REQ',
265
+				'EE_Message_Resource_Manager'                     => 'MRM',
266
+				'EventEspresso\core\services\commands\CommandBus' => 'BUS',
267
+				'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
268
+			)
269
+		);
270
+		$this->load_core('Base', array(), true);
271
+		// add our request and response objects to the cache
272
+		$request_loader = $this->_dependency_map->class_loader(
273
+			'EventEspresso\core\services\request\Request'
274
+		);
275
+		$this->_set_cached_class(
276
+			$request_loader(),
277
+			'EventEspresso\core\services\request\Request'
278
+		);
279
+		$response_loader = $this->_dependency_map->class_loader(
280
+			'EventEspresso\core\services\request\Response'
281
+		);
282
+		$this->_set_cached_class(
283
+			$response_loader(),
284
+			'EventEspresso\core\services\request\Response'
285
+		);
286
+		add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
287
+	}
288
+
289
+
290
+	/**
291
+	 * @return void
292
+	 */
293
+	public function init()
294
+	{
295
+		// Get current page protocol
296
+		$protocol = is_ssl() ? 'https://' : 'http://';
297
+		// Output admin-ajax.php URL with same protocol as current page
298
+		self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
299
+		self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') && WP_DEBUG;
300
+	}
301
+
302
+
303
+	/**
304
+	 * @return array
305
+	 */
306
+	public static function sanitize_i18n_js_strings()
307
+	{
308
+		$i18n_js_strings = (array) self::$i18n_js_strings;
309
+		foreach ($i18n_js_strings as $key => $value) {
310
+			if (is_scalar($value)) {
311
+				$decoded_value           = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
312
+				$i18n_js_strings[ $key ] = wp_strip_all_tags($decoded_value);
313
+			}
314
+		}
315
+		return $i18n_js_strings;
316
+	}
317
+
318
+
319
+	/**
320
+	 * localize_i18n_js_strings
321
+	 *
322
+	 * @return string
323
+	 */
324
+	public static function localize_i18n_js_strings()
325
+	{
326
+		$i18n_js_strings = EE_Registry::sanitize_i18n_js_strings();
327
+		return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
328
+	}
329
+
330
+
331
+	/**
332
+	 * @param mixed string | EED_Module $module
333
+	 * @throws OutOfBoundsException
334
+	 * @throws InvalidArgumentException
335
+	 * @throws InvalidInterfaceException
336
+	 * @throws InvalidDataTypeException
337
+	 * @throws EE_Error
338
+	 * @throws ReflectionException
339
+	 */
340
+	public function add_module($module)
341
+	{
342
+		if ($module instanceof EED_Module) {
343
+			$module_class = get_class($module);
344
+			$this->modules->add($module_class, $module);
345
+		} else {
346
+			if (! class_exists('EE_Module_Request_Router', false)) {
347
+				$this->load_core('Module_Request_Router');
348
+			}
349
+			EE_Module_Request_Router::module_factory($module);
350
+		}
351
+	}
352
+
353
+
354
+	/**
355
+	 * @param string $module_name
356
+	 * @return mixed EED_Module | NULL
357
+	 */
358
+	public function get_module($module_name = '')
359
+	{
360
+		return $this->modules->get($module_name);
361
+	}
362
+
363
+
364
+	/**
365
+	 * loads core classes - must be singletons
366
+	 *
367
+	 * @param string $class_name - simple class name ie: session
368
+	 * @param mixed  $arguments
369
+	 * @param bool   $load_only
370
+	 * @return mixed
371
+	 * @throws InvalidInterfaceException
372
+	 * @throws InvalidDataTypeException
373
+	 * @throws EE_Error
374
+	 * @throws ReflectionException
375
+	 * @throws InvalidArgumentException
376
+	 */
377
+	public function load_core($class_name, $arguments = array(), $load_only = false)
378
+	{
379
+		$core_paths = apply_filters(
380
+			'FHEE__EE_Registry__load_core__core_paths',
381
+			array(
382
+				EE_CORE,
383
+				EE_ADMIN,
384
+				EE_CPTS,
385
+				EE_CORE . 'data_migration_scripts/',
386
+				EE_CORE . 'capabilities/',
387
+				EE_CORE . 'request_stack/',
388
+				EE_CORE . 'middleware/',
389
+			)
390
+		);
391
+		// retrieve instantiated class
392
+		return $this->_load(
393
+			$core_paths,
394
+			'EE_',
395
+			$class_name,
396
+			'core',
397
+			$arguments,
398
+			false,
399
+			true,
400
+			$load_only
401
+		);
402
+	}
403
+
404
+
405
+	/**
406
+	 * loads service classes
407
+	 *
408
+	 * @param string $class_name - simple class name ie: session
409
+	 * @param mixed  $arguments
410
+	 * @param bool   $load_only
411
+	 * @return mixed
412
+	 * @throws InvalidInterfaceException
413
+	 * @throws InvalidDataTypeException
414
+	 * @throws EE_Error
415
+	 * @throws ReflectionException
416
+	 * @throws InvalidArgumentException
417
+	 */
418
+	public function load_service($class_name, $arguments = array(), $load_only = false)
419
+	{
420
+		$service_paths = apply_filters(
421
+			'FHEE__EE_Registry__load_service__service_paths',
422
+			array(
423
+				EE_CORE . 'services/',
424
+			)
425
+		);
426
+		// retrieve instantiated class
427
+		return $this->_load(
428
+			$service_paths,
429
+			'EE_',
430
+			$class_name,
431
+			'class',
432
+			$arguments,
433
+			false,
434
+			true,
435
+			$load_only
436
+		);
437
+	}
438
+
439
+
440
+	/**
441
+	 * loads data_migration_scripts
442
+	 *
443
+	 * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
444
+	 * @param mixed  $arguments
445
+	 * @return EE_Data_Migration_Script_Base|mixed
446
+	 * @throws InvalidInterfaceException
447
+	 * @throws InvalidDataTypeException
448
+	 * @throws EE_Error
449
+	 * @throws ReflectionException
450
+	 * @throws InvalidArgumentException
451
+	 */
452
+	public function load_dms($class_name, $arguments = array())
453
+	{
454
+		// retrieve instantiated class
455
+		return $this->_load(
456
+			EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
457
+			'EE_DMS_',
458
+			$class_name,
459
+			'dms',
460
+			$arguments,
461
+			false,
462
+			false
463
+		);
464
+	}
465
+
466
+
467
+	/**
468
+	 * loads object creating classes - must be singletons
469
+	 *
470
+	 * @param string $class_name - simple class name ie: attendee
471
+	 * @param mixed  $arguments  - an array of arguments to pass to the class
472
+	 * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to
473
+	 *                           instantiate
474
+	 * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
475
+	 *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
476
+	 * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
477
+	 *                           (default)
478
+	 * @return EE_Base_Class | bool
479
+	 * @throws InvalidInterfaceException
480
+	 * @throws InvalidDataTypeException
481
+	 * @throws EE_Error
482
+	 * @throws ReflectionException
483
+	 * @throws InvalidArgumentException
484
+	 */
485
+	public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
486
+	{
487
+		$paths = apply_filters(
488
+			'FHEE__EE_Registry__load_class__paths',
489
+			array(
490
+				EE_CORE,
491
+				EE_CLASSES,
492
+				EE_BUSINESS,
493
+			)
494
+		);
495
+		// retrieve instantiated class
496
+		return $this->_load(
497
+			$paths,
498
+			'EE_',
499
+			$class_name,
500
+			'class',
501
+			$arguments,
502
+			$from_db,
503
+			$cache,
504
+			$load_only
505
+		);
506
+	}
507
+
508
+
509
+	/**
510
+	 * loads helper classes - must be singletons
511
+	 *
512
+	 * @param string $class_name - simple class name ie: price
513
+	 * @param mixed  $arguments
514
+	 * @param bool   $load_only
515
+	 * @return EEH_Base | bool
516
+	 * @throws InvalidInterfaceException
517
+	 * @throws InvalidDataTypeException
518
+	 * @throws EE_Error
519
+	 * @throws ReflectionException
520
+	 * @throws InvalidArgumentException
521
+	 */
522
+	public function load_helper($class_name, $arguments = array(), $load_only = true)
523
+	{
524
+		// todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
525
+		$helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
526
+		// retrieve instantiated class
527
+		return $this->_load(
528
+			$helper_paths,
529
+			'EEH_',
530
+			$class_name,
531
+			'helper',
532
+			$arguments,
533
+			false,
534
+			true,
535
+			$load_only
536
+		);
537
+	}
538
+
539
+
540
+	/**
541
+	 * loads core classes - must be singletons
542
+	 *
543
+	 * @param string $class_name - simple class name ie: session
544
+	 * @param mixed  $arguments
545
+	 * @param bool   $load_only
546
+	 * @param bool   $cache      whether to cache the object or not.
547
+	 * @return mixed
548
+	 * @throws InvalidInterfaceException
549
+	 * @throws InvalidDataTypeException
550
+	 * @throws EE_Error
551
+	 * @throws ReflectionException
552
+	 * @throws InvalidArgumentException
553
+	 */
554
+	public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
555
+	{
556
+		$paths = array(
557
+			EE_LIBRARIES,
558
+			EE_LIBRARIES . 'messages/',
559
+			EE_LIBRARIES . 'shortcodes/',
560
+			EE_LIBRARIES . 'qtips/',
561
+			EE_LIBRARIES . 'payment_methods/',
562
+		);
563
+		// retrieve instantiated class
564
+		return $this->_load(
565
+			$paths,
566
+			'EE_',
567
+			$class_name,
568
+			'lib',
569
+			$arguments,
570
+			false,
571
+			$cache,
572
+			$load_only
573
+		);
574
+	}
575
+
576
+
577
+	/**
578
+	 * loads model classes - must be singletons
579
+	 *
580
+	 * @param string $class_name - simple class name ie: price
581
+	 * @param mixed  $arguments
582
+	 * @param bool   $load_only
583
+	 * @return EEM_Base | bool
584
+	 * @throws InvalidInterfaceException
585
+	 * @throws InvalidDataTypeException
586
+	 * @throws EE_Error
587
+	 * @throws ReflectionException
588
+	 * @throws InvalidArgumentException
589
+	 */
590
+	public function load_model($class_name, $arguments = array(), $load_only = false)
591
+	{
592
+		$paths = apply_filters(
593
+			'FHEE__EE_Registry__load_model__paths',
594
+			array(
595
+				EE_MODELS,
596
+				EE_CORE,
597
+			)
598
+		);
599
+		// retrieve instantiated class
600
+		return $this->_load(
601
+			$paths,
602
+			'EEM_',
603
+			$class_name,
604
+			'model',
605
+			$arguments,
606
+			false,
607
+			true,
608
+			$load_only
609
+		);
610
+	}
611
+
612
+
613
+	/**
614
+	 * loads model classes - must be singletons
615
+	 *
616
+	 * @param string $class_name - simple class name ie: price
617
+	 * @param mixed  $arguments
618
+	 * @param bool   $load_only
619
+	 * @return mixed | bool
620
+	 * @throws InvalidInterfaceException
621
+	 * @throws InvalidDataTypeException
622
+	 * @throws EE_Error
623
+	 * @throws ReflectionException
624
+	 * @throws InvalidArgumentException
625
+	 */
626
+	public function load_model_class($class_name, $arguments = array(), $load_only = true)
627
+	{
628
+		$paths = array(
629
+			EE_MODELS . 'fields/',
630
+			EE_MODELS . 'helpers/',
631
+			EE_MODELS . 'relations/',
632
+			EE_MODELS . 'strategies/',
633
+		);
634
+		// retrieve instantiated class
635
+		return $this->_load(
636
+			$paths,
637
+			'EE_',
638
+			$class_name,
639
+			'',
640
+			$arguments,
641
+			false,
642
+			true,
643
+			$load_only
644
+		);
645
+	}
646
+
647
+
648
+	/**
649
+	 * Determines if $model_name is the name of an actual EE model.
650
+	 *
651
+	 * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
652
+	 * @return boolean
653
+	 */
654
+	public function is_model_name($model_name)
655
+	{
656
+		return isset($this->models[ $model_name ]);
657
+	}
658
+
659
+
660
+	/**
661
+	 * generic class loader
662
+	 *
663
+	 * @param string $path_to_file - directory path to file location, not including filename
664
+	 * @param string $file_name    - file name  ie:  my_file.php, including extension
665
+	 * @param string $type         - file type - core? class? helper? model?
666
+	 * @param mixed  $arguments
667
+	 * @param bool   $load_only
668
+	 * @return mixed
669
+	 * @throws InvalidInterfaceException
670
+	 * @throws InvalidDataTypeException
671
+	 * @throws EE_Error
672
+	 * @throws ReflectionException
673
+	 * @throws InvalidArgumentException
674
+	 */
675
+	public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
676
+	{
677
+		// retrieve instantiated class
678
+		return $this->_load(
679
+			$path_to_file,
680
+			'',
681
+			$file_name,
682
+			$type,
683
+			$arguments,
684
+			false,
685
+			true,
686
+			$load_only
687
+		);
688
+	}
689
+
690
+
691
+	/**
692
+	 * @param string $path_to_file - directory path to file location, not including filename
693
+	 * @param string $class_name   - full class name  ie:  My_Class
694
+	 * @param string $type         - file type - core? class? helper? model?
695
+	 * @param mixed  $arguments
696
+	 * @param bool   $load_only
697
+	 * @return bool|EE_Addon|object
698
+	 * @throws InvalidInterfaceException
699
+	 * @throws InvalidDataTypeException
700
+	 * @throws EE_Error
701
+	 * @throws ReflectionException
702
+	 * @throws InvalidArgumentException
703
+	 */
704
+	public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
705
+	{
706
+		// retrieve instantiated class
707
+		return $this->_load(
708
+			$path_to_file,
709
+			'addon',
710
+			$class_name,
711
+			$type,
712
+			$arguments,
713
+			false,
714
+			true,
715
+			$load_only
716
+		);
717
+	}
718
+
719
+
720
+	/**
721
+	 * instantiates, caches, and automatically resolves dependencies
722
+	 * for classes that use a Fully Qualified Class Name.
723
+	 * if the class is not capable of being loaded using PSR-4 autoloading,
724
+	 * then you need to use one of the existing load_*() methods
725
+	 * which can resolve the classname and filepath from the passed arguments
726
+	 *
727
+	 * @param bool|string $class_name   Fully Qualified Class Name
728
+	 * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
729
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
730
+	 * @param bool        $from_db      some classes are instantiated from the db
731
+	 *                                  and thus call a different method to instantiate
732
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
733
+	 * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
734
+	 * @return bool|null|mixed          null = failure to load or instantiate class object.
735
+	 *                                  object = class loaded and instantiated successfully.
736
+	 *                                  bool = fail or success when $load_only is true
737
+	 * @throws InvalidInterfaceException
738
+	 * @throws InvalidDataTypeException
739
+	 * @throws EE_Error
740
+	 * @throws ReflectionException
741
+	 * @throws InvalidArgumentException
742
+	 */
743
+	public function create(
744
+		$class_name = false,
745
+		$arguments = array(),
746
+		$cache = false,
747
+		$from_db = false,
748
+		$load_only = false,
749
+		$addon = false
750
+	) {
751
+		$class_name = ltrim($class_name, '\\');
752
+		$class_name = $this->class_cache->getFqnForAlias($class_name);
753
+		$class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
754
+		// if a non-FQCN was passed, then
755
+		// verifyClassExists() might return an object
756
+		// or it could return null if the class just could not be found anywhere
757
+		if ($class_exists instanceof $class_name || $class_exists === null) {
758
+			// either way, return the results
759
+			return $class_exists;
760
+		}
761
+		$class_name = $class_exists;
762
+		// if we're only loading the class and it already exists, then let's just return true immediately
763
+		if ($load_only) {
764
+			return true;
765
+		}
766
+		$addon = $addon ? 'addon' : '';
767
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
768
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
769
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
770
+		if ($this->_cache_on && $cache && ! $load_only) {
771
+			// return object if it's already cached
772
+			$cached_class = $this->_get_cached_class($class_name, $addon, $arguments);
773
+			if ($cached_class !== null) {
774
+				return $cached_class;
775
+			}
776
+		}// obtain the loader method from the dependency map
777
+		$loader = $this->_dependency_map->class_loader($class_name);// instantiate the requested object
778
+		if ($loader instanceof Closure) {
779
+			$class_obj = $loader($arguments);
780
+		} else {
781
+			if ($loader && method_exists($this, $loader)) {
782
+				$class_obj = $this->{$loader}($class_name, $arguments);
783
+			} else {
784
+				$class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
785
+			}
786
+		}
787
+		if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
788
+			// save it for later... kinda like gum  { : $
789
+			$this->_set_cached_class(
790
+				$class_obj,
791
+				$class_name,
792
+				$addon,
793
+				$from_db,
794
+				$arguments
795
+			);
796
+		}
797
+		$this->_cache_on = true;
798
+		return $class_obj;
799
+	}
800
+
801
+
802
+	/**
803
+	 * Recursively checks that a class exists and potentially attempts to load classes with non-FQCNs
804
+	 *
805
+	 * @param string|object $class_name
806
+	 * @param array         $arguments
807
+	 * @param int           $attempt
808
+	 * @return mixed
809
+	 */
810
+	private function loadOrVerifyClassExists($class_name, array $arguments, $attempt = 1)
811
+	{
812
+		if (is_object($class_name) || class_exists($class_name)) {
813
+			return $class_name;
814
+		}
815
+		switch ($attempt) {
816
+			case 1:
817
+				// if it's a FQCN then maybe the class is registered with a preceding \
818
+				$class_name = strpos($class_name, '\\') !== false
819
+					? '\\' . ltrim($class_name, '\\')
820
+					: $class_name;
821
+				break;
822
+			case 2:
823
+				//
824
+				$loader = $this->_dependency_map->class_loader($class_name);
825
+				if ($loader && method_exists($this, $loader)) {
826
+					return $this->{$loader}($class_name, $arguments);
827
+				}
828
+				break;
829
+			case 3:
830
+			default:
831
+				return null;
832
+		}
833
+		$attempt++;
834
+		return $this->loadOrVerifyClassExists($class_name, $arguments, $attempt);
835
+	}
836
+
837
+
838
+	/**
839
+	 * instantiates, caches, and injects dependencies for classes
840
+	 *
841
+	 * @param array       $file_paths   an array of paths to folders to look in
842
+	 * @param string      $class_prefix EE  or EEM or... ???
843
+	 * @param bool|string $class_name   $class name
844
+	 * @param string      $type         file type - core? class? helper? model?
845
+	 * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
846
+	 * @param bool        $from_db      some classes are instantiated from the db
847
+	 *                                  and thus call a different method to instantiate
848
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
849
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
850
+	 * @return bool|null|object null = failure to load or instantiate class object.
851
+	 *                                  object = class loaded and instantiated successfully.
852
+	 *                                  bool = fail or success when $load_only is true
853
+	 * @throws EE_Error
854
+	 * @throws ReflectionException
855
+	 * @throws InvalidInterfaceException
856
+	 * @throws InvalidDataTypeException
857
+	 * @throws InvalidArgumentException
858
+	 */
859
+	protected function _load(
860
+		$file_paths = array(),
861
+		$class_prefix = 'EE_',
862
+		$class_name = false,
863
+		$type = 'class',
864
+		$arguments = array(),
865
+		$from_db = false,
866
+		$cache = true,
867
+		$load_only = false
868
+	) {
869
+		$class_name = ltrim($class_name, '\\');
870
+		// strip php file extension
871
+		$class_name = str_replace('.php', '', trim($class_name));
872
+		// does the class have a prefix ?
873
+		if (! empty($class_prefix) && $class_prefix !== 'addon') {
874
+			// make sure $class_prefix is uppercase
875
+			$class_prefix = strtoupper(trim($class_prefix));
876
+			// add class prefix ONCE!!!
877
+			$class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
878
+		}
879
+		$class_name = $this->class_cache->getFqnForAlias($class_name);
880
+		$class_exists = class_exists($class_name, false);
881
+		// if we're only loading the class and it already exists, then let's just return true immediately
882
+		if ($load_only && $class_exists) {
883
+			return true;
884
+		}
885
+		$arguments = is_array($arguments) ? $arguments : array($arguments);
886
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
887
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
888
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
889
+		if ($this->_cache_on && $cache && ! $load_only) {
890
+			// return object if it's already cached
891
+			$cached_class = $this->_get_cached_class($class_name, $class_prefix, $arguments);
892
+			if ($cached_class !== null) {
893
+				return $cached_class;
894
+			}
895
+		}
896
+		// if the class doesn't already exist.. then we need to try and find the file and load it
897
+		if (! $class_exists) {
898
+			// get full path to file
899
+			$path = $this->_resolve_path($class_name, $type, $file_paths);
900
+			// load the file
901
+			$loaded = $this->_require_file($path, $class_name, $type, $file_paths);
902
+			// if we are only loading a file but NOT instantiating an object
903
+			// then return boolean for whether class was loaded or not
904
+			if ($load_only) {
905
+				return $loaded;
906
+			}
907
+			// if an object was expected but loading failed, then return nothing
908
+			if (! $loaded) {
909
+				return null;
910
+			}
911
+		}
912
+		// instantiate the requested object
913
+		$class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
914
+		if ($this->_cache_on && $cache) {
915
+			// save it for later... kinda like gum  { : $
916
+			$this->_set_cached_class(
917
+				$class_obj,
918
+				$class_name,
919
+				$class_prefix,
920
+				$from_db,
921
+				$arguments
922
+			);
923
+		}
924
+		$this->_cache_on = true;
925
+		return $class_obj;
926
+	}
927
+
928
+
929
+	/**
930
+	 * @param string $class_name
931
+	 * @param string $default have to specify something, but not anything that will conflict
932
+	 * @return mixed|string
933
+	 */
934
+	protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
935
+	{
936
+		return isset($this->_class_abbreviations[ $class_name ])
937
+			? $this->_class_abbreviations[ $class_name ]
938
+			: $default;
939
+	}
940
+
941
+
942
+	/**
943
+	 * attempts to find a cached version of the requested class
944
+	 * by looking in the following places:
945
+	 *        $this->{$class_abbreviation}            ie:    $this->CART
946
+	 *        $this->{$class_name}                        ie:    $this->Some_Class
947
+	 *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
948
+	 *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
949
+	 *
950
+	 * @param string $class_name
951
+	 * @param string $class_prefix
952
+	 * @param array  $arguments
953
+	 * @return mixed
954
+	 */
955
+	protected function _get_cached_class(
956
+		$class_name,
957
+		$class_prefix = '',
958
+		$arguments = array()
959
+	) {
960
+		if ($class_name === 'EE_Registry') {
961
+			return $this;
962
+		}
963
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
964
+		// check if class has already been loaded, and return it if it has been
965
+		if (isset($this->{$class_abbreviation})) {
966
+			return $this->{$class_abbreviation};
967
+		}
968
+		$class_name = str_replace('\\', '_', $class_name);
969
+		if (isset($this->{$class_name})) {
970
+			return $this->{$class_name};
971
+		}
972
+		if ($class_prefix === 'addon' && $this->addons->has($class_name)) {
973
+			return $this->addons->get($class_name);
974
+		}
975
+		$object_identifier = $this->object_identifier->getIdentifier($class_name, $arguments);
976
+		if ($this->LIB->has($object_identifier)) {
977
+			return $this->LIB->get($object_identifier);
978
+		}
979
+		foreach ($this->LIB as $key => $object) {
980
+			if (
981 981
 // request does not contain new arguments and therefore no args identifier
982
-                ! $this->object_identifier->hasArguments($object_identifier)
983
-                // but previously cached class with args was found
984
-                && $this->object_identifier->fqcnMatchesObjectIdentifier($class_name, $key)
985
-            ) {
986
-                return $object;
987
-            }
988
-        }
989
-        return null;
990
-    }
991
-
992
-
993
-    /**
994
-     * removes a cached version of the requested class
995
-     *
996
-     * @param string  $class_name
997
-     * @param boolean $addon
998
-     * @param array   $arguments
999
-     * @return boolean
1000
-     */
1001
-    public function clear_cached_class(
1002
-        $class_name,
1003
-        $addon = false,
1004
-        $arguments = array()
1005
-    ) {
1006
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
1007
-        // check if class has already been loaded, and return it if it has been
1008
-        if (isset($this->{$class_abbreviation})) {
1009
-            $this->{$class_abbreviation} = null;
1010
-            return true;
1011
-        }
1012
-        $class_name = str_replace('\\', '_', $class_name);
1013
-        if (isset($this->{$class_name})) {
1014
-            $this->{$class_name} = null;
1015
-            return true;
1016
-        }
1017
-        if ($addon && $this->addons->has($class_name)) {
1018
-            $this->addons->remove($class_name);
1019
-            return true;
1020
-        }
1021
-        $class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
1022
-        if ($this->LIB->has($class_name)) {
1023
-            $this->LIB->remove($class_name);
1024
-            return true;
1025
-        }
1026
-        return false;
1027
-    }
1028
-
1029
-
1030
-    /**
1031
-     * _set_cached_class
1032
-     * attempts to cache the instantiated class locally
1033
-     * in one of the following places, in the following order:
1034
-     *        $this->{class_abbreviation}   ie:    $this->CART
1035
-     *        $this->{$class_name}          ie:    $this->Some_Class
1036
-     *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1037
-     *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1038
-     *
1039
-     * @param object $class_obj
1040
-     * @param string $class_name
1041
-     * @param string $class_prefix
1042
-     * @param bool   $from_db
1043
-     * @param array  $arguments
1044
-     * @return void
1045
-     */
1046
-    protected function _set_cached_class(
1047
-        $class_obj,
1048
-        $class_name,
1049
-        $class_prefix = '',
1050
-        $from_db = false,
1051
-        $arguments = array()
1052
-    ) {
1053
-        if ($class_name === 'EE_Registry' || empty($class_obj)) {
1054
-            return;
1055
-        }
1056
-        // return newly instantiated class
1057
-        $class_abbreviation = $this->get_class_abbreviation($class_name, '');
1058
-        if ($class_abbreviation) {
1059
-            $this->{$class_abbreviation} = $class_obj;
1060
-            return;
1061
-        }
1062
-        $class_name = str_replace('\\', '_', $class_name);
1063
-        if (property_exists($this, $class_name)) {
1064
-            $this->{$class_name} = $class_obj;
1065
-            return;
1066
-        }
1067
-        if ($class_prefix === 'addon') {
1068
-            $this->addons->add($class_name, $class_obj);
1069
-            return;
1070
-        }
1071
-        if (! $from_db) {
1072
-            $class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
1073
-            $this->LIB->add($class_name, $class_obj);
1074
-        }
1075
-    }
1076
-
1077
-
1078
-    /**
1079
-     * attempts to find a full valid filepath for the requested class.
1080
-     * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
1081
-     * then returns that path if the target file has been found and is readable
1082
-     *
1083
-     * @param string $class_name
1084
-     * @param string $type
1085
-     * @param array  $file_paths
1086
-     * @return string | bool
1087
-     */
1088
-    protected function _resolve_path($class_name, $type = '', $file_paths = array())
1089
-    {
1090
-        // make sure $file_paths is an array
1091
-        $file_paths = is_array($file_paths)
1092
-            ? $file_paths
1093
-            : array($file_paths);
1094
-        // cycle thru paths
1095
-        foreach ($file_paths as $key => $file_path) {
1096
-            // convert all separators to proper /, if no filepath, then use EE_CLASSES
1097
-            $file_path = $file_path
1098
-                ? str_replace(array('/', '\\'), '/', $file_path)
1099
-                : EE_CLASSES;
1100
-            // prep file type
1101
-            $type = ! empty($type)
1102
-                ? trim($type, '.') . '.'
1103
-                : '';
1104
-            // build full file path
1105
-            $file_paths[ $key ] = rtrim($file_path, '/') . '/' . $class_name . '.' . $type . 'php';
1106
-            // does the file exist and can be read ?
1107
-            if (is_readable($file_paths[ $key ])) {
1108
-                return $file_paths[ $key ];
1109
-            }
1110
-        }
1111
-        return false;
1112
-    }
1113
-
1114
-
1115
-    /**
1116
-     * basically just performs a require_once()
1117
-     * but with some error handling
1118
-     *
1119
-     * @param  string $path
1120
-     * @param  string $class_name
1121
-     * @param  string $type
1122
-     * @param  array  $file_paths
1123
-     * @return bool
1124
-     * @throws EE_Error
1125
-     * @throws ReflectionException
1126
-     */
1127
-    protected function _require_file($path, $class_name, $type = '', $file_paths = array())
1128
-    {
1129
-        $this->resolve_legacy_class_parent($class_name);
1130
-        // don't give up! you gotta...
1131
-        try {
1132
-            // does the file exist and can it be read ?
1133
-            if (! $path) {
1134
-                // just in case the file has already been autoloaded,
1135
-                // but discrepancies in the naming schema are preventing it from
1136
-                // being loaded via one of the EE_Registry::load_*() methods,
1137
-                // then let's try one last hail mary before throwing an exception
1138
-                // and call class_exists() again, but with autoloading turned ON
1139
-                if (class_exists($class_name)) {
1140
-                    return true;
1141
-                }
1142
-                // so sorry, can't find the file
1143
-                throw new EE_Error(
1144
-                    sprintf(
1145
-                        esc_html__(
1146
-                            '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',
1147
-                            'event_espresso'
1148
-                        ),
1149
-                        trim($type, '.'),
1150
-                        $class_name,
1151
-                        '<br />' . implode(',<br />', $file_paths)
1152
-                    )
1153
-                );
1154
-            }
1155
-            // get the file
1156
-            require_once($path);
1157
-            // if the class isn't already declared somewhere
1158
-            if (class_exists($class_name, false) === false) {
1159
-                // so sorry, not a class
1160
-                throw new EE_Error(
1161
-                    sprintf(
1162
-                        esc_html__(
1163
-                            'The %s file %s does not appear to contain the %s Class.',
1164
-                            'event_espresso'
1165
-                        ),
1166
-                        $type,
1167
-                        $path,
1168
-                        $class_name
1169
-                    )
1170
-                );
1171
-            }
1172
-        } catch (EE_Error $e) {
1173
-            $e->get_error();
1174
-            return false;
1175
-        }
1176
-        return true;
1177
-    }
1178
-
1179
-
1180
-    /**
1181
-     * Some of our legacy classes that extended a parent class would simply use a require() statement
1182
-     * before their class declaration in order to ensure that the parent class was loaded.
1183
-     * This is not ideal, but it's nearly impossible to determine the parent class of a non-namespaced class,
1184
-     * without triggering a fatal error because the parent class has yet to be loaded and therefore doesn't exist.
1185
-     *
1186
-     * @param string $class_name
1187
-     */
1188
-    protected function resolve_legacy_class_parent($class_name = '')
1189
-    {
1190
-        try {
1191
-            $legacy_parent_class_map = array(
1192
-                'EE_Payment_Processor' => 'core/business/EE_Processor_Base.class.php',
1193
-            );
1194
-            if (isset($legacy_parent_class_map[ $class_name ])) {
1195
-                require_once EE_PLUGIN_DIR_PATH . $legacy_parent_class_map[ $class_name ];
1196
-            }
1197
-        } catch (Exception $exception) {
1198
-        }
1199
-    }
1200
-
1201
-
1202
-    /**
1203
-     * _create_object
1204
-     * Attempts to instantiate the requested class via any of the
1205
-     * commonly used instantiation methods employed throughout EE.
1206
-     * The priority for instantiation is as follows:
1207
-     *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
1208
-     *        - model objects via their 'new_instance_from_db' method
1209
-     *        - model objects via their 'new_instance' method
1210
-     *        - "singleton" classes" via their 'instance' method
1211
-     *    - standard instantiable classes via their __constructor
1212
-     * Prior to instantiation, if the classname exists in the dependency_map,
1213
-     * then the constructor for the requested class will be examined to determine
1214
-     * if any dependencies exist, and if they can be injected.
1215
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1216
-     *
1217
-     * @param string $class_name
1218
-     * @param array  $arguments
1219
-     * @param string $type
1220
-     * @param bool   $from_db
1221
-     * @return null|object|bool
1222
-     * @throws InvalidArgumentException
1223
-     * @throws InvalidInterfaceException
1224
-     * @throws EE_Error
1225
-     * @throws ReflectionException
1226
-     * @throws InvalidDataTypeException
1227
-     */
1228
-    protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
1229
-    {
1230
-        // create reflection
1231
-        $reflector = $this->mirror->getReflectionClass($class_name);
1232
-        // make sure arguments are an array
1233
-        $arguments = is_array($arguments)
1234
-            ? $arguments
1235
-            : array($arguments);
1236
-        // and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1237
-        // else wrap it in an additional array so that it doesn't get split into multiple parameters
1238
-        $arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1239
-            ? $arguments
1240
-            : array($arguments);
1241
-        // attempt to inject dependencies ?
1242
-        if ($this->_dependency_map->has($class_name)) {
1243
-            $arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1244
-        }
1245
-        // instantiate the class if possible
1246
-        if ($reflector->isAbstract()) {
1247
-            // nothing to instantiate, loading file was enough
1248
-            // does not throw an exception so $instantiation_mode is unused
1249
-            // $instantiation_mode = "1) no constructor abstract class";
1250
-            return true;
1251
-        }
1252
-        if (
1253
-            empty($arguments)
1254
-            && $this->mirror->getConstructorFromReflection($reflector) === null
1255
-            && $reflector->isInstantiable()
1256
-        ) {
1257
-            // no constructor = static methods only... nothing to instantiate, loading file was enough
1258
-            // $instantiation_mode = "2) no constructor but instantiable";
1259
-            return $reflector->newInstance();
1260
-        }
1261
-        if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
1262
-            // $instantiation_mode = "3) new_instance_from_db()";
1263
-            return call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
1264
-        }
1265
-        if (method_exists($class_name, 'new_instance')) {
1266
-            // $instantiation_mode = "4) new_instance()";
1267
-            return call_user_func_array(array($class_name, 'new_instance'), $arguments);
1268
-        }
1269
-        if (method_exists($class_name, 'instance')) {
1270
-            // $instantiation_mode = "5) instance()";
1271
-            return call_user_func_array(array($class_name, 'instance'), $arguments);
1272
-        }
1273
-        if ($reflector->isInstantiable()) {
1274
-            // $instantiation_mode = "6) constructor";
1275
-            return $reflector->newInstanceArgs($arguments);
1276
-        }
1277
-        // heh ? something's not right !
1278
-        throw new EE_Error(
1279
-            sprintf(
1280
-                esc_html__('The %s file %s could not be instantiated.', 'event_espresso'),
1281
-                $type,
1282
-                $class_name
1283
-            )
1284
-        );
1285
-    }
1286
-
1287
-
1288
-    /**
1289
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1290
-     * @param array $array
1291
-     * @return bool
1292
-     */
1293
-    protected function _array_is_numerically_and_sequentially_indexed(array $array)
1294
-    {
1295
-        return ! empty($array)
1296
-            ? array_keys($array) === range(0, count($array) - 1)
1297
-            : true;
1298
-    }
1299
-
1300
-
1301
-    /**
1302
-     * _resolve_dependencies
1303
-     * examines the constructor for the requested class to determine
1304
-     * if any dependencies exist, and if they can be injected.
1305
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1306
-     * PLZ NOTE: this is achieved by type hinting the constructor params
1307
-     * For example:
1308
-     *        if attempting to load a class "Foo" with the following constructor:
1309
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
1310
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
1311
-     *        but only IF they are NOT already present in the incoming arguments array,
1312
-     *        and the correct classes can be loaded
1313
-     *
1314
-     * @param ReflectionClass $reflector
1315
-     * @param string          $class_name
1316
-     * @param array           $arguments
1317
-     * @return array
1318
-     * @throws InvalidArgumentException
1319
-     * @throws InvalidDataTypeException
1320
-     * @throws InvalidInterfaceException
1321
-     * @throws ReflectionException
1322
-     */
1323
-    protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, array $arguments = array())
1324
-    {
1325
-        // let's examine the constructor
1326
-        $constructor = $this->mirror->getConstructorFromReflection($reflector);
1327
-        // whu? huh? nothing?
1328
-        if (! $constructor) {
1329
-            return $arguments;
1330
-        }
1331
-        // get constructor parameters
1332
-        $params = $this->mirror->getParametersFromReflection($reflector);
1333
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1334
-        $argument_keys = array_keys($arguments);
1335
-        // now loop thru all of the constructors expected parameters
1336
-        foreach ($params as $index => $param) {
1337
-            try {
1338
-                // is this a dependency for a specific class ?
1339
-                $param_class = $this->mirror->getParameterClassName($param, $class_name, $index);
1340
-            } catch (ReflectionException $exception) {
1341
-                // uh-oh... most likely a legacy class that has not been autoloaded
1342
-                // let's try to derive the classname from what we have now
1343
-                // and hope that the property var name is close to the class name
1344
-                $param_class = $param->getName();
1345
-                $param_class = str_replace('_', ' ', $param_class);
1346
-                $param_class = ucwords($param_class);
1347
-                $param_class = str_replace(' ', '_', $param_class);
1348
-            }
1349
-            // BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1350
-            $param_class = $this->class_cache->isAlias($param_class, $class_name)
1351
-                ? $this->class_cache->getFqnForAlias($param_class, $class_name)
1352
-                : $param_class;
1353
-            if (
982
+				! $this->object_identifier->hasArguments($object_identifier)
983
+				// but previously cached class with args was found
984
+				&& $this->object_identifier->fqcnMatchesObjectIdentifier($class_name, $key)
985
+			) {
986
+				return $object;
987
+			}
988
+		}
989
+		return null;
990
+	}
991
+
992
+
993
+	/**
994
+	 * removes a cached version of the requested class
995
+	 *
996
+	 * @param string  $class_name
997
+	 * @param boolean $addon
998
+	 * @param array   $arguments
999
+	 * @return boolean
1000
+	 */
1001
+	public function clear_cached_class(
1002
+		$class_name,
1003
+		$addon = false,
1004
+		$arguments = array()
1005
+	) {
1006
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
1007
+		// check if class has already been loaded, and return it if it has been
1008
+		if (isset($this->{$class_abbreviation})) {
1009
+			$this->{$class_abbreviation} = null;
1010
+			return true;
1011
+		}
1012
+		$class_name = str_replace('\\', '_', $class_name);
1013
+		if (isset($this->{$class_name})) {
1014
+			$this->{$class_name} = null;
1015
+			return true;
1016
+		}
1017
+		if ($addon && $this->addons->has($class_name)) {
1018
+			$this->addons->remove($class_name);
1019
+			return true;
1020
+		}
1021
+		$class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
1022
+		if ($this->LIB->has($class_name)) {
1023
+			$this->LIB->remove($class_name);
1024
+			return true;
1025
+		}
1026
+		return false;
1027
+	}
1028
+
1029
+
1030
+	/**
1031
+	 * _set_cached_class
1032
+	 * attempts to cache the instantiated class locally
1033
+	 * in one of the following places, in the following order:
1034
+	 *        $this->{class_abbreviation}   ie:    $this->CART
1035
+	 *        $this->{$class_name}          ie:    $this->Some_Class
1036
+	 *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1037
+	 *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1038
+	 *
1039
+	 * @param object $class_obj
1040
+	 * @param string $class_name
1041
+	 * @param string $class_prefix
1042
+	 * @param bool   $from_db
1043
+	 * @param array  $arguments
1044
+	 * @return void
1045
+	 */
1046
+	protected function _set_cached_class(
1047
+		$class_obj,
1048
+		$class_name,
1049
+		$class_prefix = '',
1050
+		$from_db = false,
1051
+		$arguments = array()
1052
+	) {
1053
+		if ($class_name === 'EE_Registry' || empty($class_obj)) {
1054
+			return;
1055
+		}
1056
+		// return newly instantiated class
1057
+		$class_abbreviation = $this->get_class_abbreviation($class_name, '');
1058
+		if ($class_abbreviation) {
1059
+			$this->{$class_abbreviation} = $class_obj;
1060
+			return;
1061
+		}
1062
+		$class_name = str_replace('\\', '_', $class_name);
1063
+		if (property_exists($this, $class_name)) {
1064
+			$this->{$class_name} = $class_obj;
1065
+			return;
1066
+		}
1067
+		if ($class_prefix === 'addon') {
1068
+			$this->addons->add($class_name, $class_obj);
1069
+			return;
1070
+		}
1071
+		if (! $from_db) {
1072
+			$class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
1073
+			$this->LIB->add($class_name, $class_obj);
1074
+		}
1075
+	}
1076
+
1077
+
1078
+	/**
1079
+	 * attempts to find a full valid filepath for the requested class.
1080
+	 * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
1081
+	 * then returns that path if the target file has been found and is readable
1082
+	 *
1083
+	 * @param string $class_name
1084
+	 * @param string $type
1085
+	 * @param array  $file_paths
1086
+	 * @return string | bool
1087
+	 */
1088
+	protected function _resolve_path($class_name, $type = '', $file_paths = array())
1089
+	{
1090
+		// make sure $file_paths is an array
1091
+		$file_paths = is_array($file_paths)
1092
+			? $file_paths
1093
+			: array($file_paths);
1094
+		// cycle thru paths
1095
+		foreach ($file_paths as $key => $file_path) {
1096
+			// convert all separators to proper /, if no filepath, then use EE_CLASSES
1097
+			$file_path = $file_path
1098
+				? str_replace(array('/', '\\'), '/', $file_path)
1099
+				: EE_CLASSES;
1100
+			// prep file type
1101
+			$type = ! empty($type)
1102
+				? trim($type, '.') . '.'
1103
+				: '';
1104
+			// build full file path
1105
+			$file_paths[ $key ] = rtrim($file_path, '/') . '/' . $class_name . '.' . $type . 'php';
1106
+			// does the file exist and can be read ?
1107
+			if (is_readable($file_paths[ $key ])) {
1108
+				return $file_paths[ $key ];
1109
+			}
1110
+		}
1111
+		return false;
1112
+	}
1113
+
1114
+
1115
+	/**
1116
+	 * basically just performs a require_once()
1117
+	 * but with some error handling
1118
+	 *
1119
+	 * @param  string $path
1120
+	 * @param  string $class_name
1121
+	 * @param  string $type
1122
+	 * @param  array  $file_paths
1123
+	 * @return bool
1124
+	 * @throws EE_Error
1125
+	 * @throws ReflectionException
1126
+	 */
1127
+	protected function _require_file($path, $class_name, $type = '', $file_paths = array())
1128
+	{
1129
+		$this->resolve_legacy_class_parent($class_name);
1130
+		// don't give up! you gotta...
1131
+		try {
1132
+			// does the file exist and can it be read ?
1133
+			if (! $path) {
1134
+				// just in case the file has already been autoloaded,
1135
+				// but discrepancies in the naming schema are preventing it from
1136
+				// being loaded via one of the EE_Registry::load_*() methods,
1137
+				// then let's try one last hail mary before throwing an exception
1138
+				// and call class_exists() again, but with autoloading turned ON
1139
+				if (class_exists($class_name)) {
1140
+					return true;
1141
+				}
1142
+				// so sorry, can't find the file
1143
+				throw new EE_Error(
1144
+					sprintf(
1145
+						esc_html__(
1146
+							'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',
1147
+							'event_espresso'
1148
+						),
1149
+						trim($type, '.'),
1150
+						$class_name,
1151
+						'<br />' . implode(',<br />', $file_paths)
1152
+					)
1153
+				);
1154
+			}
1155
+			// get the file
1156
+			require_once($path);
1157
+			// if the class isn't already declared somewhere
1158
+			if (class_exists($class_name, false) === false) {
1159
+				// so sorry, not a class
1160
+				throw new EE_Error(
1161
+					sprintf(
1162
+						esc_html__(
1163
+							'The %s file %s does not appear to contain the %s Class.',
1164
+							'event_espresso'
1165
+						),
1166
+						$type,
1167
+						$path,
1168
+						$class_name
1169
+					)
1170
+				);
1171
+			}
1172
+		} catch (EE_Error $e) {
1173
+			$e->get_error();
1174
+			return false;
1175
+		}
1176
+		return true;
1177
+	}
1178
+
1179
+
1180
+	/**
1181
+	 * Some of our legacy classes that extended a parent class would simply use a require() statement
1182
+	 * before their class declaration in order to ensure that the parent class was loaded.
1183
+	 * This is not ideal, but it's nearly impossible to determine the parent class of a non-namespaced class,
1184
+	 * without triggering a fatal error because the parent class has yet to be loaded and therefore doesn't exist.
1185
+	 *
1186
+	 * @param string $class_name
1187
+	 */
1188
+	protected function resolve_legacy_class_parent($class_name = '')
1189
+	{
1190
+		try {
1191
+			$legacy_parent_class_map = array(
1192
+				'EE_Payment_Processor' => 'core/business/EE_Processor_Base.class.php',
1193
+			);
1194
+			if (isset($legacy_parent_class_map[ $class_name ])) {
1195
+				require_once EE_PLUGIN_DIR_PATH . $legacy_parent_class_map[ $class_name ];
1196
+			}
1197
+		} catch (Exception $exception) {
1198
+		}
1199
+	}
1200
+
1201
+
1202
+	/**
1203
+	 * _create_object
1204
+	 * Attempts to instantiate the requested class via any of the
1205
+	 * commonly used instantiation methods employed throughout EE.
1206
+	 * The priority for instantiation is as follows:
1207
+	 *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
1208
+	 *        - model objects via their 'new_instance_from_db' method
1209
+	 *        - model objects via their 'new_instance' method
1210
+	 *        - "singleton" classes" via their 'instance' method
1211
+	 *    - standard instantiable classes via their __constructor
1212
+	 * Prior to instantiation, if the classname exists in the dependency_map,
1213
+	 * then the constructor for the requested class will be examined to determine
1214
+	 * if any dependencies exist, and if they can be injected.
1215
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1216
+	 *
1217
+	 * @param string $class_name
1218
+	 * @param array  $arguments
1219
+	 * @param string $type
1220
+	 * @param bool   $from_db
1221
+	 * @return null|object|bool
1222
+	 * @throws InvalidArgumentException
1223
+	 * @throws InvalidInterfaceException
1224
+	 * @throws EE_Error
1225
+	 * @throws ReflectionException
1226
+	 * @throws InvalidDataTypeException
1227
+	 */
1228
+	protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
1229
+	{
1230
+		// create reflection
1231
+		$reflector = $this->mirror->getReflectionClass($class_name);
1232
+		// make sure arguments are an array
1233
+		$arguments = is_array($arguments)
1234
+			? $arguments
1235
+			: array($arguments);
1236
+		// and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1237
+		// else wrap it in an additional array so that it doesn't get split into multiple parameters
1238
+		$arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1239
+			? $arguments
1240
+			: array($arguments);
1241
+		// attempt to inject dependencies ?
1242
+		if ($this->_dependency_map->has($class_name)) {
1243
+			$arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1244
+		}
1245
+		// instantiate the class if possible
1246
+		if ($reflector->isAbstract()) {
1247
+			// nothing to instantiate, loading file was enough
1248
+			// does not throw an exception so $instantiation_mode is unused
1249
+			// $instantiation_mode = "1) no constructor abstract class";
1250
+			return true;
1251
+		}
1252
+		if (
1253
+			empty($arguments)
1254
+			&& $this->mirror->getConstructorFromReflection($reflector) === null
1255
+			&& $reflector->isInstantiable()
1256
+		) {
1257
+			// no constructor = static methods only... nothing to instantiate, loading file was enough
1258
+			// $instantiation_mode = "2) no constructor but instantiable";
1259
+			return $reflector->newInstance();
1260
+		}
1261
+		if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
1262
+			// $instantiation_mode = "3) new_instance_from_db()";
1263
+			return call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
1264
+		}
1265
+		if (method_exists($class_name, 'new_instance')) {
1266
+			// $instantiation_mode = "4) new_instance()";
1267
+			return call_user_func_array(array($class_name, 'new_instance'), $arguments);
1268
+		}
1269
+		if (method_exists($class_name, 'instance')) {
1270
+			// $instantiation_mode = "5) instance()";
1271
+			return call_user_func_array(array($class_name, 'instance'), $arguments);
1272
+		}
1273
+		if ($reflector->isInstantiable()) {
1274
+			// $instantiation_mode = "6) constructor";
1275
+			return $reflector->newInstanceArgs($arguments);
1276
+		}
1277
+		// heh ? something's not right !
1278
+		throw new EE_Error(
1279
+			sprintf(
1280
+				esc_html__('The %s file %s could not be instantiated.', 'event_espresso'),
1281
+				$type,
1282
+				$class_name
1283
+			)
1284
+		);
1285
+	}
1286
+
1287
+
1288
+	/**
1289
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1290
+	 * @param array $array
1291
+	 * @return bool
1292
+	 */
1293
+	protected function _array_is_numerically_and_sequentially_indexed(array $array)
1294
+	{
1295
+		return ! empty($array)
1296
+			? array_keys($array) === range(0, count($array) - 1)
1297
+			: true;
1298
+	}
1299
+
1300
+
1301
+	/**
1302
+	 * _resolve_dependencies
1303
+	 * examines the constructor for the requested class to determine
1304
+	 * if any dependencies exist, and if they can be injected.
1305
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1306
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
1307
+	 * For example:
1308
+	 *        if attempting to load a class "Foo" with the following constructor:
1309
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
1310
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
1311
+	 *        but only IF they are NOT already present in the incoming arguments array,
1312
+	 *        and the correct classes can be loaded
1313
+	 *
1314
+	 * @param ReflectionClass $reflector
1315
+	 * @param string          $class_name
1316
+	 * @param array           $arguments
1317
+	 * @return array
1318
+	 * @throws InvalidArgumentException
1319
+	 * @throws InvalidDataTypeException
1320
+	 * @throws InvalidInterfaceException
1321
+	 * @throws ReflectionException
1322
+	 */
1323
+	protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, array $arguments = array())
1324
+	{
1325
+		// let's examine the constructor
1326
+		$constructor = $this->mirror->getConstructorFromReflection($reflector);
1327
+		// whu? huh? nothing?
1328
+		if (! $constructor) {
1329
+			return $arguments;
1330
+		}
1331
+		// get constructor parameters
1332
+		$params = $this->mirror->getParametersFromReflection($reflector);
1333
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1334
+		$argument_keys = array_keys($arguments);
1335
+		// now loop thru all of the constructors expected parameters
1336
+		foreach ($params as $index => $param) {
1337
+			try {
1338
+				// is this a dependency for a specific class ?
1339
+				$param_class = $this->mirror->getParameterClassName($param, $class_name, $index);
1340
+			} catch (ReflectionException $exception) {
1341
+				// uh-oh... most likely a legacy class that has not been autoloaded
1342
+				// let's try to derive the classname from what we have now
1343
+				// and hope that the property var name is close to the class name
1344
+				$param_class = $param->getName();
1345
+				$param_class = str_replace('_', ' ', $param_class);
1346
+				$param_class = ucwords($param_class);
1347
+				$param_class = str_replace(' ', '_', $param_class);
1348
+			}
1349
+			// BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1350
+			$param_class = $this->class_cache->isAlias($param_class, $class_name)
1351
+				? $this->class_cache->getFqnForAlias($param_class, $class_name)
1352
+				: $param_class;
1353
+			if (
1354 1354
 // param is not even a class
1355
-                $param_class === null
1356
-                // and something already exists in the incoming arguments for this param
1357
-                && array_key_exists($index, $argument_keys)
1358
-                && array_key_exists($argument_keys[ $index ], $arguments)
1359
-            ) {
1360
-                // so let's skip this argument and move on to the next
1361
-                continue;
1362
-            }
1363
-            if (
1355
+				$param_class === null
1356
+				// and something already exists in the incoming arguments for this param
1357
+				&& array_key_exists($index, $argument_keys)
1358
+				&& array_key_exists($argument_keys[ $index ], $arguments)
1359
+			) {
1360
+				// so let's skip this argument and move on to the next
1361
+				continue;
1362
+			}
1363
+			if (
1364 1364
 // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1365
-                $param_class !== null
1366
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
1367
-                && $arguments[ $argument_keys[ $index ] ] instanceof $param_class
1368
-            ) {
1369
-                // skip this argument and move on to the next
1370
-                continue;
1371
-            }
1372
-            if (
1365
+				$param_class !== null
1366
+				&& isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
1367
+				&& $arguments[ $argument_keys[ $index ] ] instanceof $param_class
1368
+			) {
1369
+				// skip this argument and move on to the next
1370
+				continue;
1371
+			}
1372
+			if (
1373 1373
 // parameter is type hinted as a class, and should be injected
1374
-                $param_class !== null
1375
-                && $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1376
-            ) {
1377
-                $arguments = $this->_resolve_dependency(
1378
-                    $class_name,
1379
-                    $param_class,
1380
-                    $arguments,
1381
-                    $index
1382
-                );
1383
-            }
1384
-            if (empty($arguments[ $index ])) {
1385
-                $arguments[ $index ] = $this->mirror->getParameterDefaultValue(
1386
-                    $param,
1387
-                    $class_name,
1388
-                    $index
1389
-                );
1390
-            }
1391
-        }
1392
-        return $arguments;
1393
-    }
1394
-
1395
-
1396
-    /**
1397
-     * @param string $class_name
1398
-     * @param string $param_class
1399
-     * @param array  $arguments
1400
-     * @param mixed  $index
1401
-     * @return array
1402
-     * @throws InvalidArgumentException
1403
-     * @throws InvalidInterfaceException
1404
-     * @throws InvalidDataTypeException
1405
-     */
1406
-    protected function _resolve_dependency($class_name, $param_class, $arguments, $index)
1407
-    {
1408
-        $dependency = null;
1409
-        // should dependency be loaded from cache ?
1410
-        $cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1411
-            $class_name,
1412
-            $param_class
1413
-        );
1414
-        $cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1415
-        // we might have a dependency...
1416
-        // let's MAYBE try and find it in our cache if that's what's been requested
1417
-        $cached_class = $cache_on
1418
-            ? $this->_get_cached_class($param_class)
1419
-            : null;
1420
-        // and grab it if it exists
1421
-        if ($cached_class instanceof $param_class) {
1422
-            $dependency = $cached_class;
1423
-        } elseif ($param_class !== $class_name) {
1424
-            // obtain the loader method from the dependency map
1425
-            $loader = $this->_dependency_map->class_loader($param_class);
1426
-            // is loader a custom closure ?
1427
-            if ($loader instanceof Closure) {
1428
-                $dependency = $loader($arguments);
1429
-            } else {
1430
-                // set the cache on property for the recursive loading call
1431
-                $this->_cache_on = $cache_on;
1432
-                // if not, then let's try and load it via the registry
1433
-                if ($loader && method_exists($this, $loader)) {
1434
-                    $dependency = $this->{$loader}($param_class);
1435
-                } else {
1436
-                    $dependency = LoaderFactory::getLoader()->load(
1437
-                        $param_class,
1438
-                        array(),
1439
-                        $cache_on
1440
-                    );
1441
-                }
1442
-            }
1443
-        }
1444
-        // did we successfully find the correct dependency ?
1445
-        if ($dependency instanceof $param_class) {
1446
-            // then let's inject it into the incoming array of arguments at the correct location
1447
-            $arguments[ $index ] = $dependency;
1448
-        }
1449
-        return $arguments;
1450
-    }
1451
-
1452
-
1453
-    /**
1454
-     * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1455
-     *
1456
-     * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1457
-     *                          in the EE_Dependency_Map::$_class_loaders array,
1458
-     *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1459
-     * @param array  $arguments
1460
-     * @return object
1461
-     */
1462
-    public static function factory($classname, $arguments = array())
1463
-    {
1464
-        $loader = self::instance()->_dependency_map->class_loader($classname);
1465
-        if ($loader instanceof Closure) {
1466
-            return $loader($arguments);
1467
-        }
1468
-        if (method_exists(self::instance(), $loader)) {
1469
-            return self::instance()->{$loader}($classname, $arguments);
1470
-        }
1471
-        return null;
1472
-    }
1473
-
1474
-
1475
-    /**
1476
-     * Gets the addon by its class name
1477
-     *
1478
-     * @param string $class_name
1479
-     * @return EE_Addon
1480
-     */
1481
-    public function getAddon($class_name)
1482
-    {
1483
-        $class_name = str_replace('\\', '_', $class_name);
1484
-        if (isset($this->addons->{$class_name})) {
1485
-            return $this->addons->{$class_name};
1486
-        } else {
1487
-            return null;
1488
-        }
1489
-    }
1490
-
1491
-
1492
-    /**
1493
-     * removes the addon from the internal cache
1494
-     *
1495
-     * @param string $class_name
1496
-     * @return void
1497
-     */
1498
-    public function removeAddon($class_name)
1499
-    {
1500
-        $class_name = str_replace('\\', '_', $class_name);
1501
-        $this->addons->remove($class_name);
1502
-    }
1503
-
1504
-
1505
-    /**
1506
-     * Gets the addon by its name/slug (not classname. For that, just
1507
-     * use the get_addon() method above
1508
-     *
1509
-     * @param string $name
1510
-     * @return EE_Addon
1511
-     */
1512
-    public function get_addon_by_name($name)
1513
-    {
1514
-        foreach ($this->addons as $addon) {
1515
-            if ($addon->name() === $name) {
1516
-                return $addon;
1517
-            }
1518
-        }
1519
-        return null;
1520
-    }
1521
-
1522
-
1523
-    /**
1524
-     * Gets an array of all the registered addons, where the keys are their names.
1525
-     * (ie, what each returns for their name() function)
1526
-     * They're already available on EE_Registry::instance()->addons as properties,
1527
-     * where each property's name is the addon's classname,
1528
-     * So if you just want to get the addon by classname,
1529
-     * OR use the get_addon() method above.
1530
-     * PLEASE  NOTE:
1531
-     * addons with Fully Qualified Class Names
1532
-     * have had the namespace separators converted to underscores,
1533
-     * so a classname like Fully\Qualified\ClassName
1534
-     * would have been converted to Fully_Qualified_ClassName
1535
-     *
1536
-     * @return EE_Addon[] where the KEYS are the addon's name()
1537
-     */
1538
-    public function get_addons_by_name()
1539
-    {
1540
-        $addons = array();
1541
-        foreach ($this->addons as $addon) {
1542
-            $addons[ $addon->name() ] = $addon;
1543
-        }
1544
-        return $addons;
1545
-    }
1546
-
1547
-
1548
-    /**
1549
-     * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1550
-     * a stale copy of it around
1551
-     *
1552
-     * @param string $model_name
1553
-     * @return \EEM_Base
1554
-     * @throws \EE_Error
1555
-     */
1556
-    public function reset_model($model_name)
1557
-    {
1558
-        $model_class_name = strpos($model_name, 'EEM_') !== 0
1559
-            ? "EEM_{$model_name}"
1560
-            : $model_name;
1561
-        if (! $this->LIB->has($model_class_name)) {
1562
-            return null;
1563
-        }
1564
-        $model = $this->LIB->get($model_class_name);
1565
-        if (! $model instanceof EEM_Base) {
1566
-            return null;
1567
-        }
1568
-        // get that model reset it and make sure we nuke the old reference to it
1569
-        if ($model instanceof $model_class_name && is_callable([$model_class_name, 'reset'])) {
1570
-            $this->LIB->remove($model_class_name);
1571
-            $this->LIB->add($model_class_name, $model->reset());
1572
-        } else {
1573
-            throw new EE_Error(
1574
-                sprintf(
1575
-                    esc_html__('Model %s does not have a method "reset"', 'event_espresso'),
1576
-                    $model_name
1577
-                )
1578
-            );
1579
-        }
1580
-        return $model;
1581
-    }
1582
-
1583
-
1584
-    /**
1585
-     * Resets the registry.
1586
-     * The criteria for what gets reset is based on what can be shared between sites on the same request when
1587
-     * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1588
-     * - $_dependency_map
1589
-     * - $_class_abbreviations
1590
-     * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1591
-     * - $REQ:  Still on the same request so no need to change.
1592
-     * - $CAP: There is no site specific state in the EE_Capability class.
1593
-     * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1594
-     * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1595
-     * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1596
-     *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1597
-     *             switch or on the restore.
1598
-     * - $modules
1599
-     * - $shortcodes
1600
-     * - $widgets
1601
-     *
1602
-     * @param boolean $hard             [deprecated]
1603
-     * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1604
-     *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1605
-     *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1606
-     * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1607
-     *                                  client
1608
-     *                                  code instead can just change the model context to a different blog id if
1609
-     *                                  necessary
1610
-     * @return EE_Registry
1611
-     * @throws InvalidInterfaceException
1612
-     * @throws InvalidDataTypeException
1613
-     * @throws EE_Error
1614
-     * @throws ReflectionException
1615
-     * @throws InvalidArgumentException
1616
-     */
1617
-    public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1618
-    {
1619
-        $instance = self::instance();
1620
-        $instance->_cache_on = true;
1621
-        // reset some "special" classes
1622
-        EEH_Activation::reset();
1623
-        $hard = apply_filters('FHEE__EE_Registry__reset__hard', $hard);
1624
-        $instance->CFG = EE_Config::reset($hard, $reinstantiate);
1625
-        $instance->CART = null;
1626
-        $instance->MRM = null;
1627
-        $instance->AssetsRegistry = LoaderFactory::getLoader()->getShared(
1628
-            'EventEspresso\core\services\assets\Registry'
1629
-        );
1630
-        // messages reset
1631
-        EED_Messages::reset();
1632
-        // handle of objects cached on LIB
1633
-        foreach (array('LIB', 'modules') as $cache) {
1634
-            foreach ($instance->{$cache} as $class_name => $class) {
1635
-                if (self::_reset_and_unset_object($class, $reset_models)) {
1636
-                    unset($instance->{$cache}->{$class_name});
1637
-                }
1638
-            }
1639
-        }
1640
-        return $instance;
1641
-    }
1642
-
1643
-
1644
-    /**
1645
-     * if passed object implements ResettableInterface, then call it's reset() method
1646
-     * if passed object implements InterminableInterface, then return false,
1647
-     * to indicate that it should NOT be cleared from the Registry cache
1648
-     *
1649
-     * @param      $object
1650
-     * @param bool $reset_models
1651
-     * @return bool returns true if cached object should be unset
1652
-     */
1653
-    private static function _reset_and_unset_object($object, $reset_models)
1654
-    {
1655
-        if (! is_object($object)) {
1656
-            // don't unset anything that's not an object
1657
-            return false;
1658
-        }
1659
-        if ($object instanceof EED_Module) {
1660
-            $object::reset();
1661
-            // don't unset modules
1662
-            return false;
1663
-        }
1664
-        if ($object instanceof ResettableInterface) {
1665
-            if ($object instanceof EEM_Base) {
1666
-                if ($reset_models) {
1667
-                    $object->reset();
1668
-                    return true;
1669
-                }
1670
-                return false;
1671
-            }
1672
-            $object->reset();
1673
-            return true;
1674
-        }
1675
-        if (! $object instanceof InterminableInterface) {
1676
-            return true;
1677
-        }
1678
-        return false;
1679
-    }
1680
-
1681
-
1682
-    /**
1683
-     * Gets all the custom post type models defined
1684
-     *
1685
-     * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1686
-     */
1687
-    public function cpt_models()
1688
-    {
1689
-        $cpt_models = array();
1690
-        foreach ($this->non_abstract_db_models as $short_name => $classname) {
1691
-            if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1692
-                $cpt_models[ $short_name ] = $classname;
1693
-            }
1694
-        }
1695
-        return $cpt_models;
1696
-    }
1697
-
1698
-
1699
-    /**
1700
-     * @return \EE_Config
1701
-     */
1702
-    public static function CFG()
1703
-    {
1704
-        return self::instance()->CFG;
1705
-    }
1706
-
1707
-
1708
-    /**
1709
-     * @deprecated 4.9.62.p
1710
-     * @param string $class_name
1711
-     * @return ReflectionClass
1712
-     * @throws ReflectionException
1713
-     * @throws InvalidDataTypeException
1714
-     */
1715
-    public function get_ReflectionClass($class_name)
1716
-    {
1717
-        return $this->mirror->getReflectionClass($class_name);
1718
-    }
1374
+				$param_class !== null
1375
+				&& $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1376
+			) {
1377
+				$arguments = $this->_resolve_dependency(
1378
+					$class_name,
1379
+					$param_class,
1380
+					$arguments,
1381
+					$index
1382
+				);
1383
+			}
1384
+			if (empty($arguments[ $index ])) {
1385
+				$arguments[ $index ] = $this->mirror->getParameterDefaultValue(
1386
+					$param,
1387
+					$class_name,
1388
+					$index
1389
+				);
1390
+			}
1391
+		}
1392
+		return $arguments;
1393
+	}
1394
+
1395
+
1396
+	/**
1397
+	 * @param string $class_name
1398
+	 * @param string $param_class
1399
+	 * @param array  $arguments
1400
+	 * @param mixed  $index
1401
+	 * @return array
1402
+	 * @throws InvalidArgumentException
1403
+	 * @throws InvalidInterfaceException
1404
+	 * @throws InvalidDataTypeException
1405
+	 */
1406
+	protected function _resolve_dependency($class_name, $param_class, $arguments, $index)
1407
+	{
1408
+		$dependency = null;
1409
+		// should dependency be loaded from cache ?
1410
+		$cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1411
+			$class_name,
1412
+			$param_class
1413
+		);
1414
+		$cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1415
+		// we might have a dependency...
1416
+		// let's MAYBE try and find it in our cache if that's what's been requested
1417
+		$cached_class = $cache_on
1418
+			? $this->_get_cached_class($param_class)
1419
+			: null;
1420
+		// and grab it if it exists
1421
+		if ($cached_class instanceof $param_class) {
1422
+			$dependency = $cached_class;
1423
+		} elseif ($param_class !== $class_name) {
1424
+			// obtain the loader method from the dependency map
1425
+			$loader = $this->_dependency_map->class_loader($param_class);
1426
+			// is loader a custom closure ?
1427
+			if ($loader instanceof Closure) {
1428
+				$dependency = $loader($arguments);
1429
+			} else {
1430
+				// set the cache on property for the recursive loading call
1431
+				$this->_cache_on = $cache_on;
1432
+				// if not, then let's try and load it via the registry
1433
+				if ($loader && method_exists($this, $loader)) {
1434
+					$dependency = $this->{$loader}($param_class);
1435
+				} else {
1436
+					$dependency = LoaderFactory::getLoader()->load(
1437
+						$param_class,
1438
+						array(),
1439
+						$cache_on
1440
+					);
1441
+				}
1442
+			}
1443
+		}
1444
+		// did we successfully find the correct dependency ?
1445
+		if ($dependency instanceof $param_class) {
1446
+			// then let's inject it into the incoming array of arguments at the correct location
1447
+			$arguments[ $index ] = $dependency;
1448
+		}
1449
+		return $arguments;
1450
+	}
1451
+
1452
+
1453
+	/**
1454
+	 * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1455
+	 *
1456
+	 * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1457
+	 *                          in the EE_Dependency_Map::$_class_loaders array,
1458
+	 *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1459
+	 * @param array  $arguments
1460
+	 * @return object
1461
+	 */
1462
+	public static function factory($classname, $arguments = array())
1463
+	{
1464
+		$loader = self::instance()->_dependency_map->class_loader($classname);
1465
+		if ($loader instanceof Closure) {
1466
+			return $loader($arguments);
1467
+		}
1468
+		if (method_exists(self::instance(), $loader)) {
1469
+			return self::instance()->{$loader}($classname, $arguments);
1470
+		}
1471
+		return null;
1472
+	}
1473
+
1474
+
1475
+	/**
1476
+	 * Gets the addon by its class name
1477
+	 *
1478
+	 * @param string $class_name
1479
+	 * @return EE_Addon
1480
+	 */
1481
+	public function getAddon($class_name)
1482
+	{
1483
+		$class_name = str_replace('\\', '_', $class_name);
1484
+		if (isset($this->addons->{$class_name})) {
1485
+			return $this->addons->{$class_name};
1486
+		} else {
1487
+			return null;
1488
+		}
1489
+	}
1490
+
1491
+
1492
+	/**
1493
+	 * removes the addon from the internal cache
1494
+	 *
1495
+	 * @param string $class_name
1496
+	 * @return void
1497
+	 */
1498
+	public function removeAddon($class_name)
1499
+	{
1500
+		$class_name = str_replace('\\', '_', $class_name);
1501
+		$this->addons->remove($class_name);
1502
+	}
1503
+
1504
+
1505
+	/**
1506
+	 * Gets the addon by its name/slug (not classname. For that, just
1507
+	 * use the get_addon() method above
1508
+	 *
1509
+	 * @param string $name
1510
+	 * @return EE_Addon
1511
+	 */
1512
+	public function get_addon_by_name($name)
1513
+	{
1514
+		foreach ($this->addons as $addon) {
1515
+			if ($addon->name() === $name) {
1516
+				return $addon;
1517
+			}
1518
+		}
1519
+		return null;
1520
+	}
1521
+
1522
+
1523
+	/**
1524
+	 * Gets an array of all the registered addons, where the keys are their names.
1525
+	 * (ie, what each returns for their name() function)
1526
+	 * They're already available on EE_Registry::instance()->addons as properties,
1527
+	 * where each property's name is the addon's classname,
1528
+	 * So if you just want to get the addon by classname,
1529
+	 * OR use the get_addon() method above.
1530
+	 * PLEASE  NOTE:
1531
+	 * addons with Fully Qualified Class Names
1532
+	 * have had the namespace separators converted to underscores,
1533
+	 * so a classname like Fully\Qualified\ClassName
1534
+	 * would have been converted to Fully_Qualified_ClassName
1535
+	 *
1536
+	 * @return EE_Addon[] where the KEYS are the addon's name()
1537
+	 */
1538
+	public function get_addons_by_name()
1539
+	{
1540
+		$addons = array();
1541
+		foreach ($this->addons as $addon) {
1542
+			$addons[ $addon->name() ] = $addon;
1543
+		}
1544
+		return $addons;
1545
+	}
1546
+
1547
+
1548
+	/**
1549
+	 * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1550
+	 * a stale copy of it around
1551
+	 *
1552
+	 * @param string $model_name
1553
+	 * @return \EEM_Base
1554
+	 * @throws \EE_Error
1555
+	 */
1556
+	public function reset_model($model_name)
1557
+	{
1558
+		$model_class_name = strpos($model_name, 'EEM_') !== 0
1559
+			? "EEM_{$model_name}"
1560
+			: $model_name;
1561
+		if (! $this->LIB->has($model_class_name)) {
1562
+			return null;
1563
+		}
1564
+		$model = $this->LIB->get($model_class_name);
1565
+		if (! $model instanceof EEM_Base) {
1566
+			return null;
1567
+		}
1568
+		// get that model reset it and make sure we nuke the old reference to it
1569
+		if ($model instanceof $model_class_name && is_callable([$model_class_name, 'reset'])) {
1570
+			$this->LIB->remove($model_class_name);
1571
+			$this->LIB->add($model_class_name, $model->reset());
1572
+		} else {
1573
+			throw new EE_Error(
1574
+				sprintf(
1575
+					esc_html__('Model %s does not have a method "reset"', 'event_espresso'),
1576
+					$model_name
1577
+				)
1578
+			);
1579
+		}
1580
+		return $model;
1581
+	}
1582
+
1583
+
1584
+	/**
1585
+	 * Resets the registry.
1586
+	 * The criteria for what gets reset is based on what can be shared between sites on the same request when
1587
+	 * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1588
+	 * - $_dependency_map
1589
+	 * - $_class_abbreviations
1590
+	 * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1591
+	 * - $REQ:  Still on the same request so no need to change.
1592
+	 * - $CAP: There is no site specific state in the EE_Capability class.
1593
+	 * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1594
+	 * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1595
+	 * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1596
+	 *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1597
+	 *             switch or on the restore.
1598
+	 * - $modules
1599
+	 * - $shortcodes
1600
+	 * - $widgets
1601
+	 *
1602
+	 * @param boolean $hard             [deprecated]
1603
+	 * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1604
+	 *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1605
+	 *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1606
+	 * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1607
+	 *                                  client
1608
+	 *                                  code instead can just change the model context to a different blog id if
1609
+	 *                                  necessary
1610
+	 * @return EE_Registry
1611
+	 * @throws InvalidInterfaceException
1612
+	 * @throws InvalidDataTypeException
1613
+	 * @throws EE_Error
1614
+	 * @throws ReflectionException
1615
+	 * @throws InvalidArgumentException
1616
+	 */
1617
+	public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1618
+	{
1619
+		$instance = self::instance();
1620
+		$instance->_cache_on = true;
1621
+		// reset some "special" classes
1622
+		EEH_Activation::reset();
1623
+		$hard = apply_filters('FHEE__EE_Registry__reset__hard', $hard);
1624
+		$instance->CFG = EE_Config::reset($hard, $reinstantiate);
1625
+		$instance->CART = null;
1626
+		$instance->MRM = null;
1627
+		$instance->AssetsRegistry = LoaderFactory::getLoader()->getShared(
1628
+			'EventEspresso\core\services\assets\Registry'
1629
+		);
1630
+		// messages reset
1631
+		EED_Messages::reset();
1632
+		// handle of objects cached on LIB
1633
+		foreach (array('LIB', 'modules') as $cache) {
1634
+			foreach ($instance->{$cache} as $class_name => $class) {
1635
+				if (self::_reset_and_unset_object($class, $reset_models)) {
1636
+					unset($instance->{$cache}->{$class_name});
1637
+				}
1638
+			}
1639
+		}
1640
+		return $instance;
1641
+	}
1642
+
1643
+
1644
+	/**
1645
+	 * if passed object implements ResettableInterface, then call it's reset() method
1646
+	 * if passed object implements InterminableInterface, then return false,
1647
+	 * to indicate that it should NOT be cleared from the Registry cache
1648
+	 *
1649
+	 * @param      $object
1650
+	 * @param bool $reset_models
1651
+	 * @return bool returns true if cached object should be unset
1652
+	 */
1653
+	private static function _reset_and_unset_object($object, $reset_models)
1654
+	{
1655
+		if (! is_object($object)) {
1656
+			// don't unset anything that's not an object
1657
+			return false;
1658
+		}
1659
+		if ($object instanceof EED_Module) {
1660
+			$object::reset();
1661
+			// don't unset modules
1662
+			return false;
1663
+		}
1664
+		if ($object instanceof ResettableInterface) {
1665
+			if ($object instanceof EEM_Base) {
1666
+				if ($reset_models) {
1667
+					$object->reset();
1668
+					return true;
1669
+				}
1670
+				return false;
1671
+			}
1672
+			$object->reset();
1673
+			return true;
1674
+		}
1675
+		if (! $object instanceof InterminableInterface) {
1676
+			return true;
1677
+		}
1678
+		return false;
1679
+	}
1680
+
1681
+
1682
+	/**
1683
+	 * Gets all the custom post type models defined
1684
+	 *
1685
+	 * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1686
+	 */
1687
+	public function cpt_models()
1688
+	{
1689
+		$cpt_models = array();
1690
+		foreach ($this->non_abstract_db_models as $short_name => $classname) {
1691
+			if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1692
+				$cpt_models[ $short_name ] = $classname;
1693
+			}
1694
+		}
1695
+		return $cpt_models;
1696
+	}
1697
+
1698
+
1699
+	/**
1700
+	 * @return \EE_Config
1701
+	 */
1702
+	public static function CFG()
1703
+	{
1704
+		return self::instance()->CFG;
1705
+	}
1706
+
1707
+
1708
+	/**
1709
+	 * @deprecated 4.9.62.p
1710
+	 * @param string $class_name
1711
+	 * @return ReflectionClass
1712
+	 * @throws ReflectionException
1713
+	 * @throws InvalidDataTypeException
1714
+	 */
1715
+	public function get_ReflectionClass($class_name)
1716
+	{
1717
+		return $this->mirror->getReflectionClass($class_name);
1718
+	}
1719 1719
 }
Please login to merge, or discard this patch.
core/EE_Configurable.core.php 2 patches
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -10,143 +10,143 @@
 block discarded – undo
10 10
 abstract class EE_Configurable extends EE_Base
11 11
 {
12 12
 
13
-    /**
14
-     * @var $_config
15
-     * @type EE_Config_Base
16
-     */
17
-    protected $_config;
18
-
19
-    /**
20
-     * @var $_config_section
21
-     * @type string
22
-     */
23
-    protected $_config_section = '';
24
-
25
-    /**
26
-     * @var $_config_class
27
-     * @type string
28
-     */
29
-    protected $_config_class = '';
30
-
31
-    /**
32
-     * @var $_config_name
33
-     * @type string
34
-     */
35
-    protected $_config_name = '';
36
-
37
-
38
-    /**
39
-     * @param string $config_section
40
-     */
41
-    public function set_config_section($config_section = '')
42
-    {
43
-        $this->_config_section = ! empty($config_section) ? $config_section : 'modules';
44
-    }
45
-
46
-
47
-    /**
48
-     * @return mixed
49
-     */
50
-    public function config_section()
51
-    {
52
-        return $this->_config_section;
53
-    }
54
-
55
-
56
-    /**
57
-     * @param string $config_class
58
-     */
59
-    public function set_config_class($config_class = '')
60
-    {
61
-        $this->_config_class = $config_class;
62
-    }
63
-
64
-
65
-    /**
66
-     * @return mixed
67
-     */
68
-    public function config_class()
69
-    {
70
-        return $this->_config_class;
71
-    }
72
-
73
-
74
-    /**
75
-     * @param mixed $config_name
76
-     */
77
-    public function set_config_name($config_name)
78
-    {
79
-        $this->_config_name = ! empty($config_name) ? $config_name : get_called_class();
80
-    }
81
-
82
-
83
-    /**
84
-     * @return mixed
85
-     */
86
-    public function config_name()
87
-    {
88
-        return $this->_config_name;
89
-    }
90
-
91
-
92
-    /**
93
-     *    set_config
94
-     *    this method integrates directly with EE_Config to set up the config object for this class
95
-     *
96
-     * @access    protected
97
-     * @param    EE_Config_Base $config_obj
98
-     * @return    mixed    EE_Config_Base | NULL
99
-     */
100
-    protected function _set_config(EE_Config_Base $config_obj = null)
101
-    {
102
-        return EE_Config::instance()->set_config(
103
-            $this->config_section(),
104
-            $this->config_name(),
105
-            $this->config_class(),
106
-            $config_obj
107
-        );
108
-    }
109
-
110
-
111
-    /**
112
-     *    _update_config
113
-     *    this method integrates directly with EE_Config to update an existing config object for this class
114
-     *
115
-     * @access    protected
116
-     * @param    EE_Config_Base $config_obj
117
-     * @throws \EE_Error
118
-     * @return    mixed    EE_Config_Base | NULL
119
-     */
120
-    public function _update_config(EE_Config_Base $config_obj = null)
121
-    {
122
-        $config_class = $this->config_class();
123
-        if (! $config_obj instanceof $config_class) {
124
-            throw new EE_Error(
125
-                sprintf(
126
-                    esc_html__('The "%1$s" class is not an instance of %2$s.', 'event_espresso'),
127
-                    print_r($config_obj, true),
128
-                    $config_class
129
-                )
130
-            );
131
-        }
132
-        return EE_Config::instance()->update_config($this->config_section(), $this->config_name(), $config_obj);
133
-    }
134
-
135
-
136
-    /**
137
-     * gets the class's config object
138
-     *
139
-     * @return EE_Config_Base
140
-     */
141
-    public function config()
142
-    {
143
-        if (empty($this->_config)) {
144
-            $this->_config = EE_Config::instance()->get_config(
145
-                $this->config_section(),
146
-                $this->config_name(),
147
-                $this->config_class()
148
-            );
149
-        }
150
-        return $this->_config;
151
-    }
13
+	/**
14
+	 * @var $_config
15
+	 * @type EE_Config_Base
16
+	 */
17
+	protected $_config;
18
+
19
+	/**
20
+	 * @var $_config_section
21
+	 * @type string
22
+	 */
23
+	protected $_config_section = '';
24
+
25
+	/**
26
+	 * @var $_config_class
27
+	 * @type string
28
+	 */
29
+	protected $_config_class = '';
30
+
31
+	/**
32
+	 * @var $_config_name
33
+	 * @type string
34
+	 */
35
+	protected $_config_name = '';
36
+
37
+
38
+	/**
39
+	 * @param string $config_section
40
+	 */
41
+	public function set_config_section($config_section = '')
42
+	{
43
+		$this->_config_section = ! empty($config_section) ? $config_section : 'modules';
44
+	}
45
+
46
+
47
+	/**
48
+	 * @return mixed
49
+	 */
50
+	public function config_section()
51
+	{
52
+		return $this->_config_section;
53
+	}
54
+
55
+
56
+	/**
57
+	 * @param string $config_class
58
+	 */
59
+	public function set_config_class($config_class = '')
60
+	{
61
+		$this->_config_class = $config_class;
62
+	}
63
+
64
+
65
+	/**
66
+	 * @return mixed
67
+	 */
68
+	public function config_class()
69
+	{
70
+		return $this->_config_class;
71
+	}
72
+
73
+
74
+	/**
75
+	 * @param mixed $config_name
76
+	 */
77
+	public function set_config_name($config_name)
78
+	{
79
+		$this->_config_name = ! empty($config_name) ? $config_name : get_called_class();
80
+	}
81
+
82
+
83
+	/**
84
+	 * @return mixed
85
+	 */
86
+	public function config_name()
87
+	{
88
+		return $this->_config_name;
89
+	}
90
+
91
+
92
+	/**
93
+	 *    set_config
94
+	 *    this method integrates directly with EE_Config to set up the config object for this class
95
+	 *
96
+	 * @access    protected
97
+	 * @param    EE_Config_Base $config_obj
98
+	 * @return    mixed    EE_Config_Base | NULL
99
+	 */
100
+	protected function _set_config(EE_Config_Base $config_obj = null)
101
+	{
102
+		return EE_Config::instance()->set_config(
103
+			$this->config_section(),
104
+			$this->config_name(),
105
+			$this->config_class(),
106
+			$config_obj
107
+		);
108
+	}
109
+
110
+
111
+	/**
112
+	 *    _update_config
113
+	 *    this method integrates directly with EE_Config to update an existing config object for this class
114
+	 *
115
+	 * @access    protected
116
+	 * @param    EE_Config_Base $config_obj
117
+	 * @throws \EE_Error
118
+	 * @return    mixed    EE_Config_Base | NULL
119
+	 */
120
+	public function _update_config(EE_Config_Base $config_obj = null)
121
+	{
122
+		$config_class = $this->config_class();
123
+		if (! $config_obj instanceof $config_class) {
124
+			throw new EE_Error(
125
+				sprintf(
126
+					esc_html__('The "%1$s" class is not an instance of %2$s.', 'event_espresso'),
127
+					print_r($config_obj, true),
128
+					$config_class
129
+				)
130
+			);
131
+		}
132
+		return EE_Config::instance()->update_config($this->config_section(), $this->config_name(), $config_obj);
133
+	}
134
+
135
+
136
+	/**
137
+	 * gets the class's config object
138
+	 *
139
+	 * @return EE_Config_Base
140
+	 */
141
+	public function config()
142
+	{
143
+		if (empty($this->_config)) {
144
+			$this->_config = EE_Config::instance()->get_config(
145
+				$this->config_section(),
146
+				$this->config_name(),
147
+				$this->config_class()
148
+			);
149
+		}
150
+		return $this->_config;
151
+	}
152 152
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -120,7 +120,7 @@
 block discarded – undo
120 120
     public function _update_config(EE_Config_Base $config_obj = null)
121 121
     {
122 122
         $config_class = $this->config_class();
123
-        if (! $config_obj instanceof $config_class) {
123
+        if ( ! $config_obj instanceof $config_class) {
124 124
             throw new EE_Error(
125 125
                 sprintf(
126 126
                     esc_html__('The "%1$s" class is not an instance of %2$s.', 'event_espresso'),
Please login to merge, or discard this patch.
core/db_models/EEM_Price.model.php 2 patches
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -10,279 +10,279 @@
 block discarded – undo
10 10
 class EEM_Price extends EEM_Soft_Delete_Base
11 11
 {
12 12
 
13
-    // private instance of the EEM_Price object
14
-    protected static $_instance = null;
15
-
16
-
17
-
18
-    /**
19
-     *      private constructor to prevent direct creation
20
-     *      @Constructor
21
-     *      @access protected
22
-     *      @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any incoming timezone data that gets saved).  Note this just sends the timezone info to the date time model field objects.  Default is NULL (and will be assumed using the set timezone in the 'timezone_string' wp option)
23
-     *      @return EEM_Price
24
-     */
25
-    protected function __construct($timezone)
26
-    {
27
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
28
-        $this->singular_item = esc_html__('Price', 'event_espresso');
29
-        $this->plural_item = esc_html__('Prices', 'event_espresso');
30
-
31
-        $this->_tables = array(
32
-            'Price' => new EE_Primary_Table('esp_price', 'PRC_ID')
33
-        );
34
-        $this->_fields = array(
35
-            'Price' => array(
36
-                'PRC_ID' => new EE_Primary_Key_Int_Field('PRC_ID', 'Price ID'),
37
-                'PRT_ID' => new EE_Foreign_Key_Int_Field('PRT_ID', 'Price type Id', false, null, 'Price_Type'),
38
-                'PRC_amount' => new EE_Money_Field('PRC_amount', 'Price Amount', false, 0),
39
-                'PRC_name' => new EE_Plain_Text_Field('PRC_name', 'Name of Price', false, ''),
40
-                'PRC_desc' => new EE_Post_Content_Field('PRC_desc', 'Price Description', false, ''),
41
-                'PRC_is_default' => new EE_Boolean_Field('PRC_is_default', 'Flag indicating whether price is a default price', false, false),
42
-                'PRC_overrides' => new EE_Integer_Field('PRC_overrides', 'Price ID for a global Price that will be overridden by this Price  ( for replacing default prices )', true, 0),
43
-                'PRC_order' => new EE_Integer_Field('PRC_order', 'Order of Application of Price (lower numbers apply first?)', false, 1),
44
-                'PRC_deleted' => new EE_Trashed_Flag_Field('PRC_deleted', 'Flag Indicating if this has been deleted or not', false, false),
45
-                'PRC_parent' => new EE_Integer_Field('PRC_parent', esc_html__('Indicates what PRC_ID is the parent of this PRC_ID', 'event_espresso'), true, 0),
46
-                'PRC_wp_user' => new EE_WP_User_Field('PRC_wp_user', esc_html__('Price Creator ID', 'event_espresso'), false),
47
-            )
48
-        );
49
-        $this->_model_relations = array(
50
-            'Ticket' => new EE_HABTM_Relation('Ticket_Price'),
51
-            'Price_Type' => new EE_Belongs_To_Relation(),
52
-            'WP_User' => new EE_Belongs_To_Relation(),
53
-        );
54
-        // this model is generally available for reading
55
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public('PRC_is_default', 'Ticket.Datetime.Event');
56
-        // account for default tickets in the caps
57
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
58
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
59
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
60
-        parent::__construct($timezone);
61
-    }
62
-
63
-
64
-
65
-    /**
66
-     *      instantiate a new price object with blank/empty properties
67
-     *
68
-     *      @access     public
69
-     *      @return     mixed       array on success, FALSE on fail
70
-     */
71
-    public function get_new_price()
72
-    {
73
-        return $this->create_default_object();
74
-    }
75
-
76
-
77
-
78
-
79
-
80
-    /**
81
-     *      retrieve  ALL prices from db
82
-     *
83
-     *      @access     public
84
-     *      @return     EE_PRice[]
85
-     */
86
-    public function get_all_prices()
87
-    {
88
-        // retrieve all prices
89
-        return $this->get_all(array('order_by' => array('PRC_amount' => 'ASC')));
90
-    }
91
-
92
-
93
-
94
-    /**
95
-     *        retrieve all active prices for a particular event
96
-     *
97
-     * @access        public
98
-     * @param int $EVT_ID
99
-     * @return array on success
100
-     */
101
-    public function get_all_event_prices($EVT_ID = 0)
102
-    {
103
-        return $this->get_all(array(
104
-            array(
105
-                'EVT_ID' => $EVT_ID,
106
-                'Price_Type.PBT_ID' => array('!=',  EEM_Price_Type::base_type_tax)
107
-            ),
108
-            'order_by' => $this->_order_by_array_for_get_all_method()
109
-        ));
110
-    }
111
-
112
-
113
-    /**
114
-     *      retrieve all active global prices (that are not taxes (PBT_ID=4)) for a particular event
115
-     *
116
-     *      @access     public
117
-     *      @param      boolean         $count  return count
118
-     *      @return         array           on success
119
-     *      @return         boolean     false on fail
120
-     */
121
-    public function get_all_default_prices($count = false)
122
-    {
123
-        $_where = array(
124
-            'Price_Type.PBT_ID' => array('!=',4),
125
-            'PRC_deleted' => 0,
126
-            'PRC_is_default' => 1
127
-        );
128
-        $_query_params = array(
129
-            $_where,
130
-            'order_by' => $this->_order_by_array_for_get_all_method()
131
-        );
132
-        return $count ? $this->count(array($_where)) : $this->get_all($_query_params);
133
-    }
134
-
135
-
136
-
137
-
138
-
139
-
140
-
141
-
142
-
143
-
144
-    /**
145
-     *      retrieve all prices that are taxes
146
-     *
147
-     *      @access     public
148
-     *      @return         array               on success
149
-     *      @return         array top-level keys are the price's order and their values are an array,
150
-     *                      next-level keys are the price's ID, and their values are EE_Price objects
151
-     */
152
-    public function get_all_prices_that_are_taxes()
153
-    {
154
-        $taxes = array();
155
-        $all_taxes = $this->get_all(array(
156
-            array( 'Price_Type.PBT_ID' =>  EEM_Price_Type::base_type_tax ),
157
-            'order_by' => array( 'Price_Type.PRT_order' => 'ASC', 'PRC_order' => 'ASC' )
158
-        ));
159
-        foreach ($all_taxes as $tax) {
160
-            if ($tax instanceof EE_Price) {
161
-                $taxes[ $tax->order() ][ $tax->ID() ] = $tax;
162
-            }
163
-        }
164
-        return $taxes;
165
-    }
166
-
167
-
168
-
169
-
170
-
171
-    /**
172
-     *      retrieve all prices for an ticket plus default global prices, but not taxes
173
-     *
174
-     *      @access     public
175
-     *      @param int $TKT_ID          the id of the event.  If not included then we assume that this is a new ticket.
176
-     *      @return         boolean         false on fail
177
-     */
178
-    public function get_all_ticket_prices_for_admin($TKT_ID = 0)
179
-    {
180
-        $array_of_price_objects = array();
181
-        if (empty($TKT_ID)) {
182
-            // if there is no tkt, get prices with no tkt ID, are global, are not a tax, and are active
183
-            // return that list
184
-            $default_prices = $this->get_all_default_prices();
185
-
186
-            if ($default_prices) {
187
-                foreach ($default_prices as $price) {
188
-                    if ($price instanceof EE_Price) {
189
-                        $array_of_price_objects[ $price->type() ][] = $price;
190
-                    }
191
-                }
192
-                return $array_of_price_objects;
193
-            } else {
194
-                return array();
195
-            }
196
-        } else {
197
-            $ticket_prices = $this->get_all(array(
198
-                array(
199
-                    'TKT_ID' => $TKT_ID,
200
-                    'PRC_deleted' => 0
201
-                    ),
202
-                'order_by' => array('PRC_order' => 'ASC')
203
-            ));
204
-        }
205
-
206
-        if (!empty($ticket_prices)) {
207
-            foreach ($ticket_prices as $price) {
208
-                if ($price instanceof EE_Price) {
209
-                    $array_of_price_objects[ $price->type() ][] = $price;
210
-                }
211
-            }
212
-            return $array_of_price_objects;
213
-        } else {
214
-            return false;
215
-        }
216
-    }
217
-
218
-
219
-
220
-    /**
221
-     *        _sort_event_prices_by_type
222
-     *
223
-     * @access public
224
-     * @param \EE_Price $price_a
225
-     * @param \EE_Price $price_b
226
-     * @return bool false on fail
227
-     */
228
-    public function _sort_event_prices_by_type(EE_Price $price_a, EE_Price $price_b)
229
-    {
230
-        if ($price_a->type_obj()->order() == $price_b->type_obj()->order()) {
231
-            return $this->_sort_event_prices_by_order($price_a, $price_b);
232
-        }
233
-        return $price_a->type_obj()->order() < $price_b->type_obj()->order() ? -1 : 1;
234
-    }
235
-
236
-
237
-
238
-    /**
239
-     *        _sort_event_prices_by_order
240
-     *
241
-     * @access public
242
-     * @param \EE_Price $price_a
243
-     * @param \EE_Price $price_b
244
-     * @return bool false on fail
245
-     */
246
-    public function _sort_event_prices_by_order(EE_Price $price_a, EE_Price $price_b)
247
-    {
248
-        if ($price_a->order() == $price_b->order()) {
249
-            return 0;
250
-        }
251
-        return $price_a->order() < $price_b->order() ? -1 : 1;
252
-    }
253
-
254
-
255
-
256
-    /**
257
-     *      get all prices of a specific type
258
-     *
259
-     *      @access     public
260
-     *      @param      int                 $type - PRT_ID
261
-     *      @return         boolean     false on fail
262
-     */
263
-    public function get_all_prices_that_are_type($type = 0)
264
-    {
265
-        return $this->get_all(array(
266
-            array(
267
-                'PRT_ID' => $type
268
-            ),
269
-            'order_by' => $this->_order_by_array_for_get_all_method()
270
-        ));
271
-    }
272
-
273
-
274
-
275
-    /**
276
-     * Returns an array of the normal 'order_by' query parameter provided to the get_all query.
277
-     * Of course you don't have to use it, but this is the order we usually want to sort prices by
278
-     * @return array which can be used like so: $this->get_all(array(array(...where stuff...),'order_by'=>$this->_order_by_array_for_get_all_method()));
279
-     */
280
-    public function _order_by_array_for_get_all_method()
281
-    {
282
-        return array(
283
-                'PRC_order' => 'ASC',
284
-                'Price_Type.PRT_order' => 'ASC',
285
-                'PRC_ID' => 'ASC'
286
-        );
287
-    }
13
+	// private instance of the EEM_Price object
14
+	protected static $_instance = null;
15
+
16
+
17
+
18
+	/**
19
+	 *      private constructor to prevent direct creation
20
+	 *      @Constructor
21
+	 *      @access protected
22
+	 *      @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any incoming timezone data that gets saved).  Note this just sends the timezone info to the date time model field objects.  Default is NULL (and will be assumed using the set timezone in the 'timezone_string' wp option)
23
+	 *      @return EEM_Price
24
+	 */
25
+	protected function __construct($timezone)
26
+	{
27
+		require_once(EE_MODELS . 'EEM_Price_Type.model.php');
28
+		$this->singular_item = esc_html__('Price', 'event_espresso');
29
+		$this->plural_item = esc_html__('Prices', 'event_espresso');
30
+
31
+		$this->_tables = array(
32
+			'Price' => new EE_Primary_Table('esp_price', 'PRC_ID')
33
+		);
34
+		$this->_fields = array(
35
+			'Price' => array(
36
+				'PRC_ID' => new EE_Primary_Key_Int_Field('PRC_ID', 'Price ID'),
37
+				'PRT_ID' => new EE_Foreign_Key_Int_Field('PRT_ID', 'Price type Id', false, null, 'Price_Type'),
38
+				'PRC_amount' => new EE_Money_Field('PRC_amount', 'Price Amount', false, 0),
39
+				'PRC_name' => new EE_Plain_Text_Field('PRC_name', 'Name of Price', false, ''),
40
+				'PRC_desc' => new EE_Post_Content_Field('PRC_desc', 'Price Description', false, ''),
41
+				'PRC_is_default' => new EE_Boolean_Field('PRC_is_default', 'Flag indicating whether price is a default price', false, false),
42
+				'PRC_overrides' => new EE_Integer_Field('PRC_overrides', 'Price ID for a global Price that will be overridden by this Price  ( for replacing default prices )', true, 0),
43
+				'PRC_order' => new EE_Integer_Field('PRC_order', 'Order of Application of Price (lower numbers apply first?)', false, 1),
44
+				'PRC_deleted' => new EE_Trashed_Flag_Field('PRC_deleted', 'Flag Indicating if this has been deleted or not', false, false),
45
+				'PRC_parent' => new EE_Integer_Field('PRC_parent', esc_html__('Indicates what PRC_ID is the parent of this PRC_ID', 'event_espresso'), true, 0),
46
+				'PRC_wp_user' => new EE_WP_User_Field('PRC_wp_user', esc_html__('Price Creator ID', 'event_espresso'), false),
47
+			)
48
+		);
49
+		$this->_model_relations = array(
50
+			'Ticket' => new EE_HABTM_Relation('Ticket_Price'),
51
+			'Price_Type' => new EE_Belongs_To_Relation(),
52
+			'WP_User' => new EE_Belongs_To_Relation(),
53
+		);
54
+		// this model is generally available for reading
55
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public('PRC_is_default', 'Ticket.Datetime.Event');
56
+		// account for default tickets in the caps
57
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
58
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
59
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
60
+		parent::__construct($timezone);
61
+	}
62
+
63
+
64
+
65
+	/**
66
+	 *      instantiate a new price object with blank/empty properties
67
+	 *
68
+	 *      @access     public
69
+	 *      @return     mixed       array on success, FALSE on fail
70
+	 */
71
+	public function get_new_price()
72
+	{
73
+		return $this->create_default_object();
74
+	}
75
+
76
+
77
+
78
+
79
+
80
+	/**
81
+	 *      retrieve  ALL prices from db
82
+	 *
83
+	 *      @access     public
84
+	 *      @return     EE_PRice[]
85
+	 */
86
+	public function get_all_prices()
87
+	{
88
+		// retrieve all prices
89
+		return $this->get_all(array('order_by' => array('PRC_amount' => 'ASC')));
90
+	}
91
+
92
+
93
+
94
+	/**
95
+	 *        retrieve all active prices for a particular event
96
+	 *
97
+	 * @access        public
98
+	 * @param int $EVT_ID
99
+	 * @return array on success
100
+	 */
101
+	public function get_all_event_prices($EVT_ID = 0)
102
+	{
103
+		return $this->get_all(array(
104
+			array(
105
+				'EVT_ID' => $EVT_ID,
106
+				'Price_Type.PBT_ID' => array('!=',  EEM_Price_Type::base_type_tax)
107
+			),
108
+			'order_by' => $this->_order_by_array_for_get_all_method()
109
+		));
110
+	}
111
+
112
+
113
+	/**
114
+	 *      retrieve all active global prices (that are not taxes (PBT_ID=4)) for a particular event
115
+	 *
116
+	 *      @access     public
117
+	 *      @param      boolean         $count  return count
118
+	 *      @return         array           on success
119
+	 *      @return         boolean     false on fail
120
+	 */
121
+	public function get_all_default_prices($count = false)
122
+	{
123
+		$_where = array(
124
+			'Price_Type.PBT_ID' => array('!=',4),
125
+			'PRC_deleted' => 0,
126
+			'PRC_is_default' => 1
127
+		);
128
+		$_query_params = array(
129
+			$_where,
130
+			'order_by' => $this->_order_by_array_for_get_all_method()
131
+		);
132
+		return $count ? $this->count(array($_where)) : $this->get_all($_query_params);
133
+	}
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+	/**
145
+	 *      retrieve all prices that are taxes
146
+	 *
147
+	 *      @access     public
148
+	 *      @return         array               on success
149
+	 *      @return         array top-level keys are the price's order and their values are an array,
150
+	 *                      next-level keys are the price's ID, and their values are EE_Price objects
151
+	 */
152
+	public function get_all_prices_that_are_taxes()
153
+	{
154
+		$taxes = array();
155
+		$all_taxes = $this->get_all(array(
156
+			array( 'Price_Type.PBT_ID' =>  EEM_Price_Type::base_type_tax ),
157
+			'order_by' => array( 'Price_Type.PRT_order' => 'ASC', 'PRC_order' => 'ASC' )
158
+		));
159
+		foreach ($all_taxes as $tax) {
160
+			if ($tax instanceof EE_Price) {
161
+				$taxes[ $tax->order() ][ $tax->ID() ] = $tax;
162
+			}
163
+		}
164
+		return $taxes;
165
+	}
166
+
167
+
168
+
169
+
170
+
171
+	/**
172
+	 *      retrieve all prices for an ticket plus default global prices, but not taxes
173
+	 *
174
+	 *      @access     public
175
+	 *      @param int $TKT_ID          the id of the event.  If not included then we assume that this is a new ticket.
176
+	 *      @return         boolean         false on fail
177
+	 */
178
+	public function get_all_ticket_prices_for_admin($TKT_ID = 0)
179
+	{
180
+		$array_of_price_objects = array();
181
+		if (empty($TKT_ID)) {
182
+			// if there is no tkt, get prices with no tkt ID, are global, are not a tax, and are active
183
+			// return that list
184
+			$default_prices = $this->get_all_default_prices();
185
+
186
+			if ($default_prices) {
187
+				foreach ($default_prices as $price) {
188
+					if ($price instanceof EE_Price) {
189
+						$array_of_price_objects[ $price->type() ][] = $price;
190
+					}
191
+				}
192
+				return $array_of_price_objects;
193
+			} else {
194
+				return array();
195
+			}
196
+		} else {
197
+			$ticket_prices = $this->get_all(array(
198
+				array(
199
+					'TKT_ID' => $TKT_ID,
200
+					'PRC_deleted' => 0
201
+					),
202
+				'order_by' => array('PRC_order' => 'ASC')
203
+			));
204
+		}
205
+
206
+		if (!empty($ticket_prices)) {
207
+			foreach ($ticket_prices as $price) {
208
+				if ($price instanceof EE_Price) {
209
+					$array_of_price_objects[ $price->type() ][] = $price;
210
+				}
211
+			}
212
+			return $array_of_price_objects;
213
+		} else {
214
+			return false;
215
+		}
216
+	}
217
+
218
+
219
+
220
+	/**
221
+	 *        _sort_event_prices_by_type
222
+	 *
223
+	 * @access public
224
+	 * @param \EE_Price $price_a
225
+	 * @param \EE_Price $price_b
226
+	 * @return bool false on fail
227
+	 */
228
+	public function _sort_event_prices_by_type(EE_Price $price_a, EE_Price $price_b)
229
+	{
230
+		if ($price_a->type_obj()->order() == $price_b->type_obj()->order()) {
231
+			return $this->_sort_event_prices_by_order($price_a, $price_b);
232
+		}
233
+		return $price_a->type_obj()->order() < $price_b->type_obj()->order() ? -1 : 1;
234
+	}
235
+
236
+
237
+
238
+	/**
239
+	 *        _sort_event_prices_by_order
240
+	 *
241
+	 * @access public
242
+	 * @param \EE_Price $price_a
243
+	 * @param \EE_Price $price_b
244
+	 * @return bool false on fail
245
+	 */
246
+	public function _sort_event_prices_by_order(EE_Price $price_a, EE_Price $price_b)
247
+	{
248
+		if ($price_a->order() == $price_b->order()) {
249
+			return 0;
250
+		}
251
+		return $price_a->order() < $price_b->order() ? -1 : 1;
252
+	}
253
+
254
+
255
+
256
+	/**
257
+	 *      get all prices of a specific type
258
+	 *
259
+	 *      @access     public
260
+	 *      @param      int                 $type - PRT_ID
261
+	 *      @return         boolean     false on fail
262
+	 */
263
+	public function get_all_prices_that_are_type($type = 0)
264
+	{
265
+		return $this->get_all(array(
266
+			array(
267
+				'PRT_ID' => $type
268
+			),
269
+			'order_by' => $this->_order_by_array_for_get_all_method()
270
+		));
271
+	}
272
+
273
+
274
+
275
+	/**
276
+	 * Returns an array of the normal 'order_by' query parameter provided to the get_all query.
277
+	 * Of course you don't have to use it, but this is the order we usually want to sort prices by
278
+	 * @return array which can be used like so: $this->get_all(array(array(...where stuff...),'order_by'=>$this->_order_by_array_for_get_all_method()));
279
+	 */
280
+	public function _order_by_array_for_get_all_method()
281
+	{
282
+		return array(
283
+				'PRC_order' => 'ASC',
284
+				'Price_Type.PRT_order' => 'ASC',
285
+				'PRC_ID' => 'ASC'
286
+		);
287
+	}
288 288
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
      */
25 25
     protected function __construct($timezone)
26 26
     {
27
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
27
+        require_once(EE_MODELS.'EEM_Price_Type.model.php');
28 28
         $this->singular_item = esc_html__('Price', 'event_espresso');
29 29
         $this->plural_item = esc_html__('Prices', 'event_espresso');
30 30
 
@@ -52,11 +52,11 @@  discard block
 block discarded – undo
52 52
             'WP_User' => new EE_Belongs_To_Relation(),
53 53
         );
54 54
         // this model is generally available for reading
55
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Default_Public('PRC_is_default', 'Ticket.Datetime.Event');
55
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Default_Public('PRC_is_default', 'Ticket.Datetime.Event');
56 56
         // account for default tickets in the caps
57
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
58
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
59
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
57
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
58
+        $this->_cap_restriction_generators[EEM_Base::caps_edit] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
59
+        $this->_cap_restriction_generators[EEM_Base::caps_delete] = new EE_Restriction_Generator_Default_Protected('PRC_is_default', 'Ticket.Datetime.Event');
60 60
         parent::__construct($timezone);
61 61
     }
62 62
 
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
         return $this->get_all(array(
104 104
             array(
105 105
                 'EVT_ID' => $EVT_ID,
106
-                'Price_Type.PBT_ID' => array('!=',  EEM_Price_Type::base_type_tax)
106
+                'Price_Type.PBT_ID' => array('!=', EEM_Price_Type::base_type_tax)
107 107
             ),
108 108
             'order_by' => $this->_order_by_array_for_get_all_method()
109 109
         ));
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
     public function get_all_default_prices($count = false)
122 122
     {
123 123
         $_where = array(
124
-            'Price_Type.PBT_ID' => array('!=',4),
124
+            'Price_Type.PBT_ID' => array('!=', 4),
125 125
             'PRC_deleted' => 0,
126 126
             'PRC_is_default' => 1
127 127
         );
@@ -153,12 +153,12 @@  discard block
 block discarded – undo
153 153
     {
154 154
         $taxes = array();
155 155
         $all_taxes = $this->get_all(array(
156
-            array( 'Price_Type.PBT_ID' =>  EEM_Price_Type::base_type_tax ),
157
-            'order_by' => array( 'Price_Type.PRT_order' => 'ASC', 'PRC_order' => 'ASC' )
156
+            array('Price_Type.PBT_ID' =>  EEM_Price_Type::base_type_tax),
157
+            'order_by' => array('Price_Type.PRT_order' => 'ASC', 'PRC_order' => 'ASC')
158 158
         ));
159 159
         foreach ($all_taxes as $tax) {
160 160
             if ($tax instanceof EE_Price) {
161
-                $taxes[ $tax->order() ][ $tax->ID() ] = $tax;
161
+                $taxes[$tax->order()][$tax->ID()] = $tax;
162 162
             }
163 163
         }
164 164
         return $taxes;
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
             if ($default_prices) {
187 187
                 foreach ($default_prices as $price) {
188 188
                     if ($price instanceof EE_Price) {
189
-                        $array_of_price_objects[ $price->type() ][] = $price;
189
+                        $array_of_price_objects[$price->type()][] = $price;
190 190
                     }
191 191
                 }
192 192
                 return $array_of_price_objects;
@@ -203,10 +203,10 @@  discard block
 block discarded – undo
203 203
             ));
204 204
         }
205 205
 
206
-        if (!empty($ticket_prices)) {
206
+        if ( ! empty($ticket_prices)) {
207 207
             foreach ($ticket_prices as $price) {
208 208
                 if ($price instanceof EE_Price) {
209
-                    $array_of_price_objects[ $price->type() ][] = $price;
209
+                    $array_of_price_objects[$price->type()][] = $price;
210 210
                 }
211 211
             }
212 212
             return $array_of_price_objects;
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Spacing   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
     protected function __construct($timezone = null)
556 556
     {
557 557
         // check that the model has not been loaded too soon
558
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
559 559
             throw new EE_Error(
560 560
                 sprintf(
561 561
                     esc_html__(
@@ -578,7 +578,7 @@  discard block
 block discarded – undo
578 578
          *
579 579
          * @var EE_Table_Base[] $_tables
580 580
          */
581
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
582 582
         foreach ($this->_tables as $table_alias => $table_obj) {
583 583
             /** @var $table_obj EE_Table_Base */
584 584
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -593,10 +593,10 @@  discard block
 block discarded – undo
593 593
          *
594 594
          * @param EE_Model_Field_Base[] $_fields
595 595
          */
596
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
597 597
         $this->_invalidate_field_caches();
598 598
         foreach ($this->_fields as $table_alias => $fields_for_table) {
599
-            if (! array_key_exists($table_alias, $this->_tables)) {
599
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
600 600
                 throw new EE_Error(sprintf(esc_html__(
601 601
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
602 602
                     'event_espresso'
@@ -627,7 +627,7 @@  discard block
 block discarded – undo
627 627
          * @param EE_Model_Relation_Base[] $_model_relations
628 628
          */
629 629
         $this->_model_relations = (array) apply_filters(
630
-            'FHEE__' . get_class($this) . '__construct__model_relations',
630
+            'FHEE__'.get_class($this).'__construct__model_relations',
631 631
             $this->_model_relations
632 632
         );
633 633
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -640,12 +640,12 @@  discard block
 block discarded – undo
640 640
         }
641 641
         $this->set_timezone($timezone);
642 642
         // finalize default where condition strategy, or set default
643
-        if (! $this->_default_where_conditions_strategy) {
643
+        if ( ! $this->_default_where_conditions_strategy) {
644 644
             // nothing was set during child constructor, so set default
645 645
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646 646
         }
647 647
         $this->_default_where_conditions_strategy->_finalize_construct($this);
648
-        if (! $this->_minimum_where_conditions_strategy) {
648
+        if ( ! $this->_minimum_where_conditions_strategy) {
649 649
             // nothing was set during child constructor, so set default
650 650
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651 651
         }
@@ -658,8 +658,8 @@  discard block
 block discarded – undo
658 658
         // initialize the standard cap restriction generators if none were specified by the child constructor
659 659
         if ($this->_cap_restriction_generators !== false) {
660 660
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
661
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
662
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
663 663
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664 664
                         new EE_Restriction_Generator_Protected(),
665 665
                         $cap_context,
@@ -671,10 +671,10 @@  discard block
 block discarded – undo
671 671
         // if there are cap restriction generators, use them to make the default cap restrictions
672 672
         if ($this->_cap_restriction_generators !== false) {
673 673
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
-                if (! $generator_object) {
674
+                if ( ! $generator_object) {
675 675
                     continue;
676 676
                 }
677
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
678 678
                     throw new EE_Error(
679 679
                         sprintf(
680 680
                             esc_html__(
@@ -687,12 +687,12 @@  discard block
 block discarded – undo
687 687
                     );
688 688
                 }
689 689
                 $action = $this->cap_action_for_context($context);
690
-                if (! $generator_object->construction_finalized()) {
690
+                if ( ! $generator_object->construction_finalized()) {
691 691
                     $generator_object->_construct_finalize($this, $action);
692 692
                 }
693 693
             }
694 694
         }
695
-        do_action('AHEE__' . get_class($this) . '__construct__end');
695
+        do_action('AHEE__'.get_class($this).'__construct__end');
696 696
     }
697 697
 
698 698
 
@@ -739,7 +739,7 @@  discard block
 block discarded – undo
739 739
     public static function instance($timezone = null)
740 740
     {
741 741
         // check if instance of Espresso_model already exists
742
-        if (! static::$_instance instanceof static) {
742
+        if ( ! static::$_instance instanceof static) {
743 743
             // instantiate Espresso_model
744 744
             static::$_instance = new static(
745 745
                 $timezone,
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
             foreach ($r->getDefaultProperties() as $property => $value) {
779 779
                 // don't set instance to null like it was originally,
780 780
                 // but it's static anyways, and we're ignoring static properties (for now at least)
781
-                if (! isset($static_properties[ $property ])) {
781
+                if ( ! isset($static_properties[$property])) {
782 782
                     static::$_instance->{$property} = $value;
783 783
                 }
784 784
             }
@@ -802,7 +802,7 @@  discard block
 block discarded – undo
802 802
      */
803 803
     private static function getLoader()
804 804
     {
805
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
805
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
806 806
             EEM_Base::$loader = LoaderFactory::getLoader();
807 807
         }
808 808
         return EEM_Base::$loader;
@@ -822,7 +822,7 @@  discard block
 block discarded – undo
822 822
      */
823 823
     public function status_array($translated = false)
824 824
     {
825
-        if (! array_key_exists('Status', $this->_model_relations)) {
825
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
826 826
             return array();
827 827
         }
828 828
         $model_name = $this->get_this_model_name();
@@ -830,7 +830,7 @@  discard block
 block discarded – undo
830 830
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831 831
         $status_array = array();
832 832
         foreach ($stati as $status) {
833
-            $status_array[ $status->ID() ] = $status->get('STS_code');
833
+            $status_array[$status->ID()] = $status->get('STS_code');
834 834
         }
835 835
         return $translated
836 836
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -891,7 +891,7 @@  discard block
 block discarded – undo
891 891
     {
892 892
         $wp_user_field_name = $this->wp_user_field_name();
893 893
         if ($wp_user_field_name) {
894
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
894
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
895 895
         }
896 896
         return $query_params;
897 897
     }
@@ -909,17 +909,17 @@  discard block
 block discarded – undo
909 909
     public function wp_user_field_name()
910 910
     {
911 911
         try {
912
-            if (! empty($this->_model_chain_to_wp_user)) {
912
+            if ( ! empty($this->_model_chain_to_wp_user)) {
913 913
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914 914
                 $last_model_name = end($models_to_follow_to_wp_users);
915 915
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
916
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
917 917
             } else {
918 918
                 $model_with_fk_to_wp_users = $this;
919 919
                 $model_chain_to_wp_user = '';
920 920
             }
921 921
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
922
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
923 923
         } catch (EE_Error $e) {
924 924
             return false;
925 925
         }
@@ -996,11 +996,11 @@  discard block
 block discarded – undo
996 996
         if ($this->_custom_selections instanceof CustomSelects) {
997 997
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998 998
             $select_expressions .= $select_expressions
999
-                ? ', ' . $custom_expressions
999
+                ? ', '.$custom_expressions
1000 1000
                 : $custom_expressions;
1001 1001
         }
1002 1002
 
1003
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1003
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1004 1004
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005 1005
     }
1006 1006
 
@@ -1017,7 +1017,7 @@  discard block
 block discarded – undo
1017 1017
      */
1018 1018
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019 1019
     {
1020
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1020
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021 1021
             return null;
1022 1022
         }
1023 1023
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
         if (is_array($columns_to_select)) {
1067 1067
             $select_sql_array = array();
1068 1068
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070 1070
                     throw new EE_Error(
1071 1071
                         sprintf(
1072 1072
                             esc_html__(
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
                         )
1079 1079
                     );
1080 1080
                 }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1081
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082 1082
                     throw new EE_Error(
1083 1083
                         sprintf(
1084 1084
                             esc_html__(
@@ -1157,12 +1157,12 @@  discard block
 block discarded – undo
1157 1157
      */
1158 1158
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159 1159
     {
1160
-        if (! isset($query_params[0])) {
1160
+        if ( ! isset($query_params[0])) {
1161 1161
             $query_params[0] = array();
1162 1162
         }
1163 1163
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1164 1164
         if ($conditions_from_id === null) {
1165
-            $query_params[0][ $this->primary_key_name() ] = $id;
1165
+            $query_params[0][$this->primary_key_name()] = $id;
1166 1166
         } else {
1167 1167
             // no primary key, so the $id must be from the get_index_primary_key_string()
1168 1168
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
      */
1183 1183
     public function get_one($query_params = array())
1184 1184
     {
1185
-        if (! is_array($query_params)) {
1185
+        if ( ! is_array($query_params)) {
1186 1186
             EE_Error::doing_it_wrong(
1187 1187
                 'EEM_Base::get_one',
1188 1188
                 sprintf(
@@ -1380,7 +1380,7 @@  discard block
 block discarded – undo
1380 1380
                 return array();
1381 1381
             }
1382 1382
         }
1383
-        if (! is_array($query_params)) {
1383
+        if ( ! is_array($query_params)) {
1384 1384
             EE_Error::doing_it_wrong(
1385 1385
                 'EEM_Base::_get_consecutive',
1386 1386
                 sprintf(
@@ -1392,7 +1392,7 @@  discard block
 block discarded – undo
1392 1392
             $query_params = array();
1393 1393
         }
1394 1394
         // let's add the where query param for consecutive look up.
1395
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1395
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1396 1396
         $query_params['limit'] = $limit;
1397 1397
         // set direction
1398 1398
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1473,7 +1473,7 @@  discard block
 block discarded – undo
1473 1473
     {
1474 1474
         $field_settings = $this->field_settings_for($field_name);
1475 1475
         // if not a valid EE_Datetime_Field then throw error
1476
-        if (! $field_settings instanceof EE_Datetime_Field) {
1476
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1477 1477
             throw new EE_Error(sprintf(esc_html__(
1478 1478
                 '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.',
1479 1479
                 'event_espresso'
@@ -1622,7 +1622,7 @@  discard block
 block discarded – undo
1622 1622
      */
1623 1623
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624 1624
     {
1625
-        if (! is_array($query_params)) {
1625
+        if ( ! is_array($query_params)) {
1626 1626
             EE_Error::doing_it_wrong(
1627 1627
                 'EEM_Base::update',
1628 1628
                 sprintf(
@@ -1670,7 +1670,7 @@  discard block
 block discarded – undo
1670 1670
             $wpdb_result = (array) $wpdb_result;
1671 1671
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672 1672
             if ($this->has_primary_key_field()) {
1673
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1673
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1674 1674
             } else {
1675 1675
                 // 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)
1676 1676
                 $main_table_pk_value = null;
@@ -1686,7 +1686,7 @@  discard block
 block discarded – undo
1686 1686
                     // in this table, right? so insert a row in the current table, using any fields available
1687 1687
                     if (
1688 1688
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
-                           && $wpdb_result[ $this_table_pk_column ])
1689
+                           && $wpdb_result[$this_table_pk_column])
1690 1690
                     ) {
1691 1691
                         $success = $this->_insert_into_specific_table(
1692 1692
                             $table_obj,
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
                             $main_table_pk_value
1695 1695
                         );
1696 1696
                         // if we died here, report the error
1697
-                        if (! $success) {
1697
+                        if ( ! $success) {
1698 1698
                             return false;
1699 1699
                         }
1700 1700
                     }
@@ -1722,10 +1722,10 @@  discard block
 block discarded – undo
1722 1722
                 $model_objs_affected_ids = array();
1723 1723
                 foreach ($models_affected_key_columns as $row) {
1724 1724
                     $combined_index_key = $this->get_index_primary_key_string($row);
1725
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1725
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1726 1726
                 }
1727 1727
             }
1728
-            if (! $model_objs_affected_ids) {
1728
+            if ( ! $model_objs_affected_ids) {
1729 1729
                 // wait wait wait- if nothing was affected let's stop here
1730 1730
                 return 0;
1731 1731
             }
@@ -1752,7 +1752,7 @@  discard block
 block discarded – undo
1752 1752
                . $model_query_info->get_full_join_sql()
1753 1753
                . " SET "
1754 1754
                . $this->_construct_update_sql($fields_n_values)
1755
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1755
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756 1756
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757 1757
         /**
1758 1758
          * Action called after a model update call has been made.
@@ -1763,7 +1763,7 @@  discard block
 block discarded – undo
1763 1763
          * @param int      $rows_affected
1764 1764
          */
1765 1765
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
-        return $rows_affected;// how many supposedly got updated
1766
+        return $rows_affected; // how many supposedly got updated
1767 1767
     }
1768 1768
 
1769 1769
 
@@ -1791,7 +1791,7 @@  discard block
 block discarded – undo
1791 1791
         }
1792 1792
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1793 1793
         $select_expressions = $field->get_qualified_column();
1794
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1794
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1795 1795
         return $this->_do_wpdb_query('get_col', array($SQL));
1796 1796
     }
1797 1797
 
@@ -1809,7 +1809,7 @@  discard block
 block discarded – undo
1809 1809
     {
1810 1810
         $query_params['limit'] = 1;
1811 1811
         $col = $this->get_col($query_params, $field_to_select);
1812
-        if (! empty($col)) {
1812
+        if ( ! empty($col)) {
1813 1813
             return reset($col);
1814 1814
         }
1815 1815
         return null;
@@ -1840,7 +1840,7 @@  discard block
 block discarded – undo
1840 1840
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1841 1841
             $value_sql = $prepared_value === null ? 'NULL'
1842 1842
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1843
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1843
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1844 1844
         }
1845 1845
         return implode(",", $cols_n_values);
1846 1846
     }
@@ -1984,12 +1984,12 @@  discard block
 block discarded – undo
1984 1984
         if (
1985 1985
             $this->has_primary_key_field()
1986 1986
             && $rows_deleted !== false
1987
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1987
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1988 1988
         ) {
1989
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1989
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1990 1990
             foreach ($ids_for_removal as $id) {
1991
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1992
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1991
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1992
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1993 1993
                 }
1994 1994
             }
1995 1995
 
@@ -2026,7 +2026,7 @@  discard block
 block discarded – undo
2026 2026
          * @param int      $rows_deleted
2027 2027
          */
2028 2028
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
-        return $rows_deleted;// how many supposedly got deleted
2029
+        return $rows_deleted; // how many supposedly got deleted
2030 2030
     }
2031 2031
 
2032 2032
 
@@ -2120,15 +2120,15 @@  discard block
 block discarded – undo
2120 2120
                 if (
2121 2121
                     $allow_blocking
2122 2122
                     && $this->delete_is_blocked_by_related_models(
2123
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2123
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2124 2124
                     )
2125 2125
                 ) {
2126 2126
                     continue;
2127 2127
                 }
2128 2128
                 // primary table deletes
2129
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2130
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2131
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2129
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2130
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2131
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2132 2132
                 }
2133 2133
             }
2134 2134
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2137,8 +2137,8 @@  discard block
 block discarded – undo
2137 2137
                 $ids_to_delete_indexed_by_column_for_row = array();
2138 2138
                 foreach ($fields as $cpk_field) {
2139 2139
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2140
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2141
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2140
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2141
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2142 2142
                     }
2143 2143
                 }
2144 2144
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2176,7 +2176,7 @@  discard block
 block discarded – undo
2176 2176
         } elseif ($this->has_primary_key_field()) {
2177 2177
             $query = array();
2178 2178
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2179
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2179
+                $query[] = $column.' IN'.$this->_construct_in_value($ids, $this->_primary_key_field);
2180 2180
             }
2181 2181
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182 2182
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2184,7 +2184,7 @@  discard block
 block discarded – undo
2184 2184
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185 2185
                 $values_for_each_combined_primary_key_for_a_row = array();
2186 2186
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2187
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2188 2188
                 }
2189 2189
                 $ways_to_identify_a_row[] = '('
2190 2190
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2256,8 +2256,8 @@  discard block
 block discarded – undo
2256 2256
                 $column_to_count = '*';
2257 2257
             }
2258 2258
         }
2259
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2259
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2260
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2261 2261
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2262 2262
     }
2263 2263
 
@@ -2280,7 +2280,7 @@  discard block
 block discarded – undo
2280 2280
             $field_obj = $this->get_primary_key_field();
2281 2281
         }
2282 2282
         $column_to_count = $field_obj->get_qualified_column();
2283
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2283
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2284 2284
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285 2285
         $data_type = $field_obj->get_wpdb_data_type();
2286 2286
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2307,7 +2307,7 @@  discard block
 block discarded – undo
2307 2307
         // if we're in maintenance mode level 2, DON'T run any queries
2308 2308
         // because level 2 indicates the database needs updating and
2309 2309
         // is probably out of sync with the code
2310
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2310
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2311 2311
             throw new EE_Error(sprintf(esc_html__(
2312 2312
                 "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.",
2313 2313
                 "event_espresso"
@@ -2315,7 +2315,7 @@  discard block
 block discarded – undo
2315 2315
         }
2316 2316
         /** @type WPDB $wpdb */
2317 2317
         global $wpdb;
2318
-        if (! method_exists($wpdb, $wpdb_method)) {
2318
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2319 2319
             throw new EE_Error(sprintf(esc_html__(
2320 2320
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2321 2321
                 'event_espresso'
@@ -2329,7 +2329,7 @@  discard block
 block discarded – undo
2329 2329
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2330 2330
         if (WP_DEBUG) {
2331 2331
             $wpdb->show_errors($old_show_errors_value);
2332
-            if (! empty($wpdb->last_error)) {
2332
+            if ( ! empty($wpdb->last_error)) {
2333 2333
                 throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2334 2334
             }
2335 2335
             if ($result === false) {
@@ -2395,7 +2395,7 @@  discard block
 block discarded – undo
2395 2395
                     return $result;
2396 2396
                     break;
2397 2397
             }
2398
-            if (! empty($error_message)) {
2398
+            if ( ! empty($error_message)) {
2399 2399
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2400 2400
                 trigger_error($error_message);
2401 2401
             }
@@ -2475,11 +2475,11 @@  discard block
 block discarded – undo
2475 2475
      */
2476 2476
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2477 2477
     {
2478
-        return " FROM " . $model_query_info->get_full_join_sql() .
2479
-               $model_query_info->get_where_sql() .
2480
-               $model_query_info->get_group_by_sql() .
2481
-               $model_query_info->get_having_sql() .
2482
-               $model_query_info->get_order_by_sql() .
2478
+        return " FROM ".$model_query_info->get_full_join_sql().
2479
+               $model_query_info->get_where_sql().
2480
+               $model_query_info->get_group_by_sql().
2481
+               $model_query_info->get_having_sql().
2482
+               $model_query_info->get_order_by_sql().
2483 2483
                $model_query_info->get_limit_sql();
2484 2484
     }
2485 2485
 
@@ -2675,12 +2675,12 @@  discard block
 block discarded – undo
2675 2675
         $related_model = $this->get_related_model_obj($model_name);
2676 2676
         // we're just going to use the query params on the related model's normal get_all query,
2677 2677
         // except add a condition to say to match the current mod
2678
-        if (! isset($query_params['default_where_conditions'])) {
2678
+        if ( ! isset($query_params['default_where_conditions'])) {
2679 2679
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2680 2680
         }
2681 2681
         $this_model_name = $this->get_this_model_name();
2682 2682
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2683
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2683
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2684 2684
         return $related_model->count($query_params, $field_to_count, $distinct);
2685 2685
     }
2686 2686
 
@@ -2700,7 +2700,7 @@  discard block
 block discarded – undo
2700 2700
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2701 2701
     {
2702 2702
         $related_model = $this->get_related_model_obj($model_name);
2703
-        if (! is_array($query_params)) {
2703
+        if ( ! is_array($query_params)) {
2704 2704
             EE_Error::doing_it_wrong(
2705 2705
                 'EEM_Base::sum_related',
2706 2706
                 sprintf(
@@ -2713,12 +2713,12 @@  discard block
 block discarded – undo
2713 2713
         }
2714 2714
         // we're just going to use the query params on the related model's normal get_all query,
2715 2715
         // except add a condition to say to match the current mod
2716
-        if (! isset($query_params['default_where_conditions'])) {
2716
+        if ( ! isset($query_params['default_where_conditions'])) {
2717 2717
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2718 2718
         }
2719 2719
         $this_model_name = $this->get_this_model_name();
2720 2720
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2721
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2721
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2722 2722
         return $related_model->sum($query_params, $field_to_sum);
2723 2723
     }
2724 2724
 
@@ -2771,7 +2771,7 @@  discard block
 block discarded – undo
2771 2771
                 $field_with_model_name = $field;
2772 2772
             }
2773 2773
         }
2774
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2774
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2775 2775
             throw new EE_Error(sprintf(
2776 2776
                 esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2777 2777
                 $this->get_this_model_name()
@@ -2908,13 +2908,13 @@  discard block
 block discarded – undo
2908 2908
                 || $this->get_primary_key_field()
2909 2909
                    instanceof
2910 2910
                    EE_Primary_Key_String_Field)
2911
-            && isset($fields_n_values[ $this->primary_key_name() ])
2911
+            && isset($fields_n_values[$this->primary_key_name()])
2912 2912
         ) {
2913
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2913
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2914 2914
         }
2915 2915
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2916 2916
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2917
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2917
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2918 2918
         }
2919 2919
         // if there is nothing to base this search on, then we shouldn't find anything
2920 2920
         if (empty($query_params)) {
@@ -2992,15 +2992,15 @@  discard block
 block discarded – undo
2992 2992
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2993 2993
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
2994 2994
             if ($prepared_value !== null) {
2995
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2995
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2996 2996
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2997 2997
             }
2998 2998
         }
2999 2999
         if ($table instanceof EE_Secondary_Table && $new_id) {
3000 3000
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3001 3001
             // so add the fk to the main table as a column
3002
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3003
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3002
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3003
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
3004 3004
         }
3005 3005
         // insert the new entry
3006 3006
         $result = $this->_do_wpdb_query(
@@ -3017,7 +3017,7 @@  discard block
 block discarded – undo
3017 3017
             }
3018 3018
             // it's not an auto-increment primary key, so
3019 3019
             // it must have been supplied
3020
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3020
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3021 3021
         }
3022 3022
         // we can't return a  primary key because there is none. instead return
3023 3023
         // a unique string indicating this model
@@ -3042,14 +3042,14 @@  discard block
 block discarded – undo
3042 3042
         if (
3043 3043
             ! $field_obj->is_nullable()
3044 3044
             && (
3045
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3046
-                || $fields_n_values[ $field_obj->get_name() ] === null
3045
+                ! isset($fields_n_values[$field_obj->get_name()])
3046
+                || $fields_n_values[$field_obj->get_name()] === null
3047 3047
             )
3048 3048
         ) {
3049
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3049
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3050 3050
         }
3051
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3052
-            ? $fields_n_values[ $field_obj->get_name() ]
3051
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3052
+            ? $fields_n_values[$field_obj->get_name()]
3053 3053
             : null;
3054 3054
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3055 3055
     }
@@ -3150,7 +3150,7 @@  discard block
 block discarded – undo
3150 3150
      */
3151 3151
     public function get_table_obj_by_alias($table_alias = '')
3152 3152
     {
3153
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3153
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3154 3154
     }
3155 3155
 
3156 3156
 
@@ -3165,7 +3165,7 @@  discard block
 block discarded – undo
3165 3165
         $other_tables = array();
3166 3166
         foreach ($this->_tables as $table_alias => $table) {
3167 3167
             if ($table instanceof EE_Secondary_Table) {
3168
-                $other_tables[ $table_alias ] = $table;
3168
+                $other_tables[$table_alias] = $table;
3169 3169
             }
3170 3170
         }
3171 3171
         return $other_tables;
@@ -3181,7 +3181,7 @@  discard block
 block discarded – undo
3181 3181
      */
3182 3182
     public function _get_fields_for_table($table_alias)
3183 3183
     {
3184
-        return $this->_fields[ $table_alias ];
3184
+        return $this->_fields[$table_alias];
3185 3185
     }
3186 3186
 
3187 3187
 
@@ -3210,7 +3210,7 @@  discard block
 block discarded – undo
3210 3210
                     $query_info_carrier,
3211 3211
                     'group_by'
3212 3212
                 );
3213
-            } elseif (! empty($query_params['group_by'])) {
3213
+            } elseif ( ! empty($query_params['group_by'])) {
3214 3214
                 $this->_extract_related_model_info_from_query_param(
3215 3215
                     $query_params['group_by'],
3216 3216
                     $query_info_carrier,
@@ -3232,7 +3232,7 @@  discard block
 block discarded – undo
3232 3232
                     $query_info_carrier,
3233 3233
                     'order_by'
3234 3234
                 );
3235
-            } elseif (! empty($query_params['order_by'])) {
3235
+            } elseif ( ! empty($query_params['order_by'])) {
3236 3236
                 $this->_extract_related_model_info_from_query_param(
3237 3237
                     $query_params['order_by'],
3238 3238
                     $query_info_carrier,
@@ -3267,7 +3267,7 @@  discard block
 block discarded – undo
3267 3267
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3268 3268
         $query_param_type
3269 3269
     ) {
3270
-        if (! empty($sub_query_params)) {
3270
+        if ( ! empty($sub_query_params)) {
3271 3271
             $sub_query_params = (array) $sub_query_params;
3272 3272
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3273 3273
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3282,7 +3282,7 @@  discard block
 block discarded – undo
3282 3282
                 // of array('Registration.TXN_ID'=>23)
3283 3283
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284 3284
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
-                    if (! is_array($possibly_array_of_params)) {
3285
+                    if ( ! is_array($possibly_array_of_params)) {
3286 3286
                         throw new EE_Error(sprintf(
3287 3287
                             esc_html__(
3288 3288
                                 "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'))",
@@ -3306,7 +3306,7 @@  discard block
 block discarded – undo
3306 3306
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3307 3307
                     // indicating that $possible_array_of_params[1] is actually a field name,
3308 3308
                     // from which we should extract query parameters!
3309
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3309
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3310 3310
                         throw new EE_Error(sprintf(esc_html__(
3311 3311
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3312 3312
                             "event_espresso"
@@ -3340,8 +3340,8 @@  discard block
 block discarded – undo
3340 3340
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3341 3341
         $query_param_type
3342 3342
     ) {
3343
-        if (! empty($sub_query_params)) {
3344
-            if (! is_array($sub_query_params)) {
3343
+        if ( ! empty($sub_query_params)) {
3344
+            if ( ! is_array($sub_query_params)) {
3345 3345
                 throw new EE_Error(sprintf(
3346 3346
                     esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3347 3347
                     $sub_query_params
@@ -3375,7 +3375,7 @@  discard block
 block discarded – undo
3375 3375
      */
3376 3376
     public function _create_model_query_info_carrier($query_params)
3377 3377
     {
3378
-        if (! is_array($query_params)) {
3378
+        if ( ! is_array($query_params)) {
3379 3379
             EE_Error::doing_it_wrong(
3380 3380
                 'EEM_Base::_create_model_query_info_carrier',
3381 3381
                 sprintf(
@@ -3408,7 +3408,7 @@  discard block
 block discarded – undo
3408 3408
             // only include if related to a cpt where no password has been set
3409 3409
             $query_params[0]['OR*nopassword'] = array(
3410 3410
                 $where_param_key_for_password => '',
3411
-                $where_param_key_for_password . '*' => array('IS_NULL')
3411
+                $where_param_key_for_password.'*' => array('IS_NULL')
3412 3412
             );
3413 3413
         }
3414 3414
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3462,7 +3462,7 @@  discard block
 block discarded – undo
3462 3462
         // set limit
3463 3463
         if (array_key_exists('limit', $query_params)) {
3464 3464
             if (is_array($query_params['limit'])) {
3465
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3465
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3466 3466
                     $e = sprintf(
3467 3467
                         esc_html__(
3468 3468
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3470,12 +3470,12 @@  discard block
 block discarded – undo
3470 3470
                         ),
3471 3471
                         http_build_query($query_params['limit'])
3472 3472
                     );
3473
-                    throw new EE_Error($e . "|" . $e);
3473
+                    throw new EE_Error($e."|".$e);
3474 3474
                 }
3475 3475
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3476
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3477
-            } elseif (! empty($query_params['limit'])) {
3478
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3476
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3477
+            } elseif ( ! empty($query_params['limit'])) {
3478
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3479 3479
             }
3480 3480
         }
3481 3481
         // set order by
@@ -3507,10 +3507,10 @@  discard block
 block discarded – undo
3507 3507
                 $order_array = array();
3508 3508
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3509 3509
                     $order = $this->_extract_order($order);
3510
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3510
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3511 3511
                 }
3512
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3513
-            } elseif (! empty($query_params['order_by'])) {
3512
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3513
+            } elseif ( ! empty($query_params['order_by'])) {
3514 3514
                 $this->_extract_related_model_info_from_query_param(
3515 3515
                     $query_params['order_by'],
3516 3516
                     $query_object,
@@ -3521,7 +3521,7 @@  discard block
 block discarded – undo
3521 3521
                     ? $this->_extract_order($query_params['order'])
3522 3522
                     : 'DESC';
3523 3523
                 $query_object->set_order_by_sql(
3524
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3524
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3525 3525
                 );
3526 3526
             }
3527 3527
         }
@@ -3533,7 +3533,7 @@  discard block
 block discarded – undo
3533 3533
         ) {
3534 3534
             $pk_field = $this->get_primary_key_field();
3535 3535
             $order = $this->_extract_order($query_params['order']);
3536
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3536
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3537 3537
         }
3538 3538
         // set group by
3539 3539
         if (array_key_exists('group_by', $query_params)) {
@@ -3543,10 +3543,10 @@  discard block
 block discarded – undo
3543 3543
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3544 3544
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3545 3545
                 }
3546
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3547
-            } elseif (! empty($query_params['group_by'])) {
3546
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3547
+            } elseif ( ! empty($query_params['group_by'])) {
3548 3548
                 $query_object->set_group_by_sql(
3549
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3549
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3550 3550
                 );
3551 3551
             }
3552 3552
         }
@@ -3556,7 +3556,7 @@  discard block
 block discarded – undo
3556 3556
         }
3557 3557
         // now, just verify they didn't pass anything wack
3558 3558
         foreach ($query_params as $query_key => $query_value) {
3559
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3559
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3560 3560
                 throw new EE_Error(
3561 3561
                     sprintf(
3562 3562
                         esc_html__(
@@ -3664,7 +3664,7 @@  discard block
 block discarded – undo
3664 3664
         $where_query_params = array()
3665 3665
     ) {
3666 3666
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3667
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3667
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3668 3668
             throw new EE_Error(sprintf(
3669 3669
                 esc_html__(
3670 3670
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3796,19 +3796,19 @@  discard block
 block discarded – undo
3796 3796
     ) {
3797 3797
         $null_friendly_where_conditions = array();
3798 3798
         $none_overridden = true;
3799
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3799
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3800 3800
         foreach ($default_where_conditions as $key => $val) {
3801
-            if (isset($provided_where_conditions[ $key ])) {
3801
+            if (isset($provided_where_conditions[$key])) {
3802 3802
                 $none_overridden = false;
3803 3803
             } else {
3804
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3804
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3805 3805
             }
3806 3806
         }
3807 3807
         if ($none_overridden && $default_where_conditions) {
3808 3808
             if ($model->has_primary_key_field()) {
3809
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3809
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3810 3810
                                                                                 . "."
3811
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3811
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3812 3812
             }/*else{
3813 3813
                 //@todo NO PK, use other defaults
3814 3814
             }*/
@@ -3915,7 +3915,7 @@  discard block
 block discarded – undo
3915 3915
             foreach ($tables as $table_obj) {
3916 3916
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3917 3917
                                        . $table_obj->get_fully_qualified_pk_column();
3918
-                if (! in_array($qualified_pk_column, $selects)) {
3918
+                if ( ! in_array($qualified_pk_column, $selects)) {
3919 3919
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3920 3920
                 }
3921 3921
             }
@@ -4067,9 +4067,9 @@  discard block
 block discarded – undo
4067 4067
         $query_parameter_type
4068 4068
     ) {
4069 4069
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4070
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4070
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4071 4071
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4072
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4072
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4073 4073
                 if ($possible_join_string === '') {
4074 4074
                     // nothing left to $query_param
4075 4075
                     // we should actually end in a field name, not a model like this!
@@ -4200,7 +4200,7 @@  discard block
 block discarded – undo
4200 4200
     {
4201 4201
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4202 4202
         if ($SQL) {
4203
-            return " WHERE " . $SQL;
4203
+            return " WHERE ".$SQL;
4204 4204
         }
4205 4205
         return '';
4206 4206
     }
@@ -4219,7 +4219,7 @@  discard block
 block discarded – undo
4219 4219
     {
4220 4220
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4221 4221
         if ($SQL) {
4222
-            return " HAVING " . $SQL;
4222
+            return " HAVING ".$SQL;
4223 4223
         }
4224 4224
         return '';
4225 4225
     }
@@ -4238,7 +4238,7 @@  discard block
 block discarded – undo
4238 4238
     {
4239 4239
         $where_clauses = array();
4240 4240
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4241
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4241
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4242 4242
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4243 4243
                 switch ($query_param) {
4244 4244
                     case 'not':
@@ -4272,7 +4272,7 @@  discard block
 block discarded – undo
4272 4272
             } else {
4273 4273
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4274 4274
                 // if it's not a normal field, maybe it's a custom selection?
4275
-                if (! $field_obj) {
4275
+                if ( ! $field_obj) {
4276 4276
                     if ($this->_custom_selections instanceof CustomSelects) {
4277 4277
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4278 4278
                     } else {
@@ -4283,7 +4283,7 @@  discard block
 block discarded – undo
4283 4283
                     }
4284 4284
                 }
4285 4285
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4286
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4286
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4287 4287
             }
4288 4288
         }
4289 4289
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4306,7 +4306,7 @@  discard block
 block discarded – undo
4306 4306
                 $field->get_model_name(),
4307 4307
                 $query_param
4308 4308
             );
4309
-            return $table_alias_prefix . $field->get_qualified_column();
4309
+            return $table_alias_prefix.$field->get_qualified_column();
4310 4310
         }
4311 4311
         if (
4312 4312
             $this->_custom_selections instanceof CustomSelects
@@ -4366,7 +4366,7 @@  discard block
 block discarded – undo
4366 4366
     {
4367 4367
         if (is_array($op_and_value)) {
4368 4368
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4369
-            if (! $operator) {
4369
+            if ( ! $operator) {
4370 4370
                 $php_array_like_string = array();
4371 4371
                 foreach ($op_and_value as $key => $value) {
4372 4372
                     $php_array_like_string[] = "$key=>$value";
@@ -4388,14 +4388,14 @@  discard block
 block discarded – undo
4388 4388
         }
4389 4389
         // check to see if the value is actually another field
4390 4390
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4391
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4391
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4392 4392
         }
4393 4393
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4394 4394
             // in this case, the value should be an array, or at least a comma-separated list
4395 4395
             // it will need to handle a little differently
4396 4396
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4397 4397
             // note: $cleaned_value has already been run through $wpdb->prepare()
4398
-            return $operator . SP . $cleaned_value;
4398
+            return $operator.SP.$cleaned_value;
4399 4399
         }
4400 4400
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4401 4401
             // the value should be an array with count of two.
@@ -4411,7 +4411,7 @@  discard block
 block discarded – undo
4411 4411
                 );
4412 4412
             }
4413 4413
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4414
-            return $operator . SP . $cleaned_value;
4414
+            return $operator.SP.$cleaned_value;
4415 4415
         }
4416 4416
         if (in_array($operator, $this->valid_null_style_operators())) {
4417 4417
             if ($value !== null) {
@@ -4431,10 +4431,10 @@  discard block
 block discarded – undo
4431 4431
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4432 4432
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4433 4433
             // remove other junk. So just treat it as a string.
4434
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4434
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4435 4435
         }
4436
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4436
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4438 4438
         }
4439 4439
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4440 4440
             throw new EE_Error(
@@ -4448,7 +4448,7 @@  discard block
 block discarded – undo
4448 4448
                 )
4449 4449
             );
4450 4450
         }
4451
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4451
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452 4452
             throw new EE_Error(
4453 4453
                 sprintf(
4454 4454
                     esc_html__(
@@ -4488,7 +4488,7 @@  discard block
 block discarded – undo
4488 4488
         foreach ($values as $value) {
4489 4489
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4490 4490
         }
4491
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4491
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4492 4492
     }
4493 4493
 
4494 4494
 
@@ -4522,11 +4522,11 @@  discard block
 block discarded – undo
4522 4522
         // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4523 4523
         if (empty($prepped)) {
4524 4524
             $all_fields = $this->field_settings();
4525
-            $first_field    = reset($all_fields);
4525
+            $first_field = reset($all_fields);
4526 4526
             $main_table = $this->_get_main_table();
4527 4527
             $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4528 4528
         }
4529
-        return '(' . implode(',', $prepped) . ')';
4529
+        return '('.implode(',', $prepped).')';
4530 4530
     }
4531 4531
 
4532 4532
 
@@ -4547,7 +4547,7 @@  discard block
 block discarded – undo
4547 4547
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4548 4548
             );
4549 4549
         } //$field_obj should really just be a data type
4550
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4550
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4551 4551
             throw new EE_Error(
4552 4552
                 sprintf(
4553 4553
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4580,14 +4580,14 @@  discard block
 block discarded – undo
4580 4580
             ), $query_param_name));
4581 4581
         }
4582 4582
         $number_of_parts = count($query_param_parts);
4583
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4583
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4584 4584
         if ($number_of_parts === 1) {
4585 4585
             $field_name = $last_query_param_part;
4586 4586
             $model_obj = $this;
4587 4587
         } else {// $number_of_parts >= 2
4588 4588
             // the last part is the column name, and there are only 2parts. therefore...
4589 4589
             $field_name = $last_query_param_part;
4590
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4590
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4591 4591
         }
4592 4592
         try {
4593 4593
             return $model_obj->field_settings_for($field_name);
@@ -4609,7 +4609,7 @@  discard block
 block discarded – undo
4609 4609
     public function _get_qualified_column_for_field($field_name)
4610 4610
     {
4611 4611
         $all_fields = $this->field_settings();
4612
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4612
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4613 4613
         if ($field) {
4614 4614
             return $field->get_qualified_column();
4615 4615
         }
@@ -4680,10 +4680,10 @@  discard block
 block discarded – undo
4680 4680
      */
4681 4681
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4682 4682
     {
4683
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4683
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4684 4684
         $qualified_columns = array();
4685 4685
         foreach ($this->field_settings() as $field_name => $field) {
4686
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4686
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4687 4687
         }
4688 4688
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4689 4689
     }
@@ -4707,11 +4707,11 @@  discard block
 block discarded – undo
4707 4707
             if ($table_obj instanceof EE_Primary_Table) {
4708 4708
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4709 4709
                     ? $table_obj->get_select_join_limit($limit)
4710
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4710
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4711 4711
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4712 4712
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4713 4713
                     ? $table_obj->get_select_join_limit_join($limit)
4714
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4714
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4715 4715
             }
4716 4716
         }
4717 4717
         return $SQL;
@@ -4783,7 +4783,7 @@  discard block
 block discarded – undo
4783 4783
         foreach ($this->field_settings() as $field_obj) {
4784 4784
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4785 4785
             /** @var $field_obj EE_Model_Field_Base */
4786
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4786
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4787 4787
         }
4788 4788
         return $data_types;
4789 4789
     }
@@ -4799,14 +4799,14 @@  discard block
 block discarded – undo
4799 4799
      */
4800 4800
     public function get_related_model_obj($model_name)
4801 4801
     {
4802
-        $model_classname = "EEM_" . $model_name;
4803
-        if (! class_exists($model_classname)) {
4802
+        $model_classname = "EEM_".$model_name;
4803
+        if ( ! class_exists($model_classname)) {
4804 4804
             throw new EE_Error(sprintf(esc_html__(
4805 4805
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4806 4806
                 'event_espresso'
4807 4807
             ), $model_name, $model_classname));
4808 4808
         }
4809
-        return call_user_func($model_classname . "::instance");
4809
+        return call_user_func($model_classname."::instance");
4810 4810
     }
4811 4811
 
4812 4812
 
@@ -4835,7 +4835,7 @@  discard block
 block discarded – undo
4835 4835
         $belongs_to_relations = array();
4836 4836
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4837 4837
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4838
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4838
+                $belongs_to_relations[$model_name] = $relation_obj;
4839 4839
             }
4840 4840
         }
4841 4841
         return $belongs_to_relations;
@@ -4853,7 +4853,7 @@  discard block
 block discarded – undo
4853 4853
     public function related_settings_for($relation_name)
4854 4854
     {
4855 4855
         $relatedModels = $this->relation_settings();
4856
-        if (! array_key_exists($relation_name, $relatedModels)) {
4856
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4857 4857
             throw new EE_Error(
4858 4858
                 sprintf(
4859 4859
                     esc_html__(
@@ -4866,7 +4866,7 @@  discard block
 block discarded – undo
4866 4866
                 )
4867 4867
             );
4868 4868
         }
4869
-        return $relatedModels[ $relation_name ];
4869
+        return $relatedModels[$relation_name];
4870 4870
     }
4871 4871
 
4872 4872
 
@@ -4883,14 +4883,14 @@  discard block
 block discarded – undo
4883 4883
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4884 4884
     {
4885 4885
         $fieldSettings = $this->field_settings($include_db_only_fields);
4886
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4886
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4887 4887
             throw new EE_Error(sprintf(
4888 4888
                 esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4889 4889
                 $fieldName,
4890 4890
                 get_class($this)
4891 4891
             ));
4892 4892
         }
4893
-        return $fieldSettings[ $fieldName ];
4893
+        return $fieldSettings[$fieldName];
4894 4894
     }
4895 4895
 
4896 4896
 
@@ -4904,7 +4904,7 @@  discard block
 block discarded – undo
4904 4904
     public function has_field($fieldName)
4905 4905
     {
4906 4906
         $fieldSettings = $this->field_settings(true);
4907
-        if (isset($fieldSettings[ $fieldName ])) {
4907
+        if (isset($fieldSettings[$fieldName])) {
4908 4908
             return true;
4909 4909
         }
4910 4910
         return false;
@@ -4921,7 +4921,7 @@  discard block
 block discarded – undo
4921 4921
     public function has_relation($relation_name)
4922 4922
     {
4923 4923
         $relations = $this->relation_settings();
4924
-        if (isset($relations[ $relation_name ])) {
4924
+        if (isset($relations[$relation_name])) {
4925 4925
             return true;
4926 4926
         }
4927 4927
         return false;
@@ -4959,7 +4959,7 @@  discard block
 block discarded – undo
4959 4959
                     break;
4960 4960
                 }
4961 4961
             }
4962
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4962
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4963 4963
                 throw new EE_Error(sprintf(
4964 4964
                     esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4965 4965
                     get_class($this)
@@ -5020,24 +5020,24 @@  discard block
 block discarded – undo
5020 5020
      */
5021 5021
     public function get_foreign_key_to($model_name)
5022 5022
     {
5023
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5023
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5024 5024
             foreach ($this->field_settings() as $field) {
5025 5025
                 if (
5026 5026
                     $field instanceof EE_Foreign_Key_Field_Base
5027 5027
                     && in_array($model_name, $field->get_model_names_pointed_to())
5028 5028
                 ) {
5029
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5029
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5030 5030
                     break;
5031 5031
                 }
5032 5032
             }
5033
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5033
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5034 5034
                 throw new EE_Error(sprintf(esc_html__(
5035 5035
                     "There is no foreign key field pointing to model %s on model %s",
5036 5036
                     'event_espresso'
5037 5037
                 ), $model_name, get_class($this)));
5038 5038
             }
5039 5039
         }
5040
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5040
+        return $this->_cache_foreign_key_to_fields[$model_name];
5041 5041
     }
5042 5042
 
5043 5043
 
@@ -5053,7 +5053,7 @@  discard block
 block discarded – undo
5053 5053
     public function get_table_for_alias($table_alias)
5054 5054
     {
5055 5055
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5056
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5056
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5057 5057
     }
5058 5058
 
5059 5059
 
@@ -5072,7 +5072,7 @@  discard block
 block discarded – undo
5072 5072
                 $this->_cached_fields = array();
5073 5073
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5074 5074
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5075
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5075
+                        $this->_cached_fields[$field_name] = $field_obj;
5076 5076
                     }
5077 5077
                 }
5078 5078
             }
@@ -5083,8 +5083,8 @@  discard block
 block discarded – undo
5083 5083
             foreach ($this->_fields as $fields_corresponding_to_table) {
5084 5084
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5085 5085
                     /** @var $field_obj EE_Model_Field_Base */
5086
-                    if (! $field_obj->is_db_only_field()) {
5087
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5086
+                    if ( ! $field_obj->is_db_only_field()) {
5087
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5088 5088
                     }
5089 5089
                 }
5090 5090
             }
@@ -5125,12 +5125,12 @@  discard block
 block discarded – undo
5125 5125
                     $primary_key_field->get_qualified_column(),
5126 5126
                     $primary_key_field->get_table_column()
5127 5127
                 );
5128
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5128
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5129 5129
                     continue;
5130 5130
                 }
5131 5131
             }
5132 5132
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5133
-            if (! $classInstance) {
5133
+            if ( ! $classInstance) {
5134 5134
                 throw new EE_Error(
5135 5135
                     sprintf(
5136 5136
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5143,7 +5143,7 @@  discard block
 block discarded – undo
5143 5143
             $classInstance->set_timezone($this->_timezone);
5144 5144
             // make sure if there is any timezone setting present that we set the timezone for the object
5145 5145
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5146
-            $array_of_objects[ $key ] = $classInstance;
5146
+            $array_of_objects[$key] = $classInstance;
5147 5147
             // also, for all the relations of type BelongsTo, see if we can cache
5148 5148
             // those related models
5149 5149
             // (we could do this for other relations too, but if there are conditions
@@ -5187,9 +5187,9 @@  discard block
 block discarded – undo
5187 5187
         $results = array();
5188 5188
         if ($this->_custom_selections instanceof CustomSelects) {
5189 5189
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5190
-                if (isset($db_results_row[ $alias ])) {
5191
-                    $results[ $alias ] = $this->convertValueToDataType(
5192
-                        $db_results_row[ $alias ],
5190
+                if (isset($db_results_row[$alias])) {
5191
+                    $results[$alias] = $this->convertValueToDataType(
5192
+                        $db_results_row[$alias],
5193 5193
                         $this->_custom_selections->getDataTypeForAlias($alias)
5194 5194
                     );
5195 5195
                 }
@@ -5231,7 +5231,7 @@  discard block
 block discarded – undo
5231 5231
         $this_model_fields_and_values = array();
5232 5232
         // setup the row using default values;
5233 5233
         foreach ($this->field_settings() as $field_name => $field_obj) {
5234
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5234
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5235 5235
         }
5236 5236
         $className = $this->_get_class_name();
5237 5237
         $classInstance = EE_Registry::instance()
@@ -5249,20 +5249,20 @@  discard block
 block discarded – undo
5249 5249
      */
5250 5250
     public function instantiate_class_from_array_or_object($cols_n_values)
5251 5251
     {
5252
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5252
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5253 5253
             $cols_n_values = get_object_vars($cols_n_values);
5254 5254
         }
5255 5255
         $primary_key = null;
5256 5256
         // make sure the array only has keys that are fields/columns on this model
5257 5257
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5258
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5259
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5258
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5259
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5260 5260
         }
5261 5261
         $className = $this->_get_class_name();
5262 5262
         // check we actually found results that we can use to build our model object
5263 5263
         // if not, return null
5264 5264
         if ($this->has_primary_key_field()) {
5265
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5265
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5266 5266
                 return null;
5267 5267
             }
5268 5268
         } elseif ($this->unique_indexes()) {
@@ -5274,7 +5274,7 @@  discard block
 block discarded – undo
5274 5274
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5275 5275
         if ($primary_key) {
5276 5276
             $classInstance = $this->get_from_entity_map($primary_key);
5277
-            if (! $classInstance) {
5277
+            if ( ! $classInstance) {
5278 5278
                 $classInstance = EE_Registry::instance()
5279 5279
                                             ->load_class(
5280 5280
                                                 $className,
@@ -5307,8 +5307,8 @@  discard block
 block discarded – undo
5307 5307
      */
5308 5308
     public function get_from_entity_map($id)
5309 5309
     {
5310
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5311
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5310
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5311
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5312 5312
     }
5313 5313
 
5314 5314
 
@@ -5331,7 +5331,7 @@  discard block
 block discarded – undo
5331 5331
     public function add_to_entity_map(EE_Base_Class $object)
5332 5332
     {
5333 5333
         $className = $this->_get_class_name();
5334
-        if (! $object instanceof $className) {
5334
+        if ( ! $object instanceof $className) {
5335 5335
             throw new EE_Error(sprintf(
5336 5336
                 esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5337 5337
                 is_object($object) ? get_class($object) : $object,
@@ -5339,7 +5339,7 @@  discard block
 block discarded – undo
5339 5339
             ));
5340 5340
         }
5341 5341
         /** @var $object EE_Base_Class */
5342
-        if (! $object->ID()) {
5342
+        if ( ! $object->ID()) {
5343 5343
             throw new EE_Error(sprintf(esc_html__(
5344 5344
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5345 5345
                 "event_espresso"
@@ -5350,7 +5350,7 @@  discard block
 block discarded – undo
5350 5350
         if ($classInstance) {
5351 5351
             return $classInstance;
5352 5352
         }
5353
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5353
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5354 5354
         return $object;
5355 5355
     }
5356 5356
 
@@ -5366,11 +5366,11 @@  discard block
 block discarded – undo
5366 5366
     public function clear_entity_map($id = null)
5367 5367
     {
5368 5368
         if (empty($id)) {
5369
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5369
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5370 5370
             return true;
5371 5371
         }
5372
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5373
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5372
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5373
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5374 5374
             return true;
5375 5375
         }
5376 5376
         return false;
@@ -5413,17 +5413,17 @@  discard block
 block discarded – undo
5413 5413
             // there is a primary key on this table and its not set. Use defaults for all its columns
5414 5414
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5415 5415
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5416
-                    if (! $field_obj->is_db_only_field()) {
5416
+                    if ( ! $field_obj->is_db_only_field()) {
5417 5417
                         // prepare field as if its coming from db
5418 5418
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5419
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5419
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5420 5420
                     }
5421 5421
                 }
5422 5422
             } else {
5423 5423
                 // the table's rows existed. Use their values
5424 5424
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5425
-                    if (! $field_obj->is_db_only_field()) {
5426
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5425
+                    if ( ! $field_obj->is_db_only_field()) {
5426
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5427 5427
                             $cols_n_values,
5428 5428
                             $field_obj->get_qualified_column(),
5429 5429
                             $field_obj->get_table_column()
@@ -5450,17 +5450,17 @@  discard block
 block discarded – undo
5450 5450
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5451 5451
         // does the field on the model relate to this column retrieved from the db?
5452 5452
         // or is it a db-only field? (not relating to the model)
5453
-        if (isset($cols_n_values[ $qualified_column ])) {
5454
-            $value = $cols_n_values[ $qualified_column ];
5455
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5456
-            $value = $cols_n_values[ $regular_column ];
5457
-        } elseif (! empty($this->foreign_key_aliases)) {
5453
+        if (isset($cols_n_values[$qualified_column])) {
5454
+            $value = $cols_n_values[$qualified_column];
5455
+        } elseif (isset($cols_n_values[$regular_column])) {
5456
+            $value = $cols_n_values[$regular_column];
5457
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5458 5458
             // no PK?  ok check if there is a foreign key alias set for this table
5459 5459
             // then check if that alias exists in the incoming data
5460 5460
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5461 5461
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5462
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5463
-                    $value = $cols_n_values[ $FK_alias ];
5462
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5463
+                    $value = $cols_n_values[$FK_alias];
5464 5464
                     list($pk_class) = explode('.', $PK_column);
5465 5465
                     $pk_model_name = "EEM_{$pk_class}";
5466 5466
                     /** @var EEM_Base $pk_model */
@@ -5504,7 +5504,7 @@  discard block
 block discarded – undo
5504 5504
                     $obj_in_map->clear_cache($relation_name, null, true);
5505 5505
                 }
5506 5506
             }
5507
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5507
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5508 5508
             return $obj_in_map;
5509 5509
         }
5510 5510
         return $this->get_one_by_ID($id);
@@ -5557,7 +5557,7 @@  discard block
 block discarded – undo
5557 5557
      */
5558 5558
     private function _get_class_name()
5559 5559
     {
5560
-        return "EE_" . $this->get_this_model_name();
5560
+        return "EE_".$this->get_this_model_name();
5561 5561
     }
5562 5562
 
5563 5563
 
@@ -5605,7 +5605,7 @@  discard block
 block discarded – undo
5605 5605
     {
5606 5606
         $className = get_class($this);
5607 5607
         $tagName = "FHEE__{$className}__{$methodName}";
5608
-        if (! has_filter($tagName)) {
5608
+        if ( ! has_filter($tagName)) {
5609 5609
             throw new EE_Error(
5610 5610
                 sprintf(
5611 5611
                     esc_html__(
@@ -5778,7 +5778,7 @@  discard block
 block discarded – undo
5778 5778
         $unique_indexes = array();
5779 5779
         foreach ($this->_indexes as $name => $index) {
5780 5780
             if ($index instanceof EE_Unique_Index) {
5781
-                $unique_indexes [ $name ] = $index;
5781
+                $unique_indexes [$name] = $index;
5782 5782
             }
5783 5783
         }
5784 5784
         return $unique_indexes;
@@ -5845,7 +5845,7 @@  discard block
 block discarded – undo
5845 5845
         $key_vals_in_combined_pk = array();
5846 5846
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5847 5847
         foreach ($key_fields as $key_field_name => $field_obj) {
5848
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5848
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5849 5849
                 return null;
5850 5850
             }
5851 5851
         }
@@ -5866,7 +5866,7 @@  discard block
 block discarded – undo
5866 5866
     {
5867 5867
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5868 5868
         foreach ($keys_it_should_have as $key) {
5869
-            if (! isset($key_vals[ $key ])) {
5869
+            if ( ! isset($key_vals[$key])) {
5870 5870
                 return false;
5871 5871
             }
5872 5872
         }
@@ -5899,8 +5899,8 @@  discard block
 block discarded – undo
5899 5899
         }
5900 5900
         // even copies obviously won't have the same ID, so remove the primary key
5901 5901
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5902
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5903
-            unset($attributes_array[ $this->primary_key_name() ]);
5902
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5903
+            unset($attributes_array[$this->primary_key_name()]);
5904 5904
         }
5905 5905
         if (isset($query_params[0])) {
5906 5906
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5922,7 +5922,7 @@  discard block
 block discarded – undo
5922 5922
      */
5923 5923
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5924 5924
     {
5925
-        if (! is_array($query_params)) {
5925
+        if ( ! is_array($query_params)) {
5926 5926
             EE_Error::doing_it_wrong(
5927 5927
                 'EEM_Base::get_one_copy',
5928 5928
                 sprintf(
@@ -5972,7 +5972,7 @@  discard block
 block discarded – undo
5972 5972
      */
5973 5973
     private function _prepare_operator_for_sql($operator_supplied)
5974 5974
     {
5975
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5975
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5976 5976
             : null;
5977 5977
         if ($sql_operator) {
5978 5978
             return $sql_operator;
@@ -6063,7 +6063,7 @@  discard block
 block discarded – undo
6063 6063
         $objs = $this->get_all($query_params);
6064 6064
         $names = array();
6065 6065
         foreach ($objs as $obj) {
6066
-            $names[ $obj->ID() ] = $obj->name();
6066
+            $names[$obj->ID()] = $obj->name();
6067 6067
         }
6068 6068
         return $names;
6069 6069
     }
@@ -6084,7 +6084,7 @@  discard block
 block discarded – undo
6084 6084
      */
6085 6085
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6086 6086
     {
6087
-        if (! $this->has_primary_key_field()) {
6087
+        if ( ! $this->has_primary_key_field()) {
6088 6088
             if (WP_DEBUG) {
6089 6089
                 EE_Error::add_error(
6090 6090
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6097,7 +6097,7 @@  discard block
 block discarded – undo
6097 6097
         $IDs = array();
6098 6098
         foreach ($model_objects as $model_object) {
6099 6099
             $id = $model_object->ID();
6100
-            if (! $id) {
6100
+            if ( ! $id) {
6101 6101
                 if ($filter_out_empty_ids) {
6102 6102
                     continue;
6103 6103
                 }
@@ -6148,22 +6148,22 @@  discard block
 block discarded – undo
6148 6148
         EEM_Base::verify_is_valid_cap_context($context);
6149 6149
         // check if we ought to run the restriction generator first
6150 6150
         if (
6151
-            isset($this->_cap_restriction_generators[ $context ])
6152
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6153
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6151
+            isset($this->_cap_restriction_generators[$context])
6152
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6153
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6154 6154
         ) {
6155
-            $this->_cap_restrictions[ $context ] = array_merge(
6156
-                $this->_cap_restrictions[ $context ],
6157
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6155
+            $this->_cap_restrictions[$context] = array_merge(
6156
+                $this->_cap_restrictions[$context],
6157
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6158 6158
             );
6159 6159
         }
6160 6160
         // and make sure we've finalized the construction of each restriction
6161
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6161
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6162 6162
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6163 6163
                 $where_conditions_obj->_finalize_construct($this);
6164 6164
             }
6165 6165
         }
6166
-        return $this->_cap_restrictions[ $context ];
6166
+        return $this->_cap_restrictions[$context];
6167 6167
     }
6168 6168
 
6169 6169
 
@@ -6195,9 +6195,9 @@  discard block
 block discarded – undo
6195 6195
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6196 6196
             if (
6197 6197
                 ! EE_Capabilities::instance()
6198
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6198
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6199 6199
             ) {
6200
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6200
+                $missing_caps[$cap] = $restriction_if_no_cap;
6201 6201
             }
6202 6202
         }
6203 6203
         return $missing_caps;
@@ -6232,8 +6232,8 @@  discard block
 block discarded – undo
6232 6232
     public function cap_action_for_context($context)
6233 6233
     {
6234 6234
         $mapping = $this->cap_contexts_to_cap_action_map();
6235
-        if (isset($mapping[ $context ])) {
6236
-            return $mapping[ $context ];
6235
+        if (isset($mapping[$context])) {
6236
+            return $mapping[$context];
6237 6237
         }
6238 6238
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6239 6239
             return $action;
@@ -6351,7 +6351,7 @@  discard block
 block discarded – undo
6351 6351
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6352 6352
             if (
6353 6353
                 $query_param_key === $logic_query_param_key
6354
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6354
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6355 6355
             ) {
6356 6356
                 return true;
6357 6357
             }
@@ -6404,7 +6404,7 @@  discard block
 block discarded – undo
6404 6404
         if ($password_field instanceof EE_Password_Field) {
6405 6405
             $field_names = $password_field->protectedFields();
6406 6406
             foreach ($field_names as $field_name) {
6407
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6407
+                $fields[$field_name] = $this->field_settings_for($field_name);
6408 6408
             }
6409 6409
         }
6410 6410
         return $fields;
@@ -6429,7 +6429,7 @@  discard block
 block discarded – undo
6429 6429
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6430 6430
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6431 6431
         }
6432
-        if (!is_array($model_obj_or_fields_n_values)) {
6432
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6433 6433
             throw new UnexpectedEntityException(
6434 6434
                 $model_obj_or_fields_n_values,
6435 6435
                 'EE_Base_Class',
@@ -6504,7 +6504,7 @@  discard block
 block discarded – undo
6504 6504
                 )
6505 6505
             );
6506 6506
         }
6507
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6507
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6508 6508
     }
6509 6509
 
6510 6510
     /**
Please login to merge, or discard this patch.
Indentation   +6479 added lines, -6479 removed lines patch added patch discarded remove patch
@@ -36,6485 +36,6485 @@
 block discarded – undo
36 36
 abstract class EEM_Base extends EE_Base implements ResettableInterface
37 37
 {
38 38
 
39
-    /**
40
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
41
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
42
-     * They almost always WILL NOT, but it's not necessarily a requirement.
43
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
44
-     *
45
-     * @var boolean
46
-     */
47
-    private $_values_already_prepared_by_model_object = 0;
48
-
49
-    /**
50
-     * when $_values_already_prepared_by_model_object equals this, we assume
51
-     * the data is just like form input that needs to have the model fields'
52
-     * prepare_for_set and prepare_for_use_in_db called on it
53
-     */
54
-    const not_prepared_by_model_object = 0;
55
-
56
-    /**
57
-     * when $_values_already_prepared_by_model_object equals this, we
58
-     * assume this value is coming from a model object and doesn't need to have
59
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
60
-     */
61
-    const prepared_by_model_object = 1;
62
-
63
-    /**
64
-     * when $_values_already_prepared_by_model_object equals this, we assume
65
-     * the values are already to be used in the database (ie no processing is done
66
-     * on them by the model's fields)
67
-     */
68
-    const prepared_for_use_in_db = 2;
69
-
70
-
71
-    protected $singular_item = 'Item';
72
-
73
-    protected $plural_item   = 'Items';
74
-
75
-    /**
76
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
77
-     */
78
-    protected $_tables;
79
-
80
-    /**
81
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
82
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
83
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
84
-     *
85
-     * @var \EE_Model_Field_Base[][] $_fields
86
-     */
87
-    protected $_fields;
88
-
89
-    /**
90
-     * array of different kinds of relations
91
-     *
92
-     * @var \EE_Model_Relation_Base[] $_model_relations
93
-     */
94
-    protected $_model_relations;
95
-
96
-    /**
97
-     * @var \EE_Index[] $_indexes
98
-     */
99
-    protected $_indexes = array();
100
-
101
-    /**
102
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
103
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
104
-     * by setting the same columns as used in these queries in the query yourself.
105
-     *
106
-     * @var EE_Default_Where_Conditions
107
-     */
108
-    protected $_default_where_conditions_strategy;
109
-
110
-    /**
111
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
112
-     * This is particularly useful when you want something between 'none' and 'default'
113
-     *
114
-     * @var EE_Default_Where_Conditions
115
-     */
116
-    protected $_minimum_where_conditions_strategy;
117
-
118
-    /**
119
-     * String describing how to find the "owner" of this model's objects.
120
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
121
-     * But when there isn't, this indicates which related model, or transiently-related model,
122
-     * has the foreign key to the wp_users table.
123
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
124
-     * related to events, and events have a foreign key to wp_users.
125
-     * On EEM_Transaction, this would be 'Transaction.Event'
126
-     *
127
-     * @var string
128
-     */
129
-    protected $_model_chain_to_wp_user = '';
130
-
131
-    /**
132
-     * String describing how to find the model with a password controlling access to this model. This property has the
133
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
134
-     * This value is the path of models to follow to arrive at the model with the password field.
135
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
136
-     * model with a password that should affect reading this on the front-end.
137
-     * Eg this is an empty string for the Event model because it has a password.
138
-     * This is null for the Registration model, because its event's password has no bearing on whether
139
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
140
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
141
-     * should hide tickets for datetimes for events that have a password set.
142
-     * @var string |null
143
-     */
144
-    protected $model_chain_to_password = null;
145
-
146
-    /**
147
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
148
-     * don't need it (particularly CPT models)
149
-     *
150
-     * @var bool
151
-     */
152
-    protected $_ignore_where_strategy = false;
153
-
154
-    /**
155
-     * String used in caps relating to this model. Eg, if the caps relating to this
156
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
157
-     *
158
-     * @var string. If null it hasn't been initialized yet. If false then we
159
-     * have indicated capabilities don't apply to this
160
-     */
161
-    protected $_caps_slug = null;
162
-
163
-    /**
164
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
165
-     * and next-level keys are capability names, and each's value is a
166
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
167
-     * they specify which context to use (ie, frontend, backend, edit or delete)
168
-     * and then each capability in the corresponding sub-array that they're missing
169
-     * adds the where conditions onto the query.
170
-     *
171
-     * @var array
172
-     */
173
-    protected $_cap_restrictions = array(
174
-        self::caps_read       => array(),
175
-        self::caps_read_admin => array(),
176
-        self::caps_edit       => array(),
177
-        self::caps_delete     => array(),
178
-    );
179
-
180
-    /**
181
-     * Array defining which cap restriction generators to use to create default
182
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
183
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
184
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
185
-     * automatically set this to false (not just null).
186
-     *
187
-     * @var EE_Restriction_Generator_Base[]
188
-     */
189
-    protected $_cap_restriction_generators = array();
190
-
191
-    /**
192
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
193
-     */
194
-    const caps_read       = 'read';
195
-
196
-    const caps_read_admin = 'read_admin';
197
-
198
-    const caps_edit       = 'edit';
199
-
200
-    const caps_delete     = 'delete';
201
-
202
-    /**
203
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
204
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
205
-     * maps to 'read' because when looking for relevant permissions we're going to use
206
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
207
-     *
208
-     * @var array
209
-     */
210
-    protected $_cap_contexts_to_cap_action_map = array(
211
-        self::caps_read       => 'read',
212
-        self::caps_read_admin => 'read',
213
-        self::caps_edit       => 'edit',
214
-        self::caps_delete     => 'delete',
215
-    );
216
-
217
-    /**
218
-     * Timezone
219
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
220
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
221
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
222
-     * EE_Datetime_Field data type will have access to it.
223
-     *
224
-     * @var string
225
-     */
226
-    protected $_timezone;
227
-
228
-
229
-    /**
230
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
231
-     * multisite.
232
-     *
233
-     * @var int
234
-     */
235
-    protected static $_model_query_blog_id;
236
-
237
-    /**
238
-     * A copy of _fields, except the array keys are the model names pointed to by
239
-     * the field
240
-     *
241
-     * @var EE_Model_Field_Base[]
242
-     */
243
-    private $_cache_foreign_key_to_fields = array();
244
-
245
-    /**
246
-     * Cached list of all the fields on the model, indexed by their name
247
-     *
248
-     * @var EE_Model_Field_Base[]
249
-     */
250
-    private $_cached_fields = null;
251
-
252
-    /**
253
-     * Cached list of all the fields on the model, except those that are
254
-     * marked as only pertinent to the database
255
-     *
256
-     * @var EE_Model_Field_Base[]
257
-     */
258
-    private $_cached_fields_non_db_only = null;
259
-
260
-    /**
261
-     * A cached reference to the primary key for quick lookup
262
-     *
263
-     * @var EE_Model_Field_Base
264
-     */
265
-    private $_primary_key_field = null;
266
-
267
-    /**
268
-     * Flag indicating whether this model has a primary key or not
269
-     *
270
-     * @var boolean
271
-     */
272
-    protected $_has_primary_key_field = null;
273
-
274
-    /**
275
-     * array in the format:  [ FK alias => full PK ]
276
-     * where keys are local column name aliases for foreign keys
277
-     * and values are the fully qualified column name for the primary key they represent
278
-     *  ex:
279
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
280
-     *
281
-     * @var array $foreign_key_aliases
282
-     */
283
-    protected $foreign_key_aliases = [];
284
-
285
-    /**
286
-     * Whether or not this model is based off a table in WP core only (CPTs should set
287
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
288
-     * This should be true for models that deal with data that should exist independent of EE.
289
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
290
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
291
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
292
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
293
-     * @var boolean
294
-     */
295
-    protected $_wp_core_model = false;
296
-
297
-    /**
298
-     * @var bool stores whether this model has a password field or not.
299
-     * null until initialized by hasPasswordField()
300
-     */
301
-    protected $has_password_field;
302
-
303
-    /**
304
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
305
-     */
306
-    protected $password_field;
307
-
308
-    /**
309
-     *    List of valid operators that can be used for querying.
310
-     * The keys are all operators we'll accept, the values are the real SQL
311
-     * operators used
312
-     *
313
-     * @var array
314
-     */
315
-    protected $_valid_operators = array(
316
-        '='           => '=',
317
-        '<='          => '<=',
318
-        '<'           => '<',
319
-        '>='          => '>=',
320
-        '>'           => '>',
321
-        '!='          => '!=',
322
-        'LIKE'        => 'LIKE',
323
-        'like'        => 'LIKE',
324
-        'NOT_LIKE'    => 'NOT LIKE',
325
-        'not_like'    => 'NOT LIKE',
326
-        'NOT LIKE'    => 'NOT LIKE',
327
-        'not like'    => 'NOT LIKE',
328
-        'IN'          => 'IN',
329
-        'in'          => 'IN',
330
-        'NOT_IN'      => 'NOT IN',
331
-        'not_in'      => 'NOT IN',
332
-        'NOT IN'      => 'NOT IN',
333
-        'not in'      => 'NOT IN',
334
-        'between'     => 'BETWEEN',
335
-        'BETWEEN'     => 'BETWEEN',
336
-        'IS_NOT_NULL' => 'IS NOT NULL',
337
-        'is_not_null' => 'IS NOT NULL',
338
-        'IS NOT NULL' => 'IS NOT NULL',
339
-        'is not null' => 'IS NOT NULL',
340
-        'IS_NULL'     => 'IS NULL',
341
-        'is_null'     => 'IS NULL',
342
-        'IS NULL'     => 'IS NULL',
343
-        'is null'     => 'IS NULL',
344
-        'REGEXP'      => 'REGEXP',
345
-        'regexp'      => 'REGEXP',
346
-        'NOT_REGEXP'  => 'NOT REGEXP',
347
-        'not_regexp'  => 'NOT REGEXP',
348
-        'NOT REGEXP'  => 'NOT REGEXP',
349
-        'not regexp'  => 'NOT REGEXP',
350
-    );
351
-
352
-    /**
353
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
354
-     *
355
-     * @var array
356
-     */
357
-    protected $_in_style_operators = array('IN', 'NOT IN');
358
-
359
-    /**
360
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
361
-     * '12-31-2012'"
362
-     *
363
-     * @var array
364
-     */
365
-    protected $_between_style_operators = array('BETWEEN');
366
-
367
-    /**
368
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
369
-     * @var array
370
-     */
371
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
372
-    /**
373
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
374
-     * on a join table.
375
-     *
376
-     * @var array
377
-     */
378
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
379
-
380
-    /**
381
-     * Allowed values for $query_params['order'] for ordering in queries
382
-     *
383
-     * @var array
384
-     */
385
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
386
-
387
-    /**
388
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
389
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
390
-     *
391
-     * @var array
392
-     */
393
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
394
-
395
-    /**
396
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
397
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
398
-     *
399
-     * @var array
400
-     */
401
-    private $_allowed_query_params = array(
402
-        0,
403
-        'limit',
404
-        'order_by',
405
-        'group_by',
406
-        'having',
407
-        'force_join',
408
-        'order',
409
-        'on_join_limit',
410
-        'default_where_conditions',
411
-        'caps',
412
-        'extra_selects',
413
-        'exclude_protected',
414
-    );
415
-
416
-    /**
417
-     * All the data types that can be used in $wpdb->prepare statements.
418
-     *
419
-     * @var array
420
-     */
421
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
422
-
423
-    /**
424
-     * @var EE_Registry $EE
425
-     */
426
-    protected $EE = null;
427
-
428
-
429
-    /**
430
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
431
-     *
432
-     * @var int
433
-     */
434
-    protected $_show_next_x_db_queries = 0;
435
-
436
-    /**
437
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
438
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
439
-     * WHERE, GROUP_BY, etc.
440
-     *
441
-     * @var CustomSelects
442
-     */
443
-    protected $_custom_selections = array();
444
-
445
-    /**
446
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
447
-     * caches every model object we've fetched from the DB on this request
448
-     *
449
-     * @var array
450
-     */
451
-    protected $_entity_map;
452
-
453
-    /**
454
-     * @var LoaderInterface $loader
455
-     */
456
-    protected static $loader;
457
-
458
-
459
-    /**
460
-     * constant used to show EEM_Base has not yet verified the db on this http request
461
-     */
462
-    const db_verified_none = 0;
463
-
464
-    /**
465
-     * constant used to show EEM_Base has verified the EE core db on this http request,
466
-     * but not the addons' dbs
467
-     */
468
-    const db_verified_core = 1;
469
-
470
-    /**
471
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
472
-     * the EE core db too)
473
-     */
474
-    const db_verified_addons = 2;
475
-
476
-    /**
477
-     * indicates whether an EEM_Base child has already re-verified the DB
478
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
479
-     * looking like EEM_Base::db_verified_*
480
-     *
481
-     * @var int - 0 = none, 1 = core, 2 = addons
482
-     */
483
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
484
-
485
-    /**
486
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
487
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
488
-     *        registrations for non-trashed tickets for non-trashed datetimes)
489
-     */
490
-    const default_where_conditions_all = 'all';
491
-
492
-    /**
493
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
494
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
495
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
496
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
497
-     *        models which share tables with other models, this can return data for the wrong model.
498
-     */
499
-    const default_where_conditions_this_only = 'this_model_only';
500
-
501
-    /**
502
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
503
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
504
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
505
-     */
506
-    const default_where_conditions_others_only = 'other_models_only';
507
-
508
-    /**
509
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
510
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
511
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
512
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
513
-     *        (regardless of whether those events and venues are trashed)
514
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
515
-     *        events.
516
-     */
517
-    const default_where_conditions_minimum_all = 'minimum';
518
-
519
-    /**
520
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
521
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
522
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
523
-     *        not)
524
-     */
525
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
526
-
527
-    /**
528
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
529
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
530
-     *        it's possible it will return table entries for other models. You should use
531
-     *        EEM_Base::default_where_conditions_minimum_all instead.
532
-     */
533
-    const default_where_conditions_none = 'none';
534
-
535
-
536
-
537
-    /**
538
-     * About all child constructors:
539
-     * they should define the _tables, _fields and _model_relations arrays.
540
-     * Should ALWAYS be called after child constructor.
541
-     * In order to make the child constructors to be as simple as possible, this parent constructor
542
-     * finalizes constructing all the object's attributes.
543
-     * Generally, rather than requiring a child to code
544
-     * $this->_tables = array(
545
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
546
-     *        ...);
547
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
548
-     * each EE_Table has a function to set the table's alias after the constructor, using
549
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
550
-     * do something similar.
551
-     *
552
-     * @param null $timezone
553
-     * @throws EE_Error
554
-     */
555
-    protected function __construct($timezone = null)
556
-    {
557
-        // check that the model has not been loaded too soon
558
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
559
-            throw new EE_Error(
560
-                sprintf(
561
-                    esc_html__(
562
-                        '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.',
563
-                        'event_espresso'
564
-                    ),
565
-                    get_class($this)
566
-                )
567
-            );
568
-        }
569
-        /**
570
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
571
-         */
572
-        if (empty(EEM_Base::$_model_query_blog_id)) {
573
-            EEM_Base::set_model_query_blog_id();
574
-        }
575
-        /**
576
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
577
-         * just use EE_Register_Model_Extension
578
-         *
579
-         * @var EE_Table_Base[] $_tables
580
-         */
581
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
582
-        foreach ($this->_tables as $table_alias => $table_obj) {
583
-            /** @var $table_obj EE_Table_Base */
584
-            $table_obj->_construct_finalize_with_alias($table_alias);
585
-            if ($table_obj instanceof EE_Secondary_Table) {
586
-                /** @var $table_obj EE_Secondary_Table */
587
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
588
-            }
589
-        }
590
-        /**
591
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
592
-         * EE_Register_Model_Extension
593
-         *
594
-         * @param EE_Model_Field_Base[] $_fields
595
-         */
596
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
597
-        $this->_invalidate_field_caches();
598
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
599
-            if (! array_key_exists($table_alias, $this->_tables)) {
600
-                throw new EE_Error(sprintf(esc_html__(
601
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
602
-                    'event_espresso'
603
-                ), $table_alias, implode(",", $this->_fields)));
604
-            }
605
-            foreach ($fields_for_table as $field_name => $field_obj) {
606
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
607
-                // primary key field base has a slightly different _construct_finalize
608
-                /** @var $field_obj EE_Model_Field_Base */
609
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
610
-            }
611
-        }
612
-        // everything is related to Extra_Meta
613
-        if (get_class($this) !== 'EEM_Extra_Meta') {
614
-            // make extra meta related to everything, but don't block deleting things just
615
-            // because they have related extra meta info. For now just orphan those extra meta
616
-            // in the future we should automatically delete them
617
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
618
-        }
619
-        // and change logs
620
-        if (get_class($this) !== 'EEM_Change_Log') {
621
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
622
-        }
623
-        /**
624
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
625
-         * EE_Register_Model_Extension
626
-         *
627
-         * @param EE_Model_Relation_Base[] $_model_relations
628
-         */
629
-        $this->_model_relations = (array) apply_filters(
630
-            'FHEE__' . get_class($this) . '__construct__model_relations',
631
-            $this->_model_relations
632
-        );
633
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
634
-            /** @var $relation_obj EE_Model_Relation_Base */
635
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
636
-        }
637
-        foreach ($this->_indexes as $index_name => $index_obj) {
638
-            /** @var $index_obj EE_Index */
639
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
640
-        }
641
-        $this->set_timezone($timezone);
642
-        // finalize default where condition strategy, or set default
643
-        if (! $this->_default_where_conditions_strategy) {
644
-            // nothing was set during child constructor, so set default
645
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646
-        }
647
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
648
-        if (! $this->_minimum_where_conditions_strategy) {
649
-            // nothing was set during child constructor, so set default
650
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651
-        }
652
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
653
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
654
-        // to indicate to NOT set it, set it to the logical default
655
-        if ($this->_caps_slug === null) {
656
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
657
-        }
658
-        // initialize the standard cap restriction generators if none were specified by the child constructor
659
-        if ($this->_cap_restriction_generators !== false) {
660
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
663
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664
-                        new EE_Restriction_Generator_Protected(),
665
-                        $cap_context,
666
-                        $this
667
-                    );
668
-                }
669
-            }
670
-        }
671
-        // if there are cap restriction generators, use them to make the default cap restrictions
672
-        if ($this->_cap_restriction_generators !== false) {
673
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
-                if (! $generator_object) {
675
-                    continue;
676
-                }
677
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
678
-                    throw new EE_Error(
679
-                        sprintf(
680
-                            esc_html__(
681
-                                '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.',
682
-                                'event_espresso'
683
-                            ),
684
-                            $context,
685
-                            $this->get_this_model_name()
686
-                        )
687
-                    );
688
-                }
689
-                $action = $this->cap_action_for_context($context);
690
-                if (! $generator_object->construction_finalized()) {
691
-                    $generator_object->_construct_finalize($this, $action);
692
-                }
693
-            }
694
-        }
695
-        do_action('AHEE__' . get_class($this) . '__construct__end');
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     * Used to set the $_model_query_blog_id static property.
702
-     *
703
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
704
-     *                      value for get_current_blog_id() will be used.
705
-     */
706
-    public static function set_model_query_blog_id($blog_id = 0)
707
-    {
708
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
709
-    }
710
-
711
-
712
-
713
-    /**
714
-     * Returns whatever is set as the internal $model_query_blog_id.
715
-     *
716
-     * @return int
717
-     */
718
-    public static function get_model_query_blog_id()
719
-    {
720
-        return EEM_Base::$_model_query_blog_id;
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * This function is a singleton method used to instantiate the Espresso_model object
727
-     *
728
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
729
-     *                                (and any incoming timezone data that gets saved).
730
-     *                                Note this just sends the timezone info to the date time model field objects.
731
-     *                                Default is NULL
732
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
733
-     * @return static (as in the concrete child class)
734
-     * @throws EE_Error
735
-     * @throws InvalidArgumentException
736
-     * @throws InvalidDataTypeException
737
-     * @throws InvalidInterfaceException
738
-     */
739
-    public static function instance($timezone = null)
740
-    {
741
-        // check if instance of Espresso_model already exists
742
-        if (! static::$_instance instanceof static) {
743
-            // instantiate Espresso_model
744
-            static::$_instance = new static(
745
-                $timezone,
746
-                EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
747
-            );
748
-        }
749
-        // we might have a timezone set, let set_timezone decide what to do with it
750
-        static::$_instance->set_timezone($timezone);
751
-        // Espresso_model object
752
-        return static::$_instance;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * resets the model and returns it
759
-     *
760
-     * @param null | string $timezone
761
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
762
-     * all its properties reset; if it wasn't instantiated, returns null)
763
-     * @throws EE_Error
764
-     * @throws ReflectionException
765
-     * @throws InvalidArgumentException
766
-     * @throws InvalidDataTypeException
767
-     * @throws InvalidInterfaceException
768
-     */
769
-    public static function reset($timezone = null)
770
-    {
771
-        if (static::$_instance instanceof EEM_Base) {
772
-            // let's try to NOT swap out the current instance for a new one
773
-            // because if someone has a reference to it, we can't remove their reference
774
-            // so it's best to keep using the same reference, but change the original object
775
-            // reset all its properties to their original values as defined in the class
776
-            $r = new ReflectionClass(get_class(static::$_instance));
777
-            $static_properties = $r->getStaticProperties();
778
-            foreach ($r->getDefaultProperties() as $property => $value) {
779
-                // don't set instance to null like it was originally,
780
-                // but it's static anyways, and we're ignoring static properties (for now at least)
781
-                if (! isset($static_properties[ $property ])) {
782
-                    static::$_instance->{$property} = $value;
783
-                }
784
-            }
785
-            // and then directly call its constructor again, like we would if we were creating a new one
786
-            static::$_instance->__construct(
787
-                $timezone,
788
-                EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
789
-            );
790
-            return self::instance();
791
-        }
792
-        return null;
793
-    }
794
-
795
-
796
-
797
-    /**
798
-     * @return LoaderInterface
799
-     * @throws InvalidArgumentException
800
-     * @throws InvalidDataTypeException
801
-     * @throws InvalidInterfaceException
802
-     */
803
-    private static function getLoader()
804
-    {
805
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
806
-            EEM_Base::$loader = LoaderFactory::getLoader();
807
-        }
808
-        return EEM_Base::$loader;
809
-    }
810
-
811
-
812
-
813
-    /**
814
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
815
-     *
816
-     * @param  boolean $translated return localized strings or JUST the array.
817
-     * @return array
818
-     * @throws EE_Error
819
-     * @throws InvalidArgumentException
820
-     * @throws InvalidDataTypeException
821
-     * @throws InvalidInterfaceException
822
-     */
823
-    public function status_array($translated = false)
824
-    {
825
-        if (! array_key_exists('Status', $this->_model_relations)) {
826
-            return array();
827
-        }
828
-        $model_name = $this->get_this_model_name();
829
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
830
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831
-        $status_array = array();
832
-        foreach ($stati as $status) {
833
-            $status_array[ $status->ID() ] = $status->get('STS_code');
834
-        }
835
-        return $translated
836
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
837
-            : $status_array;
838
-    }
839
-
840
-
841
-
842
-    /**
843
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
844
-     *
845
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
846
-     *                             or if you have the development copy of EE you can view this at the path:
847
-     *                             /docs/G--Model-System/model-query-params.md
848
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
849
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
-     *                                        array( array(
853
-     *                                        'OR'=>array(
854
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
-     *                                        )
857
-     *                                        ),
858
-     *                                        'limit'=>10,
859
-     *                                        'group_by'=>'TXN_ID'
860
-     *                                        ));
861
-     *                                        get all the answers to the question titled "shirt size" for event with id
862
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
-     *                                        'Question.QST_display_text'=>'shirt size',
864
-     *                                        'Registration.Event.EVT_ID'=>12
865
-     *                                        ),
866
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
867
-     *                                        ));
868
-     * @throws EE_Error
869
-     */
870
-    public function get_all($query_params = array())
871
-    {
872
-        if (
873
-            isset($query_params['limit'])
874
-            && ! isset($query_params['group_by'])
875
-        ) {
876
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
877
-        }
878
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
879
-    }
880
-
881
-
882
-
883
-    /**
884
-     * Modifies the query parameters so we only get back model objects
885
-     * that "belong" to the current user
886
-     *
887
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
889
-     */
890
-    public function alter_query_params_to_only_include_mine($query_params = array())
891
-    {
892
-        $wp_user_field_name = $this->wp_user_field_name();
893
-        if ($wp_user_field_name) {
894
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
895
-        }
896
-        return $query_params;
897
-    }
898
-
899
-
900
-
901
-    /**
902
-     * Returns the name of the field's name that points to the WP_User table
903
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
904
-     * foreign key to the WP_User table)
905
-     *
906
-     * @return string|boolean string on success, boolean false when there is no
907
-     * foreign key to the WP_User table
908
-     */
909
-    public function wp_user_field_name()
910
-    {
911
-        try {
912
-            if (! empty($this->_model_chain_to_wp_user)) {
913
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914
-                $last_model_name = end($models_to_follow_to_wp_users);
915
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
917
-            } else {
918
-                $model_with_fk_to_wp_users = $this;
919
-                $model_chain_to_wp_user = '';
920
-            }
921
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
923
-        } catch (EE_Error $e) {
924
-            return false;
925
-        }
926
-    }
927
-
928
-
929
-
930
-    /**
931
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
932
-     * (or transiently-related model) has a foreign key to the wp_users table;
933
-     * useful for finding if model objects of this type are 'owned' by the current user.
934
-     * This is an empty string when the foreign key is on this model and when it isn't,
935
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
936
-     * (or transiently-related model)
937
-     *
938
-     * @return string
939
-     */
940
-    public function model_chain_to_wp_user()
941
-    {
942
-        return $this->_model_chain_to_wp_user;
943
-    }
944
-
945
-
946
-
947
-    /**
948
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
949
-     * like how registrations don't have a foreign key to wp_users, but the
950
-     * events they are for are), or is unrelated to wp users.
951
-     * generally available
952
-     *
953
-     * @return boolean
954
-     */
955
-    public function is_owned()
956
-    {
957
-        if ($this->model_chain_to_wp_user()) {
958
-            return true;
959
-        }
960
-        try {
961
-            $this->get_foreign_key_to('WP_User');
962
-            return true;
963
-        } catch (EE_Error $e) {
964
-            return false;
965
-        }
966
-    }
967
-
968
-
969
-    /**
970
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
971
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
972
-     * the model)
973
-     *
974
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
975
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
976
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
977
-     *                                  fields on the model, and the models we joined to in the query. However, you can
978
-     *                                  override this and set the select to "*", or a specific column name, like
979
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
980
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
981
-     *                                  the aliases used to refer to this selection, and values are to be
982
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
983
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
984
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
985
-     * @throws EE_Error
986
-     * @throws InvalidArgumentException
987
-     */
988
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
989
-    {
990
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
991
-        ;
992
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
993
-        $select_expressions = $columns_to_select === null
994
-            ? $this->_construct_default_select_sql($model_query_info)
995
-            : '';
996
-        if ($this->_custom_selections instanceof CustomSelects) {
997
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998
-            $select_expressions .= $select_expressions
999
-                ? ', ' . $custom_expressions
1000
-                : $custom_expressions;
1001
-        }
1002
-
1003
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1004
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1010
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1011
-     * method of including extra select information.
1012
-     *
1013
-     * @param array             $query_params
1014
-     * @param null|array|string $columns_to_select
1015
-     * @return null|CustomSelects
1016
-     * @throws InvalidArgumentException
1017
-     */
1018
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019
-    {
1020
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021
-            return null;
1022
-        }
1023
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1024
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1025
-        return new CustomSelects($selects);
1026
-    }
1027
-
1028
-
1029
-
1030
-    /**
1031
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1032
-     * but you can use the model query params to more easily
1033
-     * take care of joins, field preparation etc.
1034
-     *
1035
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1036
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1039
-     *                                  override this and set the select to "*", or a specific column name, like
1040
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
-     *                                  the aliases used to refer to this selection, and values are to be
1043
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
-     * @throws EE_Error
1047
-     */
1048
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
-    {
1050
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
-    }
1052
-
1053
-
1054
-
1055
-    /**
1056
-     * For creating a custom select statement
1057
-     *
1058
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
-     *                                 SQL, and 1=>is the datatype
1061
-     * @throws EE_Error
1062
-     * @return string
1063
-     */
1064
-    private function _construct_select_from_input($columns_to_select)
1065
-    {
1066
-        if (is_array($columns_to_select)) {
1067
-            $select_sql_array = array();
1068
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
-                    throw new EE_Error(
1071
-                        sprintf(
1072
-                            esc_html__(
1073
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
-                                'event_espresso'
1075
-                            ),
1076
-                            $selection_and_datatype,
1077
-                            $alias
1078
-                        )
1079
-                    );
1080
-                }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082
-                    throw new EE_Error(
1083
-                        sprintf(
1084
-                            esc_html__(
1085
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
-                                'event_espresso'
1087
-                            ),
1088
-                            $selection_and_datatype[1],
1089
-                            $selection_and_datatype[0],
1090
-                            $alias,
1091
-                            implode(', ', $this->_valid_wpdb_data_types)
1092
-                        )
1093
-                    );
1094
-                }
1095
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
-            }
1097
-            $columns_to_select_string = implode(', ', $select_sql_array);
1098
-        } else {
1099
-            $columns_to_select_string = $columns_to_select;
1100
-        }
1101
-        return $columns_to_select_string;
1102
-    }
1103
-
1104
-
1105
-
1106
-    /**
1107
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
-     *
1109
-     * @return string
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function primary_key_name()
1113
-    {
1114
-        return $this->get_primary_key_field()->get_name();
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1120
-     * If there is no primary key on this model, $id is treated as primary key string
1121
-     *
1122
-     * @param mixed $id int or string, depending on the type of the model's primary key
1123
-     * @return EE_Base_Class
1124
-     * @throws EE_Error
1125
-     */
1126
-    public function get_one_by_ID($id)
1127
-    {
1128
-        if ($this->get_from_entity_map($id)) {
1129
-            return $this->get_from_entity_map($id);
1130
-        }
1131
-        $model_object = $this->get_one(
1132
-            $this->alter_query_params_to_restrict_by_ID(
1133
-                $id,
1134
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
-            )
1136
-        );
1137
-        $className = $this->_get_class_name();
1138
-        if ($model_object instanceof $className) {
1139
-            // make sure valid objects get added to the entity map
1140
-            // so that the next call to this method doesn't trigger another trip to the db
1141
-            $this->add_to_entity_map($model_object);
1142
-        }
1143
-        return $model_object;
1144
-    }
1145
-
1146
-
1147
-
1148
-    /**
1149
-     * Alters query parameters to only get items with this ID are returned.
1150
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1151
-     * or could just be a simple primary key ID
1152
-     *
1153
-     * @param int   $id
1154
-     * @param array $query_params
1155
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1156
-     * @throws EE_Error
1157
-     */
1158
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159
-    {
1160
-        if (! isset($query_params[0])) {
1161
-            $query_params[0] = array();
1162
-        }
1163
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1164
-        if ($conditions_from_id === null) {
1165
-            $query_params[0][ $this->primary_key_name() ] = $id;
1166
-        } else {
1167
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1168
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1169
-        }
1170
-        return $query_params;
1171
-    }
1172
-
1173
-
1174
-
1175
-    /**
1176
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1177
-     * array. If no item is found, null is returned.
1178
-     *
1179
-     * @param array $query_params like EEM_Base's $query_params variable.
1180
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1181
-     * @throws EE_Error
1182
-     */
1183
-    public function get_one($query_params = array())
1184
-    {
1185
-        if (! is_array($query_params)) {
1186
-            EE_Error::doing_it_wrong(
1187
-                'EEM_Base::get_one',
1188
-                sprintf(
1189
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1190
-                    gettype($query_params)
1191
-                ),
1192
-                '4.6.0'
1193
-            );
1194
-            $query_params = array();
1195
-        }
1196
-        $query_params['limit'] = 1;
1197
-        $items = $this->get_all($query_params);
1198
-        if (empty($items)) {
1199
-            return null;
1200
-        }
1201
-        return array_shift($items);
1202
-    }
1203
-
1204
-
1205
-
1206
-    /**
1207
-     * Returns the next x number of items in sequence from the given value as
1208
-     * found in the database matching the given query conditions.
1209
-     *
1210
-     * @param mixed $current_field_value    Value used for the reference point.
1211
-     * @param null  $field_to_order_by      What field is used for the
1212
-     *                                      reference point.
1213
-     * @param int   $limit                  How many to return.
1214
-     * @param array $query_params           Extra conditions on the query.
1215
-     * @param null  $columns_to_select      If left null, then an array of
1216
-     *                                      EE_Base_Class objects is returned,
1217
-     *                                      otherwise you can indicate just the
1218
-     *                                      columns you want returned.
1219
-     * @return EE_Base_Class[]|array
1220
-     * @throws EE_Error
1221
-     */
1222
-    public function next_x(
1223
-        $current_field_value,
1224
-        $field_to_order_by = null,
1225
-        $limit = 1,
1226
-        $query_params = array(),
1227
-        $columns_to_select = null
1228
-    ) {
1229
-        return $this->_get_consecutive(
1230
-            $current_field_value,
1231
-            '>',
1232
-            $field_to_order_by,
1233
-            $limit,
1234
-            $query_params,
1235
-            $columns_to_select
1236
-        );
1237
-    }
1238
-
1239
-
1240
-
1241
-    /**
1242
-     * Returns the previous x number of items in sequence from the given value
1243
-     * as found in the database matching the given query conditions.
1244
-     *
1245
-     * @param mixed $current_field_value    Value used for the reference point.
1246
-     * @param null  $field_to_order_by      What field is used for the
1247
-     *                                      reference point.
1248
-     * @param int   $limit                  How many to return.
1249
-     * @param array $query_params           Extra conditions on the query.
1250
-     * @param null  $columns_to_select      If left null, then an array of
1251
-     *                                      EE_Base_Class objects is returned,
1252
-     *                                      otherwise you can indicate just the
1253
-     *                                      columns you want returned.
1254
-     * @return EE_Base_Class[]|array
1255
-     * @throws EE_Error
1256
-     */
1257
-    public function previous_x(
1258
-        $current_field_value,
1259
-        $field_to_order_by = null,
1260
-        $limit = 1,
1261
-        $query_params = array(),
1262
-        $columns_to_select = null
1263
-    ) {
1264
-        return $this->_get_consecutive(
1265
-            $current_field_value,
1266
-            '<',
1267
-            $field_to_order_by,
1268
-            $limit,
1269
-            $query_params,
1270
-            $columns_to_select
1271
-        );
1272
-    }
1273
-
1274
-
1275
-
1276
-    /**
1277
-     * Returns the next item in sequence from the given value as found in the
1278
-     * database matching the given query conditions.
1279
-     *
1280
-     * @param mixed $current_field_value    Value used for the reference point.
1281
-     * @param null  $field_to_order_by      What field is used for the
1282
-     *                                      reference point.
1283
-     * @param array $query_params           Extra conditions on the query.
1284
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1285
-     *                                      object is returned, otherwise you
1286
-     *                                      can indicate just the columns you
1287
-     *                                      want and a single array indexed by
1288
-     *                                      the columns will be returned.
1289
-     * @return EE_Base_Class|null|array()
1290
-     * @throws EE_Error
1291
-     */
1292
-    public function next(
1293
-        $current_field_value,
1294
-        $field_to_order_by = null,
1295
-        $query_params = array(),
1296
-        $columns_to_select = null
1297
-    ) {
1298
-        $results = $this->_get_consecutive(
1299
-            $current_field_value,
1300
-            '>',
1301
-            $field_to_order_by,
1302
-            1,
1303
-            $query_params,
1304
-            $columns_to_select
1305
-        );
1306
-        return empty($results) ? null : reset($results);
1307
-    }
1308
-
1309
-
1310
-
1311
-    /**
1312
-     * Returns the previous item in sequence from the given value as found in
1313
-     * the database matching the given query conditions.
1314
-     *
1315
-     * @param mixed $current_field_value    Value used for the reference point.
1316
-     * @param null  $field_to_order_by      What field is used for the
1317
-     *                                      reference point.
1318
-     * @param array $query_params           Extra conditions on the query.
1319
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1320
-     *                                      object is returned, otherwise you
1321
-     *                                      can indicate just the columns you
1322
-     *                                      want and a single array indexed by
1323
-     *                                      the columns will be returned.
1324
-     * @return EE_Base_Class|null|array()
1325
-     * @throws EE_Error
1326
-     */
1327
-    public function previous(
1328
-        $current_field_value,
1329
-        $field_to_order_by = null,
1330
-        $query_params = array(),
1331
-        $columns_to_select = null
1332
-    ) {
1333
-        $results = $this->_get_consecutive(
1334
-            $current_field_value,
1335
-            '<',
1336
-            $field_to_order_by,
1337
-            1,
1338
-            $query_params,
1339
-            $columns_to_select
1340
-        );
1341
-        return empty($results) ? null : reset($results);
1342
-    }
1343
-
1344
-
1345
-
1346
-    /**
1347
-     * Returns the a consecutive number of items in sequence from the given
1348
-     * value as found in the database matching the given query conditions.
1349
-     *
1350
-     * @param mixed  $current_field_value   Value used for the reference point.
1351
-     * @param string $operand               What operand is used for the sequence.
1352
-     * @param string $field_to_order_by     What field is used for the reference point.
1353
-     * @param int    $limit                 How many to return.
1354
-     * @param array  $query_params          Extra conditions on the query.
1355
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1356
-     *                                      otherwise you can indicate just the columns you want returned.
1357
-     * @return EE_Base_Class[]|array
1358
-     * @throws EE_Error
1359
-     */
1360
-    protected function _get_consecutive(
1361
-        $current_field_value,
1362
-        $operand = '>',
1363
-        $field_to_order_by = null,
1364
-        $limit = 1,
1365
-        $query_params = array(),
1366
-        $columns_to_select = null
1367
-    ) {
1368
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1369
-        if (empty($field_to_order_by)) {
1370
-            if ($this->has_primary_key_field()) {
1371
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1372
-            } else {
1373
-                if (WP_DEBUG) {
1374
-                    throw new EE_Error(esc_html__(
1375
-                        '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).',
1376
-                        'event_espresso'
1377
-                    ));
1378
-                }
1379
-                EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1380
-                return array();
1381
-            }
1382
-        }
1383
-        if (! is_array($query_params)) {
1384
-            EE_Error::doing_it_wrong(
1385
-                'EEM_Base::_get_consecutive',
1386
-                sprintf(
1387
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1388
-                    gettype($query_params)
1389
-                ),
1390
-                '4.6.0'
1391
-            );
1392
-            $query_params = array();
1393
-        }
1394
-        // let's add the where query param for consecutive look up.
1395
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1396
-        $query_params['limit'] = $limit;
1397
-        // set direction
1398
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1399
-        $query_params['order_by'] = $operand === '>'
1400
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1401
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1402
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1403
-        if (empty($columns_to_select)) {
1404
-            return $this->get_all($query_params);
1405
-        }
1406
-        // getting just the fields
1407
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1408
-    }
1409
-
1410
-
1411
-
1412
-    /**
1413
-     * This sets the _timezone property after model object has been instantiated.
1414
-     *
1415
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1416
-     */
1417
-    public function set_timezone($timezone)
1418
-    {
1419
-        if ($timezone !== null) {
1420
-            $this->_timezone = $timezone;
1421
-        }
1422
-        // note we need to loop through relations and set the timezone on those objects as well.
1423
-        foreach ($this->_model_relations as $relation) {
1424
-            $relation->set_timezone($timezone);
1425
-        }
1426
-        // and finally we do the same for any datetime fields
1427
-        foreach ($this->_fields as $field) {
1428
-            if ($field instanceof EE_Datetime_Field) {
1429
-                $field->set_timezone($timezone);
1430
-            }
1431
-        }
1432
-    }
1433
-
1434
-
1435
-
1436
-    /**
1437
-     * This just returns whatever is set for the current timezone.
1438
-     *
1439
-     * @access public
1440
-     * @return string
1441
-     */
1442
-    public function get_timezone()
1443
-    {
1444
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1445
-        if (empty($this->_timezone)) {
1446
-            foreach ($this->_fields as $field) {
1447
-                if ($field instanceof EE_Datetime_Field) {
1448
-                    $this->set_timezone($field->get_timezone());
1449
-                    break;
1450
-                }
1451
-            }
1452
-        }
1453
-        // if timezone STILL empty then return the default timezone for the site.
1454
-        if (empty($this->_timezone)) {
1455
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1456
-        }
1457
-        return $this->_timezone;
1458
-    }
1459
-
1460
-
1461
-
1462
-    /**
1463
-     * This returns the date formats set for the given field name and also ensures that
1464
-     * $this->_timezone property is set correctly.
1465
-     *
1466
-     * @since 4.6.x
1467
-     * @param string $field_name The name of the field the formats are being retrieved for.
1468
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1469
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1470
-     * @return array formats in an array with the date format first, and the time format last.
1471
-     */
1472
-    public function get_formats_for($field_name, $pretty = false)
1473
-    {
1474
-        $field_settings = $this->field_settings_for($field_name);
1475
-        // if not a valid EE_Datetime_Field then throw error
1476
-        if (! $field_settings instanceof EE_Datetime_Field) {
1477
-            throw new EE_Error(sprintf(esc_html__(
1478
-                '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.',
1479
-                'event_espresso'
1480
-            ), $field_name));
1481
-        }
1482
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1483
-        // the field.
1484
-        $this->_timezone = $field_settings->get_timezone();
1485
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1486
-    }
1487
-
1488
-
1489
-
1490
-    /**
1491
-     * This returns the current time in a format setup for a query on this model.
1492
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1493
-     * it will return:
1494
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1495
-     *  NOW
1496
-     *  - or a unix timestamp (equivalent to time())
1497
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1498
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1499
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1500
-     * @since 4.6.x
1501
-     * @param string $field_name       The field the current time is needed for.
1502
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1503
-     *                                 formatted string matching the set format for the field in the set timezone will
1504
-     *                                 be returned.
1505
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1506
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1507
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1508
-     *                                 exception is triggered.
1509
-     */
1510
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1511
-    {
1512
-        $formats = $this->get_formats_for($field_name);
1513
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1514
-        if ($timestamp) {
1515
-            return $DateTime->format('U');
1516
-        }
1517
-        // not returning timestamp, so return formatted string in timezone.
1518
-        switch ($what) {
1519
-            case 'time':
1520
-                return $DateTime->format($formats[1]);
1521
-                break;
1522
-            case 'date':
1523
-                return $DateTime->format($formats[0]);
1524
-                break;
1525
-            default:
1526
-                return $DateTime->format(implode(' ', $formats));
1527
-                break;
1528
-        }
1529
-    }
1530
-
1531
-
1532
-
1533
-    /**
1534
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1535
-     * for the model are.  Returns a DateTime object.
1536
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1537
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1538
-     * ignored.
1539
-     *
1540
-     * @param string $field_name      The field being setup.
1541
-     * @param string $timestring      The date time string being used.
1542
-     * @param string $incoming_format The format for the time string.
1543
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1544
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1545
-     *                                format is
1546
-     *                                'U', this is ignored.
1547
-     * @return DateTime
1548
-     * @throws EE_Error
1549
-     */
1550
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1551
-    {
1552
-        // just using this to ensure the timezone is set correctly internally
1553
-        $this->get_formats_for($field_name);
1554
-        // load EEH_DTT_Helper
1555
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1556
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1557
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1558
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1565
-     *
1566
-     * @return EE_Table_Base[]
1567
-     */
1568
-    public function get_tables()
1569
-    {
1570
-        return $this->_tables;
1571
-    }
1572
-
1573
-
1574
-
1575
-    /**
1576
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1577
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1578
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1579
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1580
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1581
-     * model object with EVT_ID = 1
1582
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1583
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1584
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1585
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1586
-     * are not specified)
1587
-     *
1588
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1589
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1590
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1591
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1592
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1593
-     *                                         ID=34, we'd use this method as follows:
1594
-     *                                         EEM_Transaction::instance()->update(
1595
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1596
-     *                                         array(array('TXN_ID'=>34)));
1597
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1598
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1599
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1600
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1601
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1602
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1603
-     *                                         TRUE, it is assumed that you've already called
1604
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1605
-     *                                         malicious javascript. However, if
1606
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1607
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1608
-     *                                         and every other field, before insertion. We provide this parameter
1609
-     *                                         because model objects perform their prepare_for_set function on all
1610
-     *                                         their values, and so don't need to be called again (and in many cases,
1611
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1612
-     *                                         prepare_for_set method...)
1613
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1614
-     *                                         in this model's entity map according to $fields_n_values that match
1615
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1616
-     *                                         by setting this to FALSE, but be aware that model objects being used
1617
-     *                                         could get out-of-sync with the database
1618
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1619
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1620
-     *                                         bad)
1621
-     * @throws EE_Error
1622
-     */
1623
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624
-    {
1625
-        if (! is_array($query_params)) {
1626
-            EE_Error::doing_it_wrong(
1627
-                'EEM_Base::update',
1628
-                sprintf(
1629
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1630
-                    gettype($query_params)
1631
-                ),
1632
-                '4.6.0'
1633
-            );
1634
-            $query_params = array();
1635
-        }
1636
-        /**
1637
-         * Action called before a model update call has been made.
1638
-         *
1639
-         * @param EEM_Base $model
1640
-         * @param array    $fields_n_values the updated fields and their new values
1641
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
-         */
1643
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1644
-        /**
1645
-         * Filters the fields about to be updated given the query parameters. You can provide the
1646
-         * $query_params to $this->get_all() to find exactly which records will be updated
1647
-         *
1648
-         * @param array    $fields_n_values fields and their new values
1649
-         * @param EEM_Base $model           the model being queried
1650
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1651
-         */
1652
-        $fields_n_values = (array) apply_filters(
1653
-            'FHEE__EEM_Base__update__fields_n_values',
1654
-            $fields_n_values,
1655
-            $this,
1656
-            $query_params
1657
-        );
1658
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1659
-        // to do that, for each table, verify that it's PK isn't null.
1660
-        $tables = $this->get_tables();
1661
-        // 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
1662
-        // NOTE: we should make this code more efficient by NOT querying twice
1663
-        // before the real update, but that needs to first go through ALPHA testing
1664
-        // as it's dangerous. says Mike August 8 2014
1665
-        // we want to make sure the default_where strategy is ignored
1666
-        $this->_ignore_where_strategy = true;
1667
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1668
-        foreach ($wpdb_select_results as $wpdb_result) {
1669
-            // type cast stdClass as array
1670
-            $wpdb_result = (array) $wpdb_result;
1671
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672
-            if ($this->has_primary_key_field()) {
1673
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1674
-            } else {
1675
-                // 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)
1676
-                $main_table_pk_value = null;
1677
-            }
1678
-            // 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
1679
-            // 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
1680
-            if (count($tables) > 1) {
1681
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1682
-                // in that table, and so we'll want to insert one
1683
-                foreach ($tables as $table_obj) {
1684
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1685
-                    // if there is no private key for this table on the results, it means there's no entry
1686
-                    // in this table, right? so insert a row in the current table, using any fields available
1687
-                    if (
1688
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
-                           && $wpdb_result[ $this_table_pk_column ])
1690
-                    ) {
1691
-                        $success = $this->_insert_into_specific_table(
1692
-                            $table_obj,
1693
-                            $fields_n_values,
1694
-                            $main_table_pk_value
1695
-                        );
1696
-                        // if we died here, report the error
1697
-                        if (! $success) {
1698
-                            return false;
1699
-                        }
1700
-                    }
1701
-                }
1702
-            }
1703
-            //              //and now check that if we have cached any models by that ID on the model, that
1704
-            //              //they also get updated properly
1705
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1706
-            //              if( $model_object ){
1707
-            //                  foreach( $fields_n_values as $field => $value ){
1708
-            //                      $model_object->set($field, $value);
1709
-            // let's make sure default_where strategy is followed now
1710
-            $this->_ignore_where_strategy = false;
1711
-        }
1712
-        // if we want to keep model objects in sync, AND
1713
-        // if this wasn't called from a model object (to update itself)
1714
-        // then we want to make sure we keep all the existing
1715
-        // model objects in sync with the db
1716
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1717
-            if ($this->has_primary_key_field()) {
1718
-                $model_objs_affected_ids = $this->get_col($query_params);
1719
-            } else {
1720
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1721
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1722
-                $model_objs_affected_ids = array();
1723
-                foreach ($models_affected_key_columns as $row) {
1724
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1725
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1726
-                }
1727
-            }
1728
-            if (! $model_objs_affected_ids) {
1729
-                // wait wait wait- if nothing was affected let's stop here
1730
-                return 0;
1731
-            }
1732
-            foreach ($model_objs_affected_ids as $id) {
1733
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1734
-                if ($model_obj_in_entity_map) {
1735
-                    foreach ($fields_n_values as $field => $new_value) {
1736
-                        $model_obj_in_entity_map->set($field, $new_value);
1737
-                    }
1738
-                }
1739
-            }
1740
-            // if there is a primary key on this model, we can now do a slight optimization
1741
-            if ($this->has_primary_key_field()) {
1742
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1743
-                $query_params = array(
1744
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1745
-                    'limit'                    => count($model_objs_affected_ids),
1746
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1747
-                );
1748
-            }
1749
-        }
1750
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1751
-        $SQL = "UPDATE "
1752
-               . $model_query_info->get_full_join_sql()
1753
-               . " SET "
1754
-               . $this->_construct_update_sql($fields_n_values)
1755
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757
-        /**
1758
-         * Action called after a model update call has been made.
1759
-         *
1760
-         * @param EEM_Base $model
1761
-         * @param array    $fields_n_values the updated fields and their new values
1762
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1763
-         * @param int      $rows_affected
1764
-         */
1765
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
-        return $rows_affected;// how many supposedly got updated
1767
-    }
1768
-
1769
-
1770
-
1771
-    /**
1772
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1773
-     * are teh values of the field specified (or by default the primary key field)
1774
-     * that matched the query params. Note that you should pass the name of the
1775
-     * model FIELD, not the database table's column name.
1776
-     *
1777
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1778
-     * @param string $field_to_select
1779
-     * @return array just like $wpdb->get_col()
1780
-     * @throws EE_Error
1781
-     */
1782
-    public function get_col($query_params = array(), $field_to_select = null)
1783
-    {
1784
-        if ($field_to_select) {
1785
-            $field = $this->field_settings_for($field_to_select);
1786
-        } elseif ($this->has_primary_key_field()) {
1787
-            $field = $this->get_primary_key_field();
1788
-        } else {
1789
-            // no primary key, just grab the first column
1790
-            $field = reset($this->field_settings());
1791
-        }
1792
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1793
-        $select_expressions = $field->get_qualified_column();
1794
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1795
-        return $this->_do_wpdb_query('get_col', array($SQL));
1796
-    }
1797
-
1798
-
1799
-
1800
-    /**
1801
-     * Returns a single column value for a single row from the database
1802
-     *
1803
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1804
-     * @param string $field_to_select @see EEM_Base::get_col()
1805
-     * @return string
1806
-     * @throws EE_Error
1807
-     */
1808
-    public function get_var($query_params = array(), $field_to_select = null)
1809
-    {
1810
-        $query_params['limit'] = 1;
1811
-        $col = $this->get_col($query_params, $field_to_select);
1812
-        if (! empty($col)) {
1813
-            return reset($col);
1814
-        }
1815
-        return null;
1816
-    }
1817
-
1818
-
1819
-
1820
-    /**
1821
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1822
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1823
-     * injection, but currently no further filtering is done
1824
-     *
1825
-     * @global      $wpdb
1826
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1827
-     *                               be updated to in the DB
1828
-     * @return string of SQL
1829
-     * @throws EE_Error
1830
-     */
1831
-    public function _construct_update_sql($fields_n_values)
1832
-    {
1833
-        /** @type WPDB $wpdb */
1834
-        global $wpdb;
1835
-        $cols_n_values = array();
1836
-        foreach ($fields_n_values as $field_name => $value) {
1837
-            $field_obj = $this->field_settings_for($field_name);
1838
-            // if the value is NULL, we want to assign the value to that.
1839
-            // wpdb->prepare doesn't really handle that properly
1840
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1841
-            $value_sql = $prepared_value === null ? 'NULL'
1842
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1843
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1844
-        }
1845
-        return implode(",", $cols_n_values);
1846
-    }
1847
-
1848
-
1849
-
1850
-    /**
1851
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1852
-     * Performs a HARD delete, meaning the database row should always be removed,
1853
-     * not just have a flag field on it switched
1854
-     * Wrapper for EEM_Base::delete_permanently()
1855
-     *
1856
-     * @param mixed $id
1857
-     * @param boolean $allow_blocking
1858
-     * @return int the number of rows deleted
1859
-     * @throws EE_Error
1860
-     */
1861
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1862
-    {
1863
-        return $this->delete_permanently(
1864
-            array(
1865
-                array($this->get_primary_key_field()->get_name() => $id),
1866
-                'limit' => 1,
1867
-            ),
1868
-            $allow_blocking
1869
-        );
1870
-    }
1871
-
1872
-
1873
-
1874
-    /**
1875
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1876
-     * Wrapper for EEM_Base::delete()
1877
-     *
1878
-     * @param mixed $id
1879
-     * @param boolean $allow_blocking
1880
-     * @return int the number of rows deleted
1881
-     * @throws EE_Error
1882
-     */
1883
-    public function delete_by_ID($id, $allow_blocking = true)
1884
-    {
1885
-        return $this->delete(
1886
-            array(
1887
-                array($this->get_primary_key_field()->get_name() => $id),
1888
-                'limit' => 1,
1889
-            ),
1890
-            $allow_blocking
1891
-        );
1892
-    }
1893
-
1894
-
1895
-
1896
-    /**
1897
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1898
-     * meaning if the model has a field that indicates its been "trashed" or
1899
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1900
-     *
1901
-     * @see EEM_Base::delete_permanently
1902
-     * @param array   $query_params
1903
-     * @param boolean $allow_blocking
1904
-     * @return int how many rows got deleted
1905
-     * @throws EE_Error
1906
-     */
1907
-    public function delete($query_params, $allow_blocking = true)
1908
-    {
1909
-        return $this->delete_permanently($query_params, $allow_blocking);
1910
-    }
1911
-
1912
-
1913
-
1914
-    /**
1915
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1916
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1917
-     * as archived, not actually deleted
1918
-     *
1919
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1920
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1921
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1922
-     *                                deletes regardless of other objects which may depend on it. Its generally
1923
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1924
-     *                                DB
1925
-     * @return int how many rows got deleted
1926
-     * @throws EE_Error
1927
-     */
1928
-    public function delete_permanently($query_params, $allow_blocking = true)
1929
-    {
1930
-        /**
1931
-         * Action called just before performing a real deletion query. You can use the
1932
-         * model and its $query_params to find exactly which items will be deleted
1933
-         *
1934
-         * @param EEM_Base $model
1935
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1936
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1937
-         *                                 to block (prevent) this deletion
1938
-         */
1939
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1940
-        // some MySQL databases may be running safe mode, which may restrict
1941
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1942
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1943
-        // to delete them
1944
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1945
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1946
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1947
-            $columns_and_ids_for_deleting
1948
-        );
1949
-        /**
1950
-         * Allows client code to act on the items being deleted before the query is actually executed.
1951
-         *
1952
-         * @param EEM_Base $this  The model instance being acted on.
1953
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1954
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1955
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1956
-         *                                                  derived from the incoming query parameters.
1957
-         *                                                  @see details on the structure of this array in the phpdocs
1958
-         *                                                  for the `_get_ids_for_delete_method`
1959
-         *
1960
-         */
1961
-        do_action(
1962
-            'AHEE__EEM_Base__delete__before_query',
1963
-            $this,
1964
-            $query_params,
1965
-            $allow_blocking,
1966
-            $columns_and_ids_for_deleting
1967
-        );
1968
-        if ($deletion_where_query_part) {
1969
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1970
-            $table_aliases = array_keys($this->_tables);
1971
-            $SQL = "DELETE "
1972
-                   . implode(", ", $table_aliases)
1973
-                   . " FROM "
1974
-                   . $model_query_info->get_full_join_sql()
1975
-                   . " WHERE "
1976
-                   . $deletion_where_query_part;
1977
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1978
-        } else {
1979
-            $rows_deleted = 0;
1980
-        }
1981
-
1982
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1983
-        // there was no error with the delete query.
1984
-        if (
1985
-            $this->has_primary_key_field()
1986
-            && $rows_deleted !== false
1987
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1988
-        ) {
1989
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1990
-            foreach ($ids_for_removal as $id) {
1991
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1992
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1993
-                }
1994
-            }
1995
-
1996
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1997
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1998
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1999
-            // (although it is possible).
2000
-            // Note this can be skipped by using the provided filter and returning false.
2001
-            if (
2002
-                apply_filters(
2003
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2004
-                    ! $this instanceof EEM_Extra_Meta,
2005
-                    $this
2006
-                )
2007
-            ) {
2008
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2009
-                    0 => array(
2010
-                        'EXM_type' => $this->get_this_model_name(),
2011
-                        'OBJ_ID'   => array(
2012
-                            'IN',
2013
-                            $ids_for_removal
2014
-                        )
2015
-                    )
2016
-                ));
2017
-            }
2018
-        }
2019
-
2020
-        /**
2021
-         * Action called just after performing a real deletion query. Although at this point the
2022
-         * items should have been deleted
2023
-         *
2024
-         * @param EEM_Base $model
2025
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2026
-         * @param int      $rows_deleted
2027
-         */
2028
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
-        return $rows_deleted;// how many supposedly got deleted
2030
-    }
2031
-
2032
-
2033
-
2034
-    /**
2035
-     * Checks all the relations that throw error messages when there are blocking related objects
2036
-     * for related model objects. If there are any related model objects on those relations,
2037
-     * adds an EE_Error, and return true
2038
-     *
2039
-     * @param EE_Base_Class|int $this_model_obj_or_id
2040
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2041
-     *                                                 should be ignored when determining whether there are related
2042
-     *                                                 model objects which block this model object's deletion. Useful
2043
-     *                                                 if you know A is related to B and are considering deleting A,
2044
-     *                                                 but want to see if A has any other objects blocking its deletion
2045
-     *                                                 before removing the relation between A and B
2046
-     * @return boolean
2047
-     * @throws EE_Error
2048
-     */
2049
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2050
-    {
2051
-        // first, if $ignore_this_model_obj was supplied, get its model
2052
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2053
-            $ignored_model = $ignore_this_model_obj->get_model();
2054
-        } else {
2055
-            $ignored_model = null;
2056
-        }
2057
-        // now check all the relations of $this_model_obj_or_id and see if there
2058
-        // are any related model objects blocking it?
2059
-        $is_blocked = false;
2060
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2061
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2062
-                // if $ignore_this_model_obj was supplied, then for the query
2063
-                // on that model needs to be told to ignore $ignore_this_model_obj
2064
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2065
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2066
-                        array(
2067
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2068
-                                '!=',
2069
-                                $ignore_this_model_obj->ID(),
2070
-                            ),
2071
-                        ),
2072
-                    ));
2073
-                } else {
2074
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2075
-                }
2076
-                if ($related_model_objects) {
2077
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2078
-                    $is_blocked = true;
2079
-                }
2080
-            }
2081
-        }
2082
-        return $is_blocked;
2083
-    }
2084
-
2085
-
2086
-    /**
2087
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2088
-     * @param array $row_results_for_deleting
2089
-     * @param bool  $allow_blocking
2090
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2091
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2092
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2093
-     *                 deleted. Example:
2094
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2095
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2096
-     *                 where each element is a group of columns and values that get deleted. Example:
2097
-     *                      array(
2098
-     *                          0 => array(
2099
-     *                              'Term_Relationship.object_id' => 1
2100
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2101
-     *                          ),
2102
-     *                          1 => array(
2103
-     *                              'Term_Relationship.object_id' => 1
2104
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2105
-     *                          )
2106
-     *                      )
2107
-     * @throws EE_Error
2108
-     */
2109
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2110
-    {
2111
-        $ids_to_delete_indexed_by_column = array();
2112
-        if ($this->has_primary_key_field()) {
2113
-            $primary_table = $this->_get_main_table();
2114
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2115
-            $other_tables = $this->_get_other_tables();
2116
-            $ids_to_delete_indexed_by_column = $query = array();
2117
-            foreach ($row_results_for_deleting as $item_to_delete) {
2118
-                // before we mark this item for deletion,
2119
-                // make sure there's no related entities blocking its deletion (if we're checking)
2120
-                if (
2121
-                    $allow_blocking
2122
-                    && $this->delete_is_blocked_by_related_models(
2123
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2124
-                    )
2125
-                ) {
2126
-                    continue;
2127
-                }
2128
-                // primary table deletes
2129
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2130
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2131
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2132
-                }
2133
-            }
2134
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2135
-            $fields = $this->get_combined_primary_key_fields();
2136
-            foreach ($row_results_for_deleting as $item_to_delete) {
2137
-                $ids_to_delete_indexed_by_column_for_row = array();
2138
-                foreach ($fields as $cpk_field) {
2139
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2140
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2141
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2142
-                    }
2143
-                }
2144
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2145
-            }
2146
-        } else {
2147
-            // so there's no primary key and no combined key...
2148
-            // sorry, can't help you
2149
-            throw new EE_Error(
2150
-                sprintf(
2151
-                    esc_html__(
2152
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2153
-                        "event_espresso"
2154
-                    ),
2155
-                    get_class($this)
2156
-                )
2157
-            );
2158
-        }
2159
-        return $ids_to_delete_indexed_by_column;
2160
-    }
2161
-
2162
-
2163
-    /**
2164
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2165
-     * the corresponding query_part for the query performing the delete.
2166
-     *
2167
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2168
-     * @return string
2169
-     * @throws EE_Error
2170
-     */
2171
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2172
-    {
2173
-        $query_part = '';
2174
-        if (empty($ids_to_delete_indexed_by_column)) {
2175
-            return $query_part;
2176
-        } elseif ($this->has_primary_key_field()) {
2177
-            $query = array();
2178
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2179
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2180
-            }
2181
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2183
-            $ways_to_identify_a_row = array();
2184
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185
-                $values_for_each_combined_primary_key_for_a_row = array();
2186
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2188
-                }
2189
-                $ways_to_identify_a_row[] = '('
2190
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2191
-                                            . ')';
2192
-            }
2193
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2194
-        }
2195
-        return $query_part;
2196
-    }
2197
-
2198
-
2199
-
2200
-    /**
2201
-     * Gets the model field by the fully qualified name
2202
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2203
-     * @return EE_Model_Field_Base
2204
-     */
2205
-    public function get_field_by_column($qualified_column_name)
2206
-    {
2207
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2208
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2209
-                return $field_obj;
2210
-            }
2211
-        }
2212
-        throw new EE_Error(
2213
-            sprintf(
2214
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2215
-                $this->get_this_model_name(),
2216
-                $qualified_column_name
2217
-            )
2218
-        );
2219
-    }
2220
-
2221
-
2222
-
2223
-    /**
2224
-     * Count all the rows that match criteria the model query params.
2225
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2226
-     * column
2227
-     *
2228
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2229
-     * @param string $field_to_count field on model to count by (not column name)
2230
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2231
-     *                               that by the setting $distinct to TRUE;
2232
-     * @return int
2233
-     * @throws EE_Error
2234
-     */
2235
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2236
-    {
2237
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2238
-        if ($field_to_count) {
2239
-            $field_obj = $this->field_settings_for($field_to_count);
2240
-            $column_to_count = $field_obj->get_qualified_column();
2241
-        } elseif ($this->has_primary_key_field()) {
2242
-            $pk_field_obj = $this->get_primary_key_field();
2243
-            $column_to_count = $pk_field_obj->get_qualified_column();
2244
-        } else {
2245
-            // there's no primary key
2246
-            // if we're counting distinct items, and there's no primary key,
2247
-            // we need to list out the columns for distinction;
2248
-            // otherwise we can just use star
2249
-            if ($distinct) {
2250
-                $columns_to_use = array();
2251
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2252
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2253
-                }
2254
-                $column_to_count = implode(',', $columns_to_use);
2255
-            } else {
2256
-                $column_to_count = '*';
2257
-            }
2258
-        }
2259
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2262
-    }
2263
-
2264
-
2265
-
2266
-    /**
2267
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2268
-     *
2269
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2270
-     * @param string $field_to_sum name of field (array key in $_fields array)
2271
-     * @return float
2272
-     * @throws EE_Error
2273
-     */
2274
-    public function sum($query_params, $field_to_sum = null)
2275
-    {
2276
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2277
-        if ($field_to_sum) {
2278
-            $field_obj = $this->field_settings_for($field_to_sum);
2279
-        } else {
2280
-            $field_obj = $this->get_primary_key_field();
2281
-        }
2282
-        $column_to_count = $field_obj->get_qualified_column();
2283
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2284
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285
-        $data_type = $field_obj->get_wpdb_data_type();
2286
-        if ($data_type === '%d' || $data_type === '%s') {
2287
-            return (float) $return_value;
2288
-        }
2289
-        // must be %f
2290
-        return (float) $return_value;
2291
-    }
2292
-
2293
-
2294
-
2295
-    /**
2296
-     * Just calls the specified method on $wpdb with the given arguments
2297
-     * Consolidates a little extra error handling code
2298
-     *
2299
-     * @param string $wpdb_method
2300
-     * @param array  $arguments_to_provide
2301
-     * @throws EE_Error
2302
-     * @global wpdb  $wpdb
2303
-     * @return mixed
2304
-     */
2305
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2306
-    {
2307
-        // if we're in maintenance mode level 2, DON'T run any queries
2308
-        // because level 2 indicates the database needs updating and
2309
-        // is probably out of sync with the code
2310
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2311
-            throw new EE_Error(sprintf(esc_html__(
2312
-                "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.",
2313
-                "event_espresso"
2314
-            )));
2315
-        }
2316
-        /** @type WPDB $wpdb */
2317
-        global $wpdb;
2318
-        if (! method_exists($wpdb, $wpdb_method)) {
2319
-            throw new EE_Error(sprintf(esc_html__(
2320
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2321
-                'event_espresso'
2322
-            ), $wpdb_method));
2323
-        }
2324
-        if (WP_DEBUG) {
2325
-            $old_show_errors_value = $wpdb->show_errors;
2326
-            $wpdb->show_errors(false);
2327
-        }
2328
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2329
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2330
-        if (WP_DEBUG) {
2331
-            $wpdb->show_errors($old_show_errors_value);
2332
-            if (! empty($wpdb->last_error)) {
2333
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2334
-            }
2335
-            if ($result === false) {
2336
-                throw new EE_Error(sprintf(esc_html__(
2337
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2338
-                    'event_espresso'
2339
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2340
-            }
2341
-        } elseif ($result === false) {
2342
-            EE_Error::add_error(
2343
-                sprintf(
2344
-                    esc_html__(
2345
-                        '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"',
2346
-                        'event_espresso'
2347
-                    ),
2348
-                    $wpdb_method,
2349
-                    var_export($arguments_to_provide, true),
2350
-                    $wpdb->last_error
2351
-                ),
2352
-                __FILE__,
2353
-                __FUNCTION__,
2354
-                __LINE__
2355
-            );
2356
-        }
2357
-        return $result;
2358
-    }
2359
-
2360
-
2361
-
2362
-    /**
2363
-     * Attempts to run the indicated WPDB method with the provided arguments,
2364
-     * and if there's an error tries to verify the DB is correct. Uses
2365
-     * the static property EEM_Base::$_db_verification_level to determine whether
2366
-     * we should try to fix the EE core db, the addons, or just give up
2367
-     *
2368
-     * @param string $wpdb_method
2369
-     * @param array  $arguments_to_provide
2370
-     * @return mixed
2371
-     */
2372
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2373
-    {
2374
-        /** @type WPDB $wpdb */
2375
-        global $wpdb;
2376
-        $wpdb->last_error = null;
2377
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2378
-        // was there an error running the query? but we don't care on new activations
2379
-        // (we're going to setup the DB anyway on new activations)
2380
-        if (
2381
-            ($result === false || ! empty($wpdb->last_error))
2382
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2383
-        ) {
2384
-            switch (EEM_Base::$_db_verification_level) {
2385
-                case EEM_Base::db_verified_none:
2386
-                    // let's double-check core's DB
2387
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2388
-                    break;
2389
-                case EEM_Base::db_verified_core:
2390
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2391
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2392
-                    break;
2393
-                case EEM_Base::db_verified_addons:
2394
-                    // ummmm... you in trouble
2395
-                    return $result;
2396
-                    break;
2397
-            }
2398
-            if (! empty($error_message)) {
2399
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2400
-                trigger_error($error_message);
2401
-            }
2402
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2403
-        }
2404
-        return $result;
2405
-    }
2406
-
2407
-
2408
-
2409
-    /**
2410
-     * Verifies the EE core database is up-to-date and records that we've done it on
2411
-     * EEM_Base::$_db_verification_level
2412
-     *
2413
-     * @param string $wpdb_method
2414
-     * @param array  $arguments_to_provide
2415
-     * @return string
2416
-     */
2417
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2418
-    {
2419
-        /** @type WPDB $wpdb */
2420
-        global $wpdb;
2421
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2422
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2423
-        $error_message = sprintf(
2424
-            esc_html__(
2425
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2426
-                'event_espresso'
2427
-            ),
2428
-            $wpdb->last_error,
2429
-            $wpdb_method,
2430
-            wp_json_encode($arguments_to_provide)
2431
-        );
2432
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2433
-        return $error_message;
2434
-    }
2435
-
2436
-
2437
-
2438
-    /**
2439
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2440
-     * EEM_Base::$_db_verification_level
2441
-     *
2442
-     * @param $wpdb_method
2443
-     * @param $arguments_to_provide
2444
-     * @return string
2445
-     */
2446
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2447
-    {
2448
-        /** @type WPDB $wpdb */
2449
-        global $wpdb;
2450
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2451
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2452
-        $error_message = sprintf(
2453
-            esc_html__(
2454
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2455
-                'event_espresso'
2456
-            ),
2457
-            $wpdb->last_error,
2458
-            $wpdb_method,
2459
-            wp_json_encode($arguments_to_provide)
2460
-        );
2461
-        EE_System::instance()->initialize_addons();
2462
-        return $error_message;
2463
-    }
2464
-
2465
-
2466
-
2467
-    /**
2468
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2469
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2470
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2471
-     * ..."
2472
-     *
2473
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2474
-     * @return string
2475
-     */
2476
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2477
-    {
2478
-        return " FROM " . $model_query_info->get_full_join_sql() .
2479
-               $model_query_info->get_where_sql() .
2480
-               $model_query_info->get_group_by_sql() .
2481
-               $model_query_info->get_having_sql() .
2482
-               $model_query_info->get_order_by_sql() .
2483
-               $model_query_info->get_limit_sql();
2484
-    }
2485
-
2486
-
2487
-
2488
-    /**
2489
-     * Set to easily debug the next X queries ran from this model.
2490
-     *
2491
-     * @param int $count
2492
-     */
2493
-    public function show_next_x_db_queries($count = 1)
2494
-    {
2495
-        $this->_show_next_x_db_queries = $count;
2496
-    }
2497
-
2498
-
2499
-
2500
-    /**
2501
-     * @param $sql_query
2502
-     */
2503
-    public function show_db_query_if_previously_requested($sql_query)
2504
-    {
2505
-        if ($this->_show_next_x_db_queries > 0) {
2506
-            echo esc_html($sql_query);
2507
-            $this->_show_next_x_db_queries--;
2508
-        }
2509
-    }
2510
-
2511
-
2512
-
2513
-    /**
2514
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2515
-     * There are the 3 cases:
2516
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2517
-     * $otherModelObject has no ID, it is first saved.
2518
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2519
-     * has no ID, it is first saved.
2520
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2521
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2522
-     * join table
2523
-     *
2524
-     * @param        EE_Base_Class                     /int $thisModelObject
2525
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2526
-     * @param string $relationName                     , key in EEM_Base::_relations
2527
-     *                                                 an attendee to a group, you also want to specify which role they
2528
-     *                                                 will have in that group. So you would use this parameter to
2529
-     *                                                 specify array('role-column-name'=>'role-id')
2530
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2531
-     *                                                 to for relation to methods that allow you to further specify
2532
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2533
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2534
-     *                                                 because these will be inserted in any new rows created as well.
2535
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2536
-     * @throws EE_Error
2537
-     */
2538
-    public function add_relationship_to(
2539
-        $id_or_obj,
2540
-        $other_model_id_or_obj,
2541
-        $relationName,
2542
-        $extra_join_model_fields_n_values = array()
2543
-    ) {
2544
-        $relation_obj = $this->related_settings_for($relationName);
2545
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2546
-    }
2547
-
2548
-
2549
-
2550
-    /**
2551
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2552
-     * There are the 3 cases:
2553
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2554
-     * error
2555
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2556
-     * an error
2557
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2558
-     *
2559
-     * @param        EE_Base_Class /int $id_or_obj
2560
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2561
-     * @param string $relationName key in EEM_Base::_relations
2562
-     * @return boolean of success
2563
-     * @throws EE_Error
2564
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2565
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2566
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2567
-     *                             because these will be inserted in any new rows created as well.
2568
-     */
2569
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2570
-    {
2571
-        $relation_obj = $this->related_settings_for($relationName);
2572
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2573
-    }
2574
-
2575
-
2576
-
2577
-    /**
2578
-     * @param mixed           $id_or_obj
2579
-     * @param string          $relationName
2580
-     * @param array           $where_query_params
2581
-     * @param EE_Base_Class[] objects to which relations were removed
2582
-     * @return \EE_Base_Class[]
2583
-     * @throws EE_Error
2584
-     */
2585
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2586
-    {
2587
-        $relation_obj = $this->related_settings_for($relationName);
2588
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2589
-    }
2590
-
2591
-
2592
-
2593
-    /**
2594
-     * Gets all the related items of the specified $model_name, using $query_params.
2595
-     * Note: by default, we remove the "default query params"
2596
-     * because we want to get even deleted items etc.
2597
-     *
2598
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2599
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2600
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2601
-     * @return EE_Base_Class[]
2602
-     * @throws EE_Error
2603
-     */
2604
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2605
-    {
2606
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2607
-        $relation_settings = $this->related_settings_for($model_name);
2608
-        return $relation_settings->get_all_related($model_obj, $query_params);
2609
-    }
2610
-
2611
-
2612
-
2613
-    /**
2614
-     * Deletes all the model objects across the relation indicated by $model_name
2615
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2616
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2617
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2618
-     *
2619
-     * @param EE_Base_Class|int|string $id_or_obj
2620
-     * @param string                   $model_name
2621
-     * @param array                    $query_params
2622
-     * @return int how many deleted
2623
-     * @throws EE_Error
2624
-     */
2625
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2626
-    {
2627
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2628
-        $relation_settings = $this->related_settings_for($model_name);
2629
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2630
-    }
2631
-
2632
-
2633
-
2634
-    /**
2635
-     * Hard deletes all the model objects across the relation indicated by $model_name
2636
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2637
-     * the model objects can't be hard deleted because of blocking related model objects,
2638
-     * just does a soft-delete on them instead.
2639
-     *
2640
-     * @param EE_Base_Class|int|string $id_or_obj
2641
-     * @param string                   $model_name
2642
-     * @param array                    $query_params
2643
-     * @return int how many deleted
2644
-     * @throws EE_Error
2645
-     */
2646
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2647
-    {
2648
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2649
-        $relation_settings = $this->related_settings_for($model_name);
2650
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2651
-    }
2652
-
2653
-
2654
-
2655
-    /**
2656
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2657
-     * unless otherwise specified in the $query_params
2658
-     *
2659
-     * @param        int             /EE_Base_Class $id_or_obj
2660
-     * @param string $model_name     like 'Event', or 'Registration'
2661
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2662
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2663
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2664
-     *                               that by the setting $distinct to TRUE;
2665
-     * @return int
2666
-     * @throws EE_Error
2667
-     */
2668
-    public function count_related(
2669
-        $id_or_obj,
2670
-        $model_name,
2671
-        $query_params = array(),
2672
-        $field_to_count = null,
2673
-        $distinct = false
2674
-    ) {
2675
-        $related_model = $this->get_related_model_obj($model_name);
2676
-        // we're just going to use the query params on the related model's normal get_all query,
2677
-        // except add a condition to say to match the current mod
2678
-        if (! isset($query_params['default_where_conditions'])) {
2679
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2680
-        }
2681
-        $this_model_name = $this->get_this_model_name();
2682
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2683
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2684
-        return $related_model->count($query_params, $field_to_count, $distinct);
2685
-    }
2686
-
2687
-
2688
-
2689
-    /**
2690
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2691
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2692
-     *
2693
-     * @param        int           /EE_Base_Class $id_or_obj
2694
-     * @param string $model_name   like 'Event', or 'Registration'
2695
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2696
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2697
-     * @return float
2698
-     * @throws EE_Error
2699
-     */
2700
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2701
-    {
2702
-        $related_model = $this->get_related_model_obj($model_name);
2703
-        if (! is_array($query_params)) {
2704
-            EE_Error::doing_it_wrong(
2705
-                'EEM_Base::sum_related',
2706
-                sprintf(
2707
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2708
-                    gettype($query_params)
2709
-                ),
2710
-                '4.6.0'
2711
-            );
2712
-            $query_params = array();
2713
-        }
2714
-        // we're just going to use the query params on the related model's normal get_all query,
2715
-        // except add a condition to say to match the current mod
2716
-        if (! isset($query_params['default_where_conditions'])) {
2717
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2718
-        }
2719
-        $this_model_name = $this->get_this_model_name();
2720
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2721
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2722
-        return $related_model->sum($query_params, $field_to_sum);
2723
-    }
2724
-
2725
-
2726
-
2727
-    /**
2728
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2729
-     * $modelObject
2730
-     *
2731
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2732
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2733
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2734
-     * @return EE_Base_Class
2735
-     * @throws EE_Error
2736
-     */
2737
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2738
-    {
2739
-        $query_params['limit'] = 1;
2740
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2741
-        if ($results) {
2742
-            return array_shift($results);
2743
-        }
2744
-        return null;
2745
-    }
2746
-
2747
-
2748
-
2749
-    /**
2750
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2751
-     *
2752
-     * @return string
2753
-     */
2754
-    public function get_this_model_name()
2755
-    {
2756
-        return str_replace("EEM_", "", get_class($this));
2757
-    }
2758
-
2759
-
2760
-
2761
-    /**
2762
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2763
-     *
2764
-     * @return EE_Any_Foreign_Model_Name_Field
2765
-     * @throws EE_Error
2766
-     */
2767
-    public function get_field_containing_related_model_name()
2768
-    {
2769
-        foreach ($this->field_settings(true) as $field) {
2770
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2771
-                $field_with_model_name = $field;
2772
-            }
2773
-        }
2774
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2775
-            throw new EE_Error(sprintf(
2776
-                esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2777
-                $this->get_this_model_name()
2778
-            ));
2779
-        }
2780
-        return $field_with_model_name;
2781
-    }
2782
-
2783
-
2784
-
2785
-    /**
2786
-     * Inserts a new entry into the database, for each table.
2787
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2788
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2789
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2790
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2791
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2792
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2793
-     *
2794
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2795
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2796
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2797
-     *                              of EEM_Base)
2798
-     * @return int|string new primary key on main table that got inserted
2799
-     * @throws EE_Error
2800
-     */
2801
-    public function insert($field_n_values)
2802
-    {
2803
-        /**
2804
-         * Filters the fields and their values before inserting an item using the models
2805
-         *
2806
-         * @param array    $fields_n_values keys are the fields and values are their new values
2807
-         * @param EEM_Base $model           the model used
2808
-         */
2809
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2810
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2811
-            $main_table = $this->_get_main_table();
2812
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2813
-            if ($new_id !== false) {
2814
-                foreach ($this->_get_other_tables() as $other_table) {
2815
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2816
-                }
2817
-            }
2818
-            /**
2819
-             * Done just after attempting to insert a new model object
2820
-             *
2821
-             * @param EEM_Base   $model           used
2822
-             * @param array      $fields_n_values fields and their values
2823
-             * @param int|string the              ID of the newly-inserted model object
2824
-             */
2825
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2826
-            return $new_id;
2827
-        }
2828
-        return false;
2829
-    }
2830
-
2831
-
2832
-
2833
-    /**
2834
-     * Checks that the result would satisfy the unique indexes on this model
2835
-     *
2836
-     * @param array  $field_n_values
2837
-     * @param string $action
2838
-     * @return boolean
2839
-     * @throws EE_Error
2840
-     */
2841
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2842
-    {
2843
-        foreach ($this->unique_indexes() as $index_name => $index) {
2844
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2845
-            if ($this->exists(array($uniqueness_where_params))) {
2846
-                EE_Error::add_error(
2847
-                    sprintf(
2848
-                        esc_html__(
2849
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2850
-                            "event_espresso"
2851
-                        ),
2852
-                        $action,
2853
-                        $this->_get_class_name(),
2854
-                        $index_name,
2855
-                        implode(",", $index->field_names()),
2856
-                        http_build_query($uniqueness_where_params)
2857
-                    ),
2858
-                    __FILE__,
2859
-                    __FUNCTION__,
2860
-                    __LINE__
2861
-                );
2862
-                return false;
2863
-            }
2864
-        }
2865
-        return true;
2866
-    }
2867
-
2868
-
2869
-
2870
-    /**
2871
-     * Checks the database for an item that conflicts (ie, if this item were
2872
-     * saved to the DB would break some uniqueness requirement, like a primary key
2873
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2874
-     * can be either an EE_Base_Class or an array of fields n values
2875
-     *
2876
-     * @param EE_Base_Class|array $obj_or_fields_array
2877
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2878
-     *                                                 when looking for conflicts
2879
-     *                                                 (ie, if false, we ignore the model object's primary key
2880
-     *                                                 when finding "conflicts". If true, it's also considered).
2881
-     *                                                 Only works for INT primary key,
2882
-     *                                                 STRING primary keys cannot be ignored
2883
-     * @throws EE_Error
2884
-     * @return EE_Base_Class|array
2885
-     */
2886
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2887
-    {
2888
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2889
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2890
-        } elseif (is_array($obj_or_fields_array)) {
2891
-            $fields_n_values = $obj_or_fields_array;
2892
-        } else {
2893
-            throw new EE_Error(
2894
-                sprintf(
2895
-                    esc_html__(
2896
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2897
-                        "event_espresso"
2898
-                    ),
2899
-                    get_class($this),
2900
-                    $obj_or_fields_array
2901
-                )
2902
-            );
2903
-        }
2904
-        $query_params = array();
2905
-        if (
2906
-            $this->has_primary_key_field()
2907
-            && ($include_primary_key
2908
-                || $this->get_primary_key_field()
2909
-                   instanceof
2910
-                   EE_Primary_Key_String_Field)
2911
-            && isset($fields_n_values[ $this->primary_key_name() ])
2912
-        ) {
2913
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2914
-        }
2915
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2916
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2917
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2918
-        }
2919
-        // if there is nothing to base this search on, then we shouldn't find anything
2920
-        if (empty($query_params)) {
2921
-            return array();
2922
-        }
2923
-        return $this->get_one($query_params);
2924
-    }
2925
-
2926
-
2927
-
2928
-    /**
2929
-     * Like count, but is optimized and returns a boolean instead of an int
2930
-     *
2931
-     * @param array $query_params
2932
-     * @return boolean
2933
-     * @throws EE_Error
2934
-     */
2935
-    public function exists($query_params)
2936
-    {
2937
-        $query_params['limit'] = 1;
2938
-        return $this->count($query_params) > 0;
2939
-    }
2940
-
2941
-
2942
-
2943
-    /**
2944
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2945
-     *
2946
-     * @param int|string $id
2947
-     * @return boolean
2948
-     * @throws EE_Error
2949
-     */
2950
-    public function exists_by_ID($id)
2951
-    {
2952
-        return $this->exists(
2953
-            array(
2954
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2955
-                array(
2956
-                    $this->primary_key_name() => $id,
2957
-                ),
2958
-            )
2959
-        );
2960
-    }
2961
-
2962
-
2963
-
2964
-    /**
2965
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2966
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2967
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2968
-     * on the main table)
2969
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2970
-     * cases where we want to call it directly rather than via insert().
2971
-     *
2972
-     * @access   protected
2973
-     * @param EE_Table_Base $table
2974
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2975
-     *                                       float
2976
-     * @param int           $new_id          for now we assume only int keys
2977
-     * @throws EE_Error
2978
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2979
-     * @return int ID of new row inserted, or FALSE on failure
2980
-     */
2981
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2982
-    {
2983
-        global $wpdb;
2984
-        $insertion_col_n_values = array();
2985
-        $format_for_insertion = array();
2986
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2987
-        foreach ($fields_on_table as $field_name => $field_obj) {
2988
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2989
-            if ($field_obj->is_auto_increment()) {
2990
-                continue;
2991
-            }
2992
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2993
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2994
-            if ($prepared_value !== null) {
2995
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2996
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2997
-            }
2998
-        }
2999
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3000
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3001
-            // so add the fk to the main table as a column
3002
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3003
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3004
-        }
3005
-        // insert the new entry
3006
-        $result = $this->_do_wpdb_query(
3007
-            'insert',
3008
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3009
-        );
3010
-        if ($result === false) {
3011
-            return false;
3012
-        }
3013
-        // ok, now what do we return for the ID of the newly-inserted thing?
3014
-        if ($this->has_primary_key_field()) {
3015
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3016
-                return $wpdb->insert_id;
3017
-            }
3018
-            // it's not an auto-increment primary key, so
3019
-            // it must have been supplied
3020
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3021
-        }
3022
-        // we can't return a  primary key because there is none. instead return
3023
-        // a unique string indicating this model
3024
-        return $this->get_index_primary_key_string($fields_n_values);
3025
-    }
3026
-
3027
-
3028
-
3029
-    /**
3030
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3031
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3032
-     * and there is no default, we pass it along. WPDB will take care of it)
3033
-     *
3034
-     * @param EE_Model_Field_Base $field_obj
3035
-     * @param array               $fields_n_values
3036
-     * @return mixed string|int|float depending on what the table column will be expecting
3037
-     * @throws EE_Error
3038
-     */
3039
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3040
-    {
3041
-        // if this field doesn't allow nullable, don't allow it
3042
-        if (
3043
-            ! $field_obj->is_nullable()
3044
-            && (
3045
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3046
-                || $fields_n_values[ $field_obj->get_name() ] === null
3047
-            )
3048
-        ) {
3049
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3050
-        }
3051
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3052
-            ? $fields_n_values[ $field_obj->get_name() ]
3053
-            : null;
3054
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3055
-    }
3056
-
3057
-
3058
-
3059
-    /**
3060
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3061
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3062
-     * the field's prepare_for_set() method.
3063
-     *
3064
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3065
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3066
-     *                                   top of file)
3067
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3068
-     *                                   $value is a custom selection
3069
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3070
-     */
3071
-    private function _prepare_value_for_use_in_db($value, $field)
3072
-    {
3073
-        if ($field && $field instanceof EE_Model_Field_Base) {
3074
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3075
-            switch ($this->_values_already_prepared_by_model_object) {
3076
-                /** @noinspection PhpMissingBreakStatementInspection */
3077
-                case self::not_prepared_by_model_object:
3078
-                    $value = $field->prepare_for_set($value);
3079
-                // purposefully left out "return"
3080
-                case self::prepared_by_model_object:
3081
-                    /** @noinspection SuspiciousAssignmentsInspection */
3082
-                    $value = $field->prepare_for_use_in_db($value);
3083
-                case self::prepared_for_use_in_db:
3084
-                    // leave the value alone
3085
-            }
3086
-            return $value;
3087
-            // phpcs:enable
3088
-        }
3089
-        return $value;
3090
-    }
3091
-
3092
-
3093
-
3094
-    /**
3095
-     * Returns the main table on this model
3096
-     *
3097
-     * @return EE_Primary_Table
3098
-     * @throws EE_Error
3099
-     */
3100
-    protected function _get_main_table()
3101
-    {
3102
-        foreach ($this->_tables as $table) {
3103
-            if ($table instanceof EE_Primary_Table) {
3104
-                return $table;
3105
-            }
3106
-        }
3107
-        throw new EE_Error(sprintf(esc_html__(
3108
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3109
-            'event_espresso'
3110
-        ), get_class($this)));
3111
-    }
3112
-
3113
-
3114
-
3115
-    /**
3116
-     * table
3117
-     * returns EE_Primary_Table table name
3118
-     *
3119
-     * @return string
3120
-     * @throws EE_Error
3121
-     */
3122
-    public function table()
3123
-    {
3124
-        return $this->_get_main_table()->get_table_name();
3125
-    }
3126
-
3127
-
3128
-
3129
-    /**
3130
-     * table
3131
-     * returns first EE_Secondary_Table table name
3132
-     *
3133
-     * @return string
3134
-     */
3135
-    public function second_table()
3136
-    {
3137
-        // grab second table from tables array
3138
-        $second_table = end($this->_tables);
3139
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3140
-    }
3141
-
3142
-
3143
-
3144
-    /**
3145
-     * get_table_obj_by_alias
3146
-     * returns table name given it's alias
3147
-     *
3148
-     * @param string $table_alias
3149
-     * @return EE_Primary_Table | EE_Secondary_Table
3150
-     */
3151
-    public function get_table_obj_by_alias($table_alias = '')
3152
-    {
3153
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3154
-    }
3155
-
3156
-
3157
-
3158
-    /**
3159
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3160
-     *
3161
-     * @return EE_Secondary_Table[]
3162
-     */
3163
-    protected function _get_other_tables()
3164
-    {
3165
-        $other_tables = array();
3166
-        foreach ($this->_tables as $table_alias => $table) {
3167
-            if ($table instanceof EE_Secondary_Table) {
3168
-                $other_tables[ $table_alias ] = $table;
3169
-            }
3170
-        }
3171
-        return $other_tables;
3172
-    }
3173
-
3174
-
3175
-
3176
-    /**
3177
-     * Finds all the fields that correspond to the given table
3178
-     *
3179
-     * @param string $table_alias , array key in EEM_Base::_tables
3180
-     * @return EE_Model_Field_Base[]
3181
-     */
3182
-    public function _get_fields_for_table($table_alias)
3183
-    {
3184
-        return $this->_fields[ $table_alias ];
3185
-    }
3186
-
3187
-
3188
-
3189
-    /**
3190
-     * Recurses through all the where parameters, and finds all the related models we'll need
3191
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3192
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3193
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3194
-     * related Registration, Transaction, and Payment models.
3195
-     *
3196
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3197
-     * @return EE_Model_Query_Info_Carrier
3198
-     * @throws EE_Error
3199
-     */
3200
-    public function _extract_related_models_from_query($query_params)
3201
-    {
3202
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3203
-        if (array_key_exists(0, $query_params)) {
3204
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3205
-        }
3206
-        if (array_key_exists('group_by', $query_params)) {
3207
-            if (is_array($query_params['group_by'])) {
3208
-                $this->_extract_related_models_from_sub_params_array_values(
3209
-                    $query_params['group_by'],
3210
-                    $query_info_carrier,
3211
-                    'group_by'
3212
-                );
3213
-            } elseif (! empty($query_params['group_by'])) {
3214
-                $this->_extract_related_model_info_from_query_param(
3215
-                    $query_params['group_by'],
3216
-                    $query_info_carrier,
3217
-                    'group_by'
3218
-                );
3219
-            }
3220
-        }
3221
-        if (array_key_exists('having', $query_params)) {
3222
-            $this->_extract_related_models_from_sub_params_array_keys(
3223
-                $query_params[0],
3224
-                $query_info_carrier,
3225
-                'having'
3226
-            );
3227
-        }
3228
-        if (array_key_exists('order_by', $query_params)) {
3229
-            if (is_array($query_params['order_by'])) {
3230
-                $this->_extract_related_models_from_sub_params_array_keys(
3231
-                    $query_params['order_by'],
3232
-                    $query_info_carrier,
3233
-                    'order_by'
3234
-                );
3235
-            } elseif (! empty($query_params['order_by'])) {
3236
-                $this->_extract_related_model_info_from_query_param(
3237
-                    $query_params['order_by'],
3238
-                    $query_info_carrier,
3239
-                    'order_by'
3240
-                );
3241
-            }
3242
-        }
3243
-        if (array_key_exists('force_join', $query_params)) {
3244
-            $this->_extract_related_models_from_sub_params_array_values(
3245
-                $query_params['force_join'],
3246
-                $query_info_carrier,
3247
-                'force_join'
3248
-            );
3249
-        }
3250
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3251
-        return $query_info_carrier;
3252
-    }
3253
-
3254
-
3255
-
3256
-    /**
3257
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3258
-     *
3259
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3260
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3261
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3262
-     * @throws EE_Error
3263
-     * @return \EE_Model_Query_Info_Carrier
3264
-     */
3265
-    private function _extract_related_models_from_sub_params_array_keys(
3266
-        $sub_query_params,
3267
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3268
-        $query_param_type
3269
-    ) {
3270
-        if (! empty($sub_query_params)) {
3271
-            $sub_query_params = (array) $sub_query_params;
3272
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3273
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3274
-                $this->_extract_related_model_info_from_query_param(
3275
-                    $param,
3276
-                    $model_query_info_carrier,
3277
-                    $query_param_type
3278
-                );
3279
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3280
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3281
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3282
-                // of array('Registration.TXN_ID'=>23)
3283
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
-                    if (! is_array($possibly_array_of_params)) {
3286
-                        throw new EE_Error(sprintf(
3287
-                            esc_html__(
3288
-                                "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'))",
3289
-                                "event_espresso"
3290
-                            ),
3291
-                            $param,
3292
-                            $possibly_array_of_params
3293
-                        ));
3294
-                    }
3295
-                    $this->_extract_related_models_from_sub_params_array_keys(
3296
-                        $possibly_array_of_params,
3297
-                        $model_query_info_carrier,
3298
-                        $query_param_type
3299
-                    );
3300
-                } elseif (
3301
-                    $query_param_type === 0 // ie WHERE
3302
-                          && is_array($possibly_array_of_params)
3303
-                          && isset($possibly_array_of_params[2])
3304
-                          && $possibly_array_of_params[2] == true
3305
-                ) {
3306
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3307
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3308
-                    // from which we should extract query parameters!
3309
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3310
-                        throw new EE_Error(sprintf(esc_html__(
3311
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3312
-                            "event_espresso"
3313
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3314
-                    }
3315
-                    $this->_extract_related_model_info_from_query_param(
3316
-                        $possibly_array_of_params[1],
3317
-                        $model_query_info_carrier,
3318
-                        $query_param_type
3319
-                    );
3320
-                }
3321
-            }
3322
-        }
3323
-        return $model_query_info_carrier;
3324
-    }
3325
-
3326
-
3327
-
3328
-    /**
3329
-     * For extracting related models from forced_joins, where the array values contain the info about what
3330
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3331
-     *
3332
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3333
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3334
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3335
-     * @throws EE_Error
3336
-     * @return \EE_Model_Query_Info_Carrier
3337
-     */
3338
-    private function _extract_related_models_from_sub_params_array_values(
3339
-        $sub_query_params,
3340
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3341
-        $query_param_type
3342
-    ) {
3343
-        if (! empty($sub_query_params)) {
3344
-            if (! is_array($sub_query_params)) {
3345
-                throw new EE_Error(sprintf(
3346
-                    esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3347
-                    $sub_query_params
3348
-                ));
3349
-            }
3350
-            foreach ($sub_query_params as $param) {
3351
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3352
-                $this->_extract_related_model_info_from_query_param(
3353
-                    $param,
3354
-                    $model_query_info_carrier,
3355
-                    $query_param_type
3356
-                );
3357
-            }
3358
-        }
3359
-        return $model_query_info_carrier;
3360
-    }
3361
-
3362
-
3363
-    /**
3364
-     * Extract all the query parts from  model query params
3365
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3366
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3367
-     * but use them in a different order. Eg, we need to know what models we are querying
3368
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3369
-     * other models before we can finalize the where clause SQL.
3370
-     *
3371
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3372
-     * @throws EE_Error
3373
-     * @return EE_Model_Query_Info_Carrier
3374
-     * @throws ModelConfigurationException
3375
-     */
3376
-    public function _create_model_query_info_carrier($query_params)
3377
-    {
3378
-        if (! is_array($query_params)) {
3379
-            EE_Error::doing_it_wrong(
3380
-                'EEM_Base::_create_model_query_info_carrier',
3381
-                sprintf(
3382
-                    esc_html__(
3383
-                        '$query_params should be an array, you passed a variable of type %s',
3384
-                        'event_espresso'
3385
-                    ),
3386
-                    gettype($query_params)
3387
-                ),
3388
-                '4.6.0'
3389
-            );
3390
-            $query_params = array();
3391
-        }
3392
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3393
-        // first check if we should alter the query to account for caps or not
3394
-        // because the caps might require us to do extra joins
3395
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3396
-            $query_params[0] = array_replace_recursive(
3397
-                $query_params[0],
3398
-                $this->caps_where_conditions(
3399
-                    $query_params['caps']
3400
-                )
3401
-            );
3402
-        }
3403
-
3404
-        // check if we should alter the query to remove data related to protected
3405
-        // custom post types
3406
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3407
-            $where_param_key_for_password = $this->modelChainAndPassword();
3408
-            // only include if related to a cpt where no password has been set
3409
-            $query_params[0]['OR*nopassword'] = array(
3410
-                $where_param_key_for_password => '',
3411
-                $where_param_key_for_password . '*' => array('IS_NULL')
3412
-            );
3413
-        }
3414
-        $query_object = $this->_extract_related_models_from_query($query_params);
3415
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3416
-        foreach ($query_params[0] as $key => $value) {
3417
-            if (is_int($key)) {
3418
-                throw new EE_Error(
3419
-                    sprintf(
3420
-                        esc_html__(
3421
-                            "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.",
3422
-                            "event_espresso"
3423
-                        ),
3424
-                        $key,
3425
-                        var_export($value, true),
3426
-                        var_export($query_params, true),
3427
-                        get_class($this)
3428
-                    )
3429
-                );
3430
-            }
3431
-        }
3432
-        if (
3433
-            array_key_exists('default_where_conditions', $query_params)
3434
-            && ! empty($query_params['default_where_conditions'])
3435
-        ) {
3436
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3437
-        } else {
3438
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3439
-        }
3440
-        $query_params[0] = array_merge(
3441
-            $this->_get_default_where_conditions_for_models_in_query(
3442
-                $query_object,
3443
-                $use_default_where_conditions,
3444
-                $query_params[0]
3445
-            ),
3446
-            $query_params[0]
3447
-        );
3448
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3449
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3450
-        // So we need to setup a subquery and use that for the main join.
3451
-        // Note for now this only works on the primary table for the model.
3452
-        // So for instance, you could set the limit array like this:
3453
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3454
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3455
-            $query_object->set_main_model_join_sql(
3456
-                $this->_construct_limit_join_select(
3457
-                    $query_params['on_join_limit'][0],
3458
-                    $query_params['on_join_limit'][1]
3459
-                )
3460
-            );
3461
-        }
3462
-        // set limit
3463
-        if (array_key_exists('limit', $query_params)) {
3464
-            if (is_array($query_params['limit'])) {
3465
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3466
-                    $e = sprintf(
3467
-                        esc_html__(
3468
-                            "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)",
3469
-                            "event_espresso"
3470
-                        ),
3471
-                        http_build_query($query_params['limit'])
3472
-                    );
3473
-                    throw new EE_Error($e . "|" . $e);
3474
-                }
3475
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3476
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3477
-            } elseif (! empty($query_params['limit'])) {
3478
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3479
-            }
3480
-        }
3481
-        // set order by
3482
-        if (array_key_exists('order_by', $query_params)) {
3483
-            if (is_array($query_params['order_by'])) {
3484
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3485
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3486
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3487
-                if (array_key_exists('order', $query_params)) {
3488
-                    throw new EE_Error(
3489
-                        sprintf(
3490
-                            esc_html__(
3491
-                                "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 ",
3492
-                                "event_espresso"
3493
-                            ),
3494
-                            get_class($this),
3495
-                            implode(", ", array_keys($query_params['order_by'])),
3496
-                            implode(", ", $query_params['order_by']),
3497
-                            $query_params['order']
3498
-                        )
3499
-                    );
3500
-                }
3501
-                $this->_extract_related_models_from_sub_params_array_keys(
3502
-                    $query_params['order_by'],
3503
-                    $query_object,
3504
-                    'order_by'
3505
-                );
3506
-                // assume it's an array of fields to order by
3507
-                $order_array = array();
3508
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3509
-                    $order = $this->_extract_order($order);
3510
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3511
-                }
3512
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3513
-            } elseif (! empty($query_params['order_by'])) {
3514
-                $this->_extract_related_model_info_from_query_param(
3515
-                    $query_params['order_by'],
3516
-                    $query_object,
3517
-                    'order',
3518
-                    $query_params['order_by']
3519
-                );
3520
-                $order = isset($query_params['order'])
3521
-                    ? $this->_extract_order($query_params['order'])
3522
-                    : 'DESC';
3523
-                $query_object->set_order_by_sql(
3524
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3525
-                );
3526
-            }
3527
-        }
3528
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3529
-        if (
3530
-            ! array_key_exists('order_by', $query_params)
3531
-            && array_key_exists('order', $query_params)
3532
-            && ! empty($query_params['order'])
3533
-        ) {
3534
-            $pk_field = $this->get_primary_key_field();
3535
-            $order = $this->_extract_order($query_params['order']);
3536
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3537
-        }
3538
-        // set group by
3539
-        if (array_key_exists('group_by', $query_params)) {
3540
-            if (is_array($query_params['group_by'])) {
3541
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3542
-                $group_by_array = array();
3543
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3544
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3545
-                }
3546
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3547
-            } elseif (! empty($query_params['group_by'])) {
3548
-                $query_object->set_group_by_sql(
3549
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3550
-                );
3551
-            }
3552
-        }
3553
-        // set having
3554
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3555
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3556
-        }
3557
-        // now, just verify they didn't pass anything wack
3558
-        foreach ($query_params as $query_key => $query_value) {
3559
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3560
-                throw new EE_Error(
3561
-                    sprintf(
3562
-                        esc_html__(
3563
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3564
-                            'event_espresso'
3565
-                        ),
3566
-                        $query_key,
3567
-                        get_class($this),
3568
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3569
-                        implode(',', $this->_allowed_query_params)
3570
-                    )
3571
-                );
3572
-            }
3573
-        }
3574
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3575
-        if (empty($main_model_join_sql)) {
3576
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3577
-        }
3578
-        return $query_object;
3579
-    }
3580
-
3581
-
3582
-
3583
-    /**
3584
-     * Gets the where conditions that should be imposed on the query based on the
3585
-     * context (eg reading frontend, backend, edit or delete).
3586
-     *
3587
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3588
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3589
-     * @throws EE_Error
3590
-     */
3591
-    public function caps_where_conditions($context = self::caps_read)
3592
-    {
3593
-        EEM_Base::verify_is_valid_cap_context($context);
3594
-        $cap_where_conditions = array();
3595
-        $cap_restrictions = $this->caps_missing($context);
3596
-        /**
3597
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3598
-         */
3599
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3600
-            $cap_where_conditions = array_replace_recursive(
3601
-                $cap_where_conditions,
3602
-                $restriction_if_no_cap->get_default_where_conditions()
3603
-            );
3604
-        }
3605
-        return apply_filters(
3606
-            'FHEE__EEM_Base__caps_where_conditions__return',
3607
-            $cap_where_conditions,
3608
-            $this,
3609
-            $context,
3610
-            $cap_restrictions
3611
-        );
3612
-    }
3613
-
3614
-
3615
-
3616
-    /**
3617
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3618
-     * otherwise throws an exception
3619
-     *
3620
-     * @param string $should_be_order_string
3621
-     * @return string either ASC, asc, DESC or desc
3622
-     * @throws EE_Error
3623
-     */
3624
-    private function _extract_order($should_be_order_string)
3625
-    {
3626
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3627
-            return $should_be_order_string;
3628
-        }
3629
-        throw new EE_Error(
3630
-            sprintf(
3631
-                esc_html__(
3632
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3633
-                    "event_espresso"
3634
-                ),
3635
-                get_class($this),
3636
-                $should_be_order_string
3637
-            )
3638
-        );
3639
-    }
3640
-
3641
-
3642
-
3643
-    /**
3644
-     * Looks at all the models which are included in this query, and asks each
3645
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3646
-     * so they can be merged
3647
-     *
3648
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3649
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3650
-     *                                                                  'none' means NO default where conditions will
3651
-     *                                                                  be used AT ALL during this query.
3652
-     *                                                                  'other_models_only' means default where
3653
-     *                                                                  conditions from other models will be used, but
3654
-     *                                                                  not for this primary model. 'all', the default,
3655
-     *                                                                  means default where conditions will apply as
3656
-     *                                                                  normal
3657
-     * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3658
-     * @throws EE_Error
3659
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3660
-     */
3661
-    private function _get_default_where_conditions_for_models_in_query(
3662
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3663
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3664
-        $where_query_params = array()
3665
-    ) {
3666
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3667
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3668
-            throw new EE_Error(sprintf(
3669
-                esc_html__(
3670
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3671
-                    "event_espresso"
3672
-                ),
3673
-                $use_default_where_conditions,
3674
-                implode(", ", $allowed_used_default_where_conditions_values)
3675
-            ));
3676
-        }
3677
-        $universal_query_params = array();
3678
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3679
-            $universal_query_params = $this->_get_default_where_conditions();
3680
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3681
-            $universal_query_params = $this->_get_minimum_where_conditions();
3682
-        }
3683
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3684
-            $related_model = $this->get_related_model_obj($model_name);
3685
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3686
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3687
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3688
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3689
-            } else {
3690
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3691
-                continue;
3692
-            }
3693
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3694
-                $related_model_universal_where_params,
3695
-                $where_query_params,
3696
-                $related_model,
3697
-                $model_relation_path
3698
-            );
3699
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3700
-                $universal_query_params,
3701
-                $overrides
3702
-            );
3703
-        }
3704
-        return $universal_query_params;
3705
-    }
3706
-
3707
-
3708
-
3709
-    /**
3710
-     * Determines whether or not we should use default where conditions for the model in question
3711
-     * (this model, or other related models).
3712
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3713
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3714
-     * We should use default where conditions on related models when they requested to use default where conditions
3715
-     * on all models, or specifically just on other related models
3716
-     * @param      $default_where_conditions_value
3717
-     * @param bool $for_this_model false means this is for OTHER related models
3718
-     * @return bool
3719
-     */
3720
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3721
-    {
3722
-        return (
3723
-                   $for_this_model
3724
-                   && in_array(
3725
-                       $default_where_conditions_value,
3726
-                       array(
3727
-                           EEM_Base::default_where_conditions_all,
3728
-                           EEM_Base::default_where_conditions_this_only,
3729
-                           EEM_Base::default_where_conditions_minimum_others,
3730
-                       ),
3731
-                       true
3732
-                   )
3733
-               )
3734
-               || (
3735
-                   ! $for_this_model
3736
-                   && in_array(
3737
-                       $default_where_conditions_value,
3738
-                       array(
3739
-                           EEM_Base::default_where_conditions_all,
3740
-                           EEM_Base::default_where_conditions_others_only,
3741
-                       ),
3742
-                       true
3743
-                   )
3744
-               );
3745
-    }
3746
-
3747
-    /**
3748
-     * Determines whether or not we should use default minimum conditions for the model in question
3749
-     * (this model, or other related models).
3750
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3751
-     * where conditions.
3752
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3753
-     * on this model or others
3754
-     * @param      $default_where_conditions_value
3755
-     * @param bool $for_this_model false means this is for OTHER related models
3756
-     * @return bool
3757
-     */
3758
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3759
-    {
3760
-        return (
3761
-                   $for_this_model
3762
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3763
-               )
3764
-               || (
3765
-                   ! $for_this_model
3766
-                   && in_array(
3767
-                       $default_where_conditions_value,
3768
-                       array(
3769
-                           EEM_Base::default_where_conditions_minimum_others,
3770
-                           EEM_Base::default_where_conditions_minimum_all,
3771
-                       ),
3772
-                       true
3773
-                   )
3774
-               );
3775
-    }
3776
-
3777
-
3778
-    /**
3779
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3780
-     * then we also add a special where condition which allows for that model's primary key
3781
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3782
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3783
-     *
3784
-     * @param array    $default_where_conditions
3785
-     * @param array    $provided_where_conditions
3786
-     * @param EEM_Base $model
3787
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3788
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3789
-     * @throws EE_Error
3790
-     */
3791
-    private function _override_defaults_or_make_null_friendly(
3792
-        $default_where_conditions,
3793
-        $provided_where_conditions,
3794
-        $model,
3795
-        $model_relation_path
3796
-    ) {
3797
-        $null_friendly_where_conditions = array();
3798
-        $none_overridden = true;
3799
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3800
-        foreach ($default_where_conditions as $key => $val) {
3801
-            if (isset($provided_where_conditions[ $key ])) {
3802
-                $none_overridden = false;
3803
-            } else {
3804
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3805
-            }
3806
-        }
3807
-        if ($none_overridden && $default_where_conditions) {
3808
-            if ($model->has_primary_key_field()) {
3809
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3810
-                                                                                . "."
3811
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3812
-            }/*else{
39
+	/**
40
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
41
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
42
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
43
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
44
+	 *
45
+	 * @var boolean
46
+	 */
47
+	private $_values_already_prepared_by_model_object = 0;
48
+
49
+	/**
50
+	 * when $_values_already_prepared_by_model_object equals this, we assume
51
+	 * the data is just like form input that needs to have the model fields'
52
+	 * prepare_for_set and prepare_for_use_in_db called on it
53
+	 */
54
+	const not_prepared_by_model_object = 0;
55
+
56
+	/**
57
+	 * when $_values_already_prepared_by_model_object equals this, we
58
+	 * assume this value is coming from a model object and doesn't need to have
59
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
60
+	 */
61
+	const prepared_by_model_object = 1;
62
+
63
+	/**
64
+	 * when $_values_already_prepared_by_model_object equals this, we assume
65
+	 * the values are already to be used in the database (ie no processing is done
66
+	 * on them by the model's fields)
67
+	 */
68
+	const prepared_for_use_in_db = 2;
69
+
70
+
71
+	protected $singular_item = 'Item';
72
+
73
+	protected $plural_item   = 'Items';
74
+
75
+	/**
76
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
77
+	 */
78
+	protected $_tables;
79
+
80
+	/**
81
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
82
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
83
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
84
+	 *
85
+	 * @var \EE_Model_Field_Base[][] $_fields
86
+	 */
87
+	protected $_fields;
88
+
89
+	/**
90
+	 * array of different kinds of relations
91
+	 *
92
+	 * @var \EE_Model_Relation_Base[] $_model_relations
93
+	 */
94
+	protected $_model_relations;
95
+
96
+	/**
97
+	 * @var \EE_Index[] $_indexes
98
+	 */
99
+	protected $_indexes = array();
100
+
101
+	/**
102
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
103
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
104
+	 * by setting the same columns as used in these queries in the query yourself.
105
+	 *
106
+	 * @var EE_Default_Where_Conditions
107
+	 */
108
+	protected $_default_where_conditions_strategy;
109
+
110
+	/**
111
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
112
+	 * This is particularly useful when you want something between 'none' and 'default'
113
+	 *
114
+	 * @var EE_Default_Where_Conditions
115
+	 */
116
+	protected $_minimum_where_conditions_strategy;
117
+
118
+	/**
119
+	 * String describing how to find the "owner" of this model's objects.
120
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
121
+	 * But when there isn't, this indicates which related model, or transiently-related model,
122
+	 * has the foreign key to the wp_users table.
123
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
124
+	 * related to events, and events have a foreign key to wp_users.
125
+	 * On EEM_Transaction, this would be 'Transaction.Event'
126
+	 *
127
+	 * @var string
128
+	 */
129
+	protected $_model_chain_to_wp_user = '';
130
+
131
+	/**
132
+	 * String describing how to find the model with a password controlling access to this model. This property has the
133
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
134
+	 * This value is the path of models to follow to arrive at the model with the password field.
135
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
136
+	 * model with a password that should affect reading this on the front-end.
137
+	 * Eg this is an empty string for the Event model because it has a password.
138
+	 * This is null for the Registration model, because its event's password has no bearing on whether
139
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
140
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
141
+	 * should hide tickets for datetimes for events that have a password set.
142
+	 * @var string |null
143
+	 */
144
+	protected $model_chain_to_password = null;
145
+
146
+	/**
147
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
148
+	 * don't need it (particularly CPT models)
149
+	 *
150
+	 * @var bool
151
+	 */
152
+	protected $_ignore_where_strategy = false;
153
+
154
+	/**
155
+	 * String used in caps relating to this model. Eg, if the caps relating to this
156
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
157
+	 *
158
+	 * @var string. If null it hasn't been initialized yet. If false then we
159
+	 * have indicated capabilities don't apply to this
160
+	 */
161
+	protected $_caps_slug = null;
162
+
163
+	/**
164
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
165
+	 * and next-level keys are capability names, and each's value is a
166
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
167
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
168
+	 * and then each capability in the corresponding sub-array that they're missing
169
+	 * adds the where conditions onto the query.
170
+	 *
171
+	 * @var array
172
+	 */
173
+	protected $_cap_restrictions = array(
174
+		self::caps_read       => array(),
175
+		self::caps_read_admin => array(),
176
+		self::caps_edit       => array(),
177
+		self::caps_delete     => array(),
178
+	);
179
+
180
+	/**
181
+	 * Array defining which cap restriction generators to use to create default
182
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
183
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
184
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
185
+	 * automatically set this to false (not just null).
186
+	 *
187
+	 * @var EE_Restriction_Generator_Base[]
188
+	 */
189
+	protected $_cap_restriction_generators = array();
190
+
191
+	/**
192
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
193
+	 */
194
+	const caps_read       = 'read';
195
+
196
+	const caps_read_admin = 'read_admin';
197
+
198
+	const caps_edit       = 'edit';
199
+
200
+	const caps_delete     = 'delete';
201
+
202
+	/**
203
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
204
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
205
+	 * maps to 'read' because when looking for relevant permissions we're going to use
206
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
207
+	 *
208
+	 * @var array
209
+	 */
210
+	protected $_cap_contexts_to_cap_action_map = array(
211
+		self::caps_read       => 'read',
212
+		self::caps_read_admin => 'read',
213
+		self::caps_edit       => 'edit',
214
+		self::caps_delete     => 'delete',
215
+	);
216
+
217
+	/**
218
+	 * Timezone
219
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
220
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
221
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
222
+	 * EE_Datetime_Field data type will have access to it.
223
+	 *
224
+	 * @var string
225
+	 */
226
+	protected $_timezone;
227
+
228
+
229
+	/**
230
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
231
+	 * multisite.
232
+	 *
233
+	 * @var int
234
+	 */
235
+	protected static $_model_query_blog_id;
236
+
237
+	/**
238
+	 * A copy of _fields, except the array keys are the model names pointed to by
239
+	 * the field
240
+	 *
241
+	 * @var EE_Model_Field_Base[]
242
+	 */
243
+	private $_cache_foreign_key_to_fields = array();
244
+
245
+	/**
246
+	 * Cached list of all the fields on the model, indexed by their name
247
+	 *
248
+	 * @var EE_Model_Field_Base[]
249
+	 */
250
+	private $_cached_fields = null;
251
+
252
+	/**
253
+	 * Cached list of all the fields on the model, except those that are
254
+	 * marked as only pertinent to the database
255
+	 *
256
+	 * @var EE_Model_Field_Base[]
257
+	 */
258
+	private $_cached_fields_non_db_only = null;
259
+
260
+	/**
261
+	 * A cached reference to the primary key for quick lookup
262
+	 *
263
+	 * @var EE_Model_Field_Base
264
+	 */
265
+	private $_primary_key_field = null;
266
+
267
+	/**
268
+	 * Flag indicating whether this model has a primary key or not
269
+	 *
270
+	 * @var boolean
271
+	 */
272
+	protected $_has_primary_key_field = null;
273
+
274
+	/**
275
+	 * array in the format:  [ FK alias => full PK ]
276
+	 * where keys are local column name aliases for foreign keys
277
+	 * and values are the fully qualified column name for the primary key they represent
278
+	 *  ex:
279
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
280
+	 *
281
+	 * @var array $foreign_key_aliases
282
+	 */
283
+	protected $foreign_key_aliases = [];
284
+
285
+	/**
286
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
287
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
288
+	 * This should be true for models that deal with data that should exist independent of EE.
289
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
290
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
291
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
292
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
293
+	 * @var boolean
294
+	 */
295
+	protected $_wp_core_model = false;
296
+
297
+	/**
298
+	 * @var bool stores whether this model has a password field or not.
299
+	 * null until initialized by hasPasswordField()
300
+	 */
301
+	protected $has_password_field;
302
+
303
+	/**
304
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
305
+	 */
306
+	protected $password_field;
307
+
308
+	/**
309
+	 *    List of valid operators that can be used for querying.
310
+	 * The keys are all operators we'll accept, the values are the real SQL
311
+	 * operators used
312
+	 *
313
+	 * @var array
314
+	 */
315
+	protected $_valid_operators = array(
316
+		'='           => '=',
317
+		'<='          => '<=',
318
+		'<'           => '<',
319
+		'>='          => '>=',
320
+		'>'           => '>',
321
+		'!='          => '!=',
322
+		'LIKE'        => 'LIKE',
323
+		'like'        => 'LIKE',
324
+		'NOT_LIKE'    => 'NOT LIKE',
325
+		'not_like'    => 'NOT LIKE',
326
+		'NOT LIKE'    => 'NOT LIKE',
327
+		'not like'    => 'NOT LIKE',
328
+		'IN'          => 'IN',
329
+		'in'          => 'IN',
330
+		'NOT_IN'      => 'NOT IN',
331
+		'not_in'      => 'NOT IN',
332
+		'NOT IN'      => 'NOT IN',
333
+		'not in'      => 'NOT IN',
334
+		'between'     => 'BETWEEN',
335
+		'BETWEEN'     => 'BETWEEN',
336
+		'IS_NOT_NULL' => 'IS NOT NULL',
337
+		'is_not_null' => 'IS NOT NULL',
338
+		'IS NOT NULL' => 'IS NOT NULL',
339
+		'is not null' => 'IS NOT NULL',
340
+		'IS_NULL'     => 'IS NULL',
341
+		'is_null'     => 'IS NULL',
342
+		'IS NULL'     => 'IS NULL',
343
+		'is null'     => 'IS NULL',
344
+		'REGEXP'      => 'REGEXP',
345
+		'regexp'      => 'REGEXP',
346
+		'NOT_REGEXP'  => 'NOT REGEXP',
347
+		'not_regexp'  => 'NOT REGEXP',
348
+		'NOT REGEXP'  => 'NOT REGEXP',
349
+		'not regexp'  => 'NOT REGEXP',
350
+	);
351
+
352
+	/**
353
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
354
+	 *
355
+	 * @var array
356
+	 */
357
+	protected $_in_style_operators = array('IN', 'NOT IN');
358
+
359
+	/**
360
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
361
+	 * '12-31-2012'"
362
+	 *
363
+	 * @var array
364
+	 */
365
+	protected $_between_style_operators = array('BETWEEN');
366
+
367
+	/**
368
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
369
+	 * @var array
370
+	 */
371
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
372
+	/**
373
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
374
+	 * on a join table.
375
+	 *
376
+	 * @var array
377
+	 */
378
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
379
+
380
+	/**
381
+	 * Allowed values for $query_params['order'] for ordering in queries
382
+	 *
383
+	 * @var array
384
+	 */
385
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
386
+
387
+	/**
388
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
389
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
390
+	 *
391
+	 * @var array
392
+	 */
393
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
394
+
395
+	/**
396
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
397
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
398
+	 *
399
+	 * @var array
400
+	 */
401
+	private $_allowed_query_params = array(
402
+		0,
403
+		'limit',
404
+		'order_by',
405
+		'group_by',
406
+		'having',
407
+		'force_join',
408
+		'order',
409
+		'on_join_limit',
410
+		'default_where_conditions',
411
+		'caps',
412
+		'extra_selects',
413
+		'exclude_protected',
414
+	);
415
+
416
+	/**
417
+	 * All the data types that can be used in $wpdb->prepare statements.
418
+	 *
419
+	 * @var array
420
+	 */
421
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
422
+
423
+	/**
424
+	 * @var EE_Registry $EE
425
+	 */
426
+	protected $EE = null;
427
+
428
+
429
+	/**
430
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
431
+	 *
432
+	 * @var int
433
+	 */
434
+	protected $_show_next_x_db_queries = 0;
435
+
436
+	/**
437
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
438
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
439
+	 * WHERE, GROUP_BY, etc.
440
+	 *
441
+	 * @var CustomSelects
442
+	 */
443
+	protected $_custom_selections = array();
444
+
445
+	/**
446
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
447
+	 * caches every model object we've fetched from the DB on this request
448
+	 *
449
+	 * @var array
450
+	 */
451
+	protected $_entity_map;
452
+
453
+	/**
454
+	 * @var LoaderInterface $loader
455
+	 */
456
+	protected static $loader;
457
+
458
+
459
+	/**
460
+	 * constant used to show EEM_Base has not yet verified the db on this http request
461
+	 */
462
+	const db_verified_none = 0;
463
+
464
+	/**
465
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
466
+	 * but not the addons' dbs
467
+	 */
468
+	const db_verified_core = 1;
469
+
470
+	/**
471
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
472
+	 * the EE core db too)
473
+	 */
474
+	const db_verified_addons = 2;
475
+
476
+	/**
477
+	 * indicates whether an EEM_Base child has already re-verified the DB
478
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
479
+	 * looking like EEM_Base::db_verified_*
480
+	 *
481
+	 * @var int - 0 = none, 1 = core, 2 = addons
482
+	 */
483
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
484
+
485
+	/**
486
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
487
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
488
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
489
+	 */
490
+	const default_where_conditions_all = 'all';
491
+
492
+	/**
493
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
494
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
495
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
496
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
497
+	 *        models which share tables with other models, this can return data for the wrong model.
498
+	 */
499
+	const default_where_conditions_this_only = 'this_model_only';
500
+
501
+	/**
502
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
503
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
504
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
505
+	 */
506
+	const default_where_conditions_others_only = 'other_models_only';
507
+
508
+	/**
509
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
510
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
511
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
512
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
513
+	 *        (regardless of whether those events and venues are trashed)
514
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
515
+	 *        events.
516
+	 */
517
+	const default_where_conditions_minimum_all = 'minimum';
518
+
519
+	/**
520
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
521
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
522
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
523
+	 *        not)
524
+	 */
525
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
526
+
527
+	/**
528
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
529
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
530
+	 *        it's possible it will return table entries for other models. You should use
531
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
532
+	 */
533
+	const default_where_conditions_none = 'none';
534
+
535
+
536
+
537
+	/**
538
+	 * About all child constructors:
539
+	 * they should define the _tables, _fields and _model_relations arrays.
540
+	 * Should ALWAYS be called after child constructor.
541
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
542
+	 * finalizes constructing all the object's attributes.
543
+	 * Generally, rather than requiring a child to code
544
+	 * $this->_tables = array(
545
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
546
+	 *        ...);
547
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
548
+	 * each EE_Table has a function to set the table's alias after the constructor, using
549
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
550
+	 * do something similar.
551
+	 *
552
+	 * @param null $timezone
553
+	 * @throws EE_Error
554
+	 */
555
+	protected function __construct($timezone = null)
556
+	{
557
+		// check that the model has not been loaded too soon
558
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
559
+			throw new EE_Error(
560
+				sprintf(
561
+					esc_html__(
562
+						'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.',
563
+						'event_espresso'
564
+					),
565
+					get_class($this)
566
+				)
567
+			);
568
+		}
569
+		/**
570
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
571
+		 */
572
+		if (empty(EEM_Base::$_model_query_blog_id)) {
573
+			EEM_Base::set_model_query_blog_id();
574
+		}
575
+		/**
576
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
577
+		 * just use EE_Register_Model_Extension
578
+		 *
579
+		 * @var EE_Table_Base[] $_tables
580
+		 */
581
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
582
+		foreach ($this->_tables as $table_alias => $table_obj) {
583
+			/** @var $table_obj EE_Table_Base */
584
+			$table_obj->_construct_finalize_with_alias($table_alias);
585
+			if ($table_obj instanceof EE_Secondary_Table) {
586
+				/** @var $table_obj EE_Secondary_Table */
587
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
588
+			}
589
+		}
590
+		/**
591
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
592
+		 * EE_Register_Model_Extension
593
+		 *
594
+		 * @param EE_Model_Field_Base[] $_fields
595
+		 */
596
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
597
+		$this->_invalidate_field_caches();
598
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
599
+			if (! array_key_exists($table_alias, $this->_tables)) {
600
+				throw new EE_Error(sprintf(esc_html__(
601
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
602
+					'event_espresso'
603
+				), $table_alias, implode(",", $this->_fields)));
604
+			}
605
+			foreach ($fields_for_table as $field_name => $field_obj) {
606
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
607
+				// primary key field base has a slightly different _construct_finalize
608
+				/** @var $field_obj EE_Model_Field_Base */
609
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
610
+			}
611
+		}
612
+		// everything is related to Extra_Meta
613
+		if (get_class($this) !== 'EEM_Extra_Meta') {
614
+			// make extra meta related to everything, but don't block deleting things just
615
+			// because they have related extra meta info. For now just orphan those extra meta
616
+			// in the future we should automatically delete them
617
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
618
+		}
619
+		// and change logs
620
+		if (get_class($this) !== 'EEM_Change_Log') {
621
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
622
+		}
623
+		/**
624
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
625
+		 * EE_Register_Model_Extension
626
+		 *
627
+		 * @param EE_Model_Relation_Base[] $_model_relations
628
+		 */
629
+		$this->_model_relations = (array) apply_filters(
630
+			'FHEE__' . get_class($this) . '__construct__model_relations',
631
+			$this->_model_relations
632
+		);
633
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
634
+			/** @var $relation_obj EE_Model_Relation_Base */
635
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
636
+		}
637
+		foreach ($this->_indexes as $index_name => $index_obj) {
638
+			/** @var $index_obj EE_Index */
639
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
640
+		}
641
+		$this->set_timezone($timezone);
642
+		// finalize default where condition strategy, or set default
643
+		if (! $this->_default_where_conditions_strategy) {
644
+			// nothing was set during child constructor, so set default
645
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646
+		}
647
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
648
+		if (! $this->_minimum_where_conditions_strategy) {
649
+			// nothing was set during child constructor, so set default
650
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651
+		}
652
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
653
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
654
+		// to indicate to NOT set it, set it to the logical default
655
+		if ($this->_caps_slug === null) {
656
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
657
+		}
658
+		// initialize the standard cap restriction generators if none were specified by the child constructor
659
+		if ($this->_cap_restriction_generators !== false) {
660
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
663
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664
+						new EE_Restriction_Generator_Protected(),
665
+						$cap_context,
666
+						$this
667
+					);
668
+				}
669
+			}
670
+		}
671
+		// if there are cap restriction generators, use them to make the default cap restrictions
672
+		if ($this->_cap_restriction_generators !== false) {
673
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
+				if (! $generator_object) {
675
+					continue;
676
+				}
677
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
678
+					throw new EE_Error(
679
+						sprintf(
680
+							esc_html__(
681
+								'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.',
682
+								'event_espresso'
683
+							),
684
+							$context,
685
+							$this->get_this_model_name()
686
+						)
687
+					);
688
+				}
689
+				$action = $this->cap_action_for_context($context);
690
+				if (! $generator_object->construction_finalized()) {
691
+					$generator_object->_construct_finalize($this, $action);
692
+				}
693
+			}
694
+		}
695
+		do_action('AHEE__' . get_class($this) . '__construct__end');
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 * Used to set the $_model_query_blog_id static property.
702
+	 *
703
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
704
+	 *                      value for get_current_blog_id() will be used.
705
+	 */
706
+	public static function set_model_query_blog_id($blog_id = 0)
707
+	{
708
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
709
+	}
710
+
711
+
712
+
713
+	/**
714
+	 * Returns whatever is set as the internal $model_query_blog_id.
715
+	 *
716
+	 * @return int
717
+	 */
718
+	public static function get_model_query_blog_id()
719
+	{
720
+		return EEM_Base::$_model_query_blog_id;
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * This function is a singleton method used to instantiate the Espresso_model object
727
+	 *
728
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
729
+	 *                                (and any incoming timezone data that gets saved).
730
+	 *                                Note this just sends the timezone info to the date time model field objects.
731
+	 *                                Default is NULL
732
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
733
+	 * @return static (as in the concrete child class)
734
+	 * @throws EE_Error
735
+	 * @throws InvalidArgumentException
736
+	 * @throws InvalidDataTypeException
737
+	 * @throws InvalidInterfaceException
738
+	 */
739
+	public static function instance($timezone = null)
740
+	{
741
+		// check if instance of Espresso_model already exists
742
+		if (! static::$_instance instanceof static) {
743
+			// instantiate Espresso_model
744
+			static::$_instance = new static(
745
+				$timezone,
746
+				EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
747
+			);
748
+		}
749
+		// we might have a timezone set, let set_timezone decide what to do with it
750
+		static::$_instance->set_timezone($timezone);
751
+		// Espresso_model object
752
+		return static::$_instance;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * resets the model and returns it
759
+	 *
760
+	 * @param null | string $timezone
761
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
762
+	 * all its properties reset; if it wasn't instantiated, returns null)
763
+	 * @throws EE_Error
764
+	 * @throws ReflectionException
765
+	 * @throws InvalidArgumentException
766
+	 * @throws InvalidDataTypeException
767
+	 * @throws InvalidInterfaceException
768
+	 */
769
+	public static function reset($timezone = null)
770
+	{
771
+		if (static::$_instance instanceof EEM_Base) {
772
+			// let's try to NOT swap out the current instance for a new one
773
+			// because if someone has a reference to it, we can't remove their reference
774
+			// so it's best to keep using the same reference, but change the original object
775
+			// reset all its properties to their original values as defined in the class
776
+			$r = new ReflectionClass(get_class(static::$_instance));
777
+			$static_properties = $r->getStaticProperties();
778
+			foreach ($r->getDefaultProperties() as $property => $value) {
779
+				// don't set instance to null like it was originally,
780
+				// but it's static anyways, and we're ignoring static properties (for now at least)
781
+				if (! isset($static_properties[ $property ])) {
782
+					static::$_instance->{$property} = $value;
783
+				}
784
+			}
785
+			// and then directly call its constructor again, like we would if we were creating a new one
786
+			static::$_instance->__construct(
787
+				$timezone,
788
+				EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
789
+			);
790
+			return self::instance();
791
+		}
792
+		return null;
793
+	}
794
+
795
+
796
+
797
+	/**
798
+	 * @return LoaderInterface
799
+	 * @throws InvalidArgumentException
800
+	 * @throws InvalidDataTypeException
801
+	 * @throws InvalidInterfaceException
802
+	 */
803
+	private static function getLoader()
804
+	{
805
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
806
+			EEM_Base::$loader = LoaderFactory::getLoader();
807
+		}
808
+		return EEM_Base::$loader;
809
+	}
810
+
811
+
812
+
813
+	/**
814
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
815
+	 *
816
+	 * @param  boolean $translated return localized strings or JUST the array.
817
+	 * @return array
818
+	 * @throws EE_Error
819
+	 * @throws InvalidArgumentException
820
+	 * @throws InvalidDataTypeException
821
+	 * @throws InvalidInterfaceException
822
+	 */
823
+	public function status_array($translated = false)
824
+	{
825
+		if (! array_key_exists('Status', $this->_model_relations)) {
826
+			return array();
827
+		}
828
+		$model_name = $this->get_this_model_name();
829
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
830
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831
+		$status_array = array();
832
+		foreach ($stati as $status) {
833
+			$status_array[ $status->ID() ] = $status->get('STS_code');
834
+		}
835
+		return $translated
836
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
837
+			: $status_array;
838
+	}
839
+
840
+
841
+
842
+	/**
843
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
844
+	 *
845
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
846
+	 *                             or if you have the development copy of EE you can view this at the path:
847
+	 *                             /docs/G--Model-System/model-query-params.md
848
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
849
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
+	 *                                        array( array(
853
+	 *                                        'OR'=>array(
854
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
+	 *                                        )
857
+	 *                                        ),
858
+	 *                                        'limit'=>10,
859
+	 *                                        'group_by'=>'TXN_ID'
860
+	 *                                        ));
861
+	 *                                        get all the answers to the question titled "shirt size" for event with id
862
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
+	 *                                        'Question.QST_display_text'=>'shirt size',
864
+	 *                                        'Registration.Event.EVT_ID'=>12
865
+	 *                                        ),
866
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
867
+	 *                                        ));
868
+	 * @throws EE_Error
869
+	 */
870
+	public function get_all($query_params = array())
871
+	{
872
+		if (
873
+			isset($query_params['limit'])
874
+			&& ! isset($query_params['group_by'])
875
+		) {
876
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
877
+		}
878
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
879
+	}
880
+
881
+
882
+
883
+	/**
884
+	 * Modifies the query parameters so we only get back model objects
885
+	 * that "belong" to the current user
886
+	 *
887
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
889
+	 */
890
+	public function alter_query_params_to_only_include_mine($query_params = array())
891
+	{
892
+		$wp_user_field_name = $this->wp_user_field_name();
893
+		if ($wp_user_field_name) {
894
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
895
+		}
896
+		return $query_params;
897
+	}
898
+
899
+
900
+
901
+	/**
902
+	 * Returns the name of the field's name that points to the WP_User table
903
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
904
+	 * foreign key to the WP_User table)
905
+	 *
906
+	 * @return string|boolean string on success, boolean false when there is no
907
+	 * foreign key to the WP_User table
908
+	 */
909
+	public function wp_user_field_name()
910
+	{
911
+		try {
912
+			if (! empty($this->_model_chain_to_wp_user)) {
913
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914
+				$last_model_name = end($models_to_follow_to_wp_users);
915
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
917
+			} else {
918
+				$model_with_fk_to_wp_users = $this;
919
+				$model_chain_to_wp_user = '';
920
+			}
921
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
923
+		} catch (EE_Error $e) {
924
+			return false;
925
+		}
926
+	}
927
+
928
+
929
+
930
+	/**
931
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
932
+	 * (or transiently-related model) has a foreign key to the wp_users table;
933
+	 * useful for finding if model objects of this type are 'owned' by the current user.
934
+	 * This is an empty string when the foreign key is on this model and when it isn't,
935
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
936
+	 * (or transiently-related model)
937
+	 *
938
+	 * @return string
939
+	 */
940
+	public function model_chain_to_wp_user()
941
+	{
942
+		return $this->_model_chain_to_wp_user;
943
+	}
944
+
945
+
946
+
947
+	/**
948
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
949
+	 * like how registrations don't have a foreign key to wp_users, but the
950
+	 * events they are for are), or is unrelated to wp users.
951
+	 * generally available
952
+	 *
953
+	 * @return boolean
954
+	 */
955
+	public function is_owned()
956
+	{
957
+		if ($this->model_chain_to_wp_user()) {
958
+			return true;
959
+		}
960
+		try {
961
+			$this->get_foreign_key_to('WP_User');
962
+			return true;
963
+		} catch (EE_Error $e) {
964
+			return false;
965
+		}
966
+	}
967
+
968
+
969
+	/**
970
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
971
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
972
+	 * the model)
973
+	 *
974
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
975
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
976
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
977
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
978
+	 *                                  override this and set the select to "*", or a specific column name, like
979
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
980
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
981
+	 *                                  the aliases used to refer to this selection, and values are to be
982
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
983
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
984
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
985
+	 * @throws EE_Error
986
+	 * @throws InvalidArgumentException
987
+	 */
988
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
989
+	{
990
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
991
+		;
992
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
993
+		$select_expressions = $columns_to_select === null
994
+			? $this->_construct_default_select_sql($model_query_info)
995
+			: '';
996
+		if ($this->_custom_selections instanceof CustomSelects) {
997
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998
+			$select_expressions .= $select_expressions
999
+				? ', ' . $custom_expressions
1000
+				: $custom_expressions;
1001
+		}
1002
+
1003
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1004
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1010
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1011
+	 * method of including extra select information.
1012
+	 *
1013
+	 * @param array             $query_params
1014
+	 * @param null|array|string $columns_to_select
1015
+	 * @return null|CustomSelects
1016
+	 * @throws InvalidArgumentException
1017
+	 */
1018
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019
+	{
1020
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021
+			return null;
1022
+		}
1023
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1024
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1025
+		return new CustomSelects($selects);
1026
+	}
1027
+
1028
+
1029
+
1030
+	/**
1031
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1032
+	 * but you can use the model query params to more easily
1033
+	 * take care of joins, field preparation etc.
1034
+	 *
1035
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1036
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1039
+	 *                                  override this and set the select to "*", or a specific column name, like
1040
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
+	 *                                  the aliases used to refer to this selection, and values are to be
1043
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
+	 * @throws EE_Error
1047
+	 */
1048
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
+	{
1050
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
+	}
1052
+
1053
+
1054
+
1055
+	/**
1056
+	 * For creating a custom select statement
1057
+	 *
1058
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
+	 *                                 SQL, and 1=>is the datatype
1061
+	 * @throws EE_Error
1062
+	 * @return string
1063
+	 */
1064
+	private function _construct_select_from_input($columns_to_select)
1065
+	{
1066
+		if (is_array($columns_to_select)) {
1067
+			$select_sql_array = array();
1068
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
+					throw new EE_Error(
1071
+						sprintf(
1072
+							esc_html__(
1073
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
+								'event_espresso'
1075
+							),
1076
+							$selection_and_datatype,
1077
+							$alias
1078
+						)
1079
+					);
1080
+				}
1081
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082
+					throw new EE_Error(
1083
+						sprintf(
1084
+							esc_html__(
1085
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
+								'event_espresso'
1087
+							),
1088
+							$selection_and_datatype[1],
1089
+							$selection_and_datatype[0],
1090
+							$alias,
1091
+							implode(', ', $this->_valid_wpdb_data_types)
1092
+						)
1093
+					);
1094
+				}
1095
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
+			}
1097
+			$columns_to_select_string = implode(', ', $select_sql_array);
1098
+		} else {
1099
+			$columns_to_select_string = $columns_to_select;
1100
+		}
1101
+		return $columns_to_select_string;
1102
+	}
1103
+
1104
+
1105
+
1106
+	/**
1107
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
+	 *
1109
+	 * @return string
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function primary_key_name()
1113
+	{
1114
+		return $this->get_primary_key_field()->get_name();
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1120
+	 * If there is no primary key on this model, $id is treated as primary key string
1121
+	 *
1122
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1123
+	 * @return EE_Base_Class
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	public function get_one_by_ID($id)
1127
+	{
1128
+		if ($this->get_from_entity_map($id)) {
1129
+			return $this->get_from_entity_map($id);
1130
+		}
1131
+		$model_object = $this->get_one(
1132
+			$this->alter_query_params_to_restrict_by_ID(
1133
+				$id,
1134
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
+			)
1136
+		);
1137
+		$className = $this->_get_class_name();
1138
+		if ($model_object instanceof $className) {
1139
+			// make sure valid objects get added to the entity map
1140
+			// so that the next call to this method doesn't trigger another trip to the db
1141
+			$this->add_to_entity_map($model_object);
1142
+		}
1143
+		return $model_object;
1144
+	}
1145
+
1146
+
1147
+
1148
+	/**
1149
+	 * Alters query parameters to only get items with this ID are returned.
1150
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1151
+	 * or could just be a simple primary key ID
1152
+	 *
1153
+	 * @param int   $id
1154
+	 * @param array $query_params
1155
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1156
+	 * @throws EE_Error
1157
+	 */
1158
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159
+	{
1160
+		if (! isset($query_params[0])) {
1161
+			$query_params[0] = array();
1162
+		}
1163
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1164
+		if ($conditions_from_id === null) {
1165
+			$query_params[0][ $this->primary_key_name() ] = $id;
1166
+		} else {
1167
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1168
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1169
+		}
1170
+		return $query_params;
1171
+	}
1172
+
1173
+
1174
+
1175
+	/**
1176
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1177
+	 * array. If no item is found, null is returned.
1178
+	 *
1179
+	 * @param array $query_params like EEM_Base's $query_params variable.
1180
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1181
+	 * @throws EE_Error
1182
+	 */
1183
+	public function get_one($query_params = array())
1184
+	{
1185
+		if (! is_array($query_params)) {
1186
+			EE_Error::doing_it_wrong(
1187
+				'EEM_Base::get_one',
1188
+				sprintf(
1189
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1190
+					gettype($query_params)
1191
+				),
1192
+				'4.6.0'
1193
+			);
1194
+			$query_params = array();
1195
+		}
1196
+		$query_params['limit'] = 1;
1197
+		$items = $this->get_all($query_params);
1198
+		if (empty($items)) {
1199
+			return null;
1200
+		}
1201
+		return array_shift($items);
1202
+	}
1203
+
1204
+
1205
+
1206
+	/**
1207
+	 * Returns the next x number of items in sequence from the given value as
1208
+	 * found in the database matching the given query conditions.
1209
+	 *
1210
+	 * @param mixed $current_field_value    Value used for the reference point.
1211
+	 * @param null  $field_to_order_by      What field is used for the
1212
+	 *                                      reference point.
1213
+	 * @param int   $limit                  How many to return.
1214
+	 * @param array $query_params           Extra conditions on the query.
1215
+	 * @param null  $columns_to_select      If left null, then an array of
1216
+	 *                                      EE_Base_Class objects is returned,
1217
+	 *                                      otherwise you can indicate just the
1218
+	 *                                      columns you want returned.
1219
+	 * @return EE_Base_Class[]|array
1220
+	 * @throws EE_Error
1221
+	 */
1222
+	public function next_x(
1223
+		$current_field_value,
1224
+		$field_to_order_by = null,
1225
+		$limit = 1,
1226
+		$query_params = array(),
1227
+		$columns_to_select = null
1228
+	) {
1229
+		return $this->_get_consecutive(
1230
+			$current_field_value,
1231
+			'>',
1232
+			$field_to_order_by,
1233
+			$limit,
1234
+			$query_params,
1235
+			$columns_to_select
1236
+		);
1237
+	}
1238
+
1239
+
1240
+
1241
+	/**
1242
+	 * Returns the previous x number of items in sequence from the given value
1243
+	 * as found in the database matching the given query conditions.
1244
+	 *
1245
+	 * @param mixed $current_field_value    Value used for the reference point.
1246
+	 * @param null  $field_to_order_by      What field is used for the
1247
+	 *                                      reference point.
1248
+	 * @param int   $limit                  How many to return.
1249
+	 * @param array $query_params           Extra conditions on the query.
1250
+	 * @param null  $columns_to_select      If left null, then an array of
1251
+	 *                                      EE_Base_Class objects is returned,
1252
+	 *                                      otherwise you can indicate just the
1253
+	 *                                      columns you want returned.
1254
+	 * @return EE_Base_Class[]|array
1255
+	 * @throws EE_Error
1256
+	 */
1257
+	public function previous_x(
1258
+		$current_field_value,
1259
+		$field_to_order_by = null,
1260
+		$limit = 1,
1261
+		$query_params = array(),
1262
+		$columns_to_select = null
1263
+	) {
1264
+		return $this->_get_consecutive(
1265
+			$current_field_value,
1266
+			'<',
1267
+			$field_to_order_by,
1268
+			$limit,
1269
+			$query_params,
1270
+			$columns_to_select
1271
+		);
1272
+	}
1273
+
1274
+
1275
+
1276
+	/**
1277
+	 * Returns the next item in sequence from the given value as found in the
1278
+	 * database matching the given query conditions.
1279
+	 *
1280
+	 * @param mixed $current_field_value    Value used for the reference point.
1281
+	 * @param null  $field_to_order_by      What field is used for the
1282
+	 *                                      reference point.
1283
+	 * @param array $query_params           Extra conditions on the query.
1284
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1285
+	 *                                      object is returned, otherwise you
1286
+	 *                                      can indicate just the columns you
1287
+	 *                                      want and a single array indexed by
1288
+	 *                                      the columns will be returned.
1289
+	 * @return EE_Base_Class|null|array()
1290
+	 * @throws EE_Error
1291
+	 */
1292
+	public function next(
1293
+		$current_field_value,
1294
+		$field_to_order_by = null,
1295
+		$query_params = array(),
1296
+		$columns_to_select = null
1297
+	) {
1298
+		$results = $this->_get_consecutive(
1299
+			$current_field_value,
1300
+			'>',
1301
+			$field_to_order_by,
1302
+			1,
1303
+			$query_params,
1304
+			$columns_to_select
1305
+		);
1306
+		return empty($results) ? null : reset($results);
1307
+	}
1308
+
1309
+
1310
+
1311
+	/**
1312
+	 * Returns the previous item in sequence from the given value as found in
1313
+	 * the database matching the given query conditions.
1314
+	 *
1315
+	 * @param mixed $current_field_value    Value used for the reference point.
1316
+	 * @param null  $field_to_order_by      What field is used for the
1317
+	 *                                      reference point.
1318
+	 * @param array $query_params           Extra conditions on the query.
1319
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1320
+	 *                                      object is returned, otherwise you
1321
+	 *                                      can indicate just the columns you
1322
+	 *                                      want and a single array indexed by
1323
+	 *                                      the columns will be returned.
1324
+	 * @return EE_Base_Class|null|array()
1325
+	 * @throws EE_Error
1326
+	 */
1327
+	public function previous(
1328
+		$current_field_value,
1329
+		$field_to_order_by = null,
1330
+		$query_params = array(),
1331
+		$columns_to_select = null
1332
+	) {
1333
+		$results = $this->_get_consecutive(
1334
+			$current_field_value,
1335
+			'<',
1336
+			$field_to_order_by,
1337
+			1,
1338
+			$query_params,
1339
+			$columns_to_select
1340
+		);
1341
+		return empty($results) ? null : reset($results);
1342
+	}
1343
+
1344
+
1345
+
1346
+	/**
1347
+	 * Returns the a consecutive number of items in sequence from the given
1348
+	 * value as found in the database matching the given query conditions.
1349
+	 *
1350
+	 * @param mixed  $current_field_value   Value used for the reference point.
1351
+	 * @param string $operand               What operand is used for the sequence.
1352
+	 * @param string $field_to_order_by     What field is used for the reference point.
1353
+	 * @param int    $limit                 How many to return.
1354
+	 * @param array  $query_params          Extra conditions on the query.
1355
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1356
+	 *                                      otherwise you can indicate just the columns you want returned.
1357
+	 * @return EE_Base_Class[]|array
1358
+	 * @throws EE_Error
1359
+	 */
1360
+	protected function _get_consecutive(
1361
+		$current_field_value,
1362
+		$operand = '>',
1363
+		$field_to_order_by = null,
1364
+		$limit = 1,
1365
+		$query_params = array(),
1366
+		$columns_to_select = null
1367
+	) {
1368
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1369
+		if (empty($field_to_order_by)) {
1370
+			if ($this->has_primary_key_field()) {
1371
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1372
+			} else {
1373
+				if (WP_DEBUG) {
1374
+					throw new EE_Error(esc_html__(
1375
+						'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).',
1376
+						'event_espresso'
1377
+					));
1378
+				}
1379
+				EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1380
+				return array();
1381
+			}
1382
+		}
1383
+		if (! is_array($query_params)) {
1384
+			EE_Error::doing_it_wrong(
1385
+				'EEM_Base::_get_consecutive',
1386
+				sprintf(
1387
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1388
+					gettype($query_params)
1389
+				),
1390
+				'4.6.0'
1391
+			);
1392
+			$query_params = array();
1393
+		}
1394
+		// let's add the where query param for consecutive look up.
1395
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1396
+		$query_params['limit'] = $limit;
1397
+		// set direction
1398
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1399
+		$query_params['order_by'] = $operand === '>'
1400
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1401
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1402
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1403
+		if (empty($columns_to_select)) {
1404
+			return $this->get_all($query_params);
1405
+		}
1406
+		// getting just the fields
1407
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1408
+	}
1409
+
1410
+
1411
+
1412
+	/**
1413
+	 * This sets the _timezone property after model object has been instantiated.
1414
+	 *
1415
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1416
+	 */
1417
+	public function set_timezone($timezone)
1418
+	{
1419
+		if ($timezone !== null) {
1420
+			$this->_timezone = $timezone;
1421
+		}
1422
+		// note we need to loop through relations and set the timezone on those objects as well.
1423
+		foreach ($this->_model_relations as $relation) {
1424
+			$relation->set_timezone($timezone);
1425
+		}
1426
+		// and finally we do the same for any datetime fields
1427
+		foreach ($this->_fields as $field) {
1428
+			if ($field instanceof EE_Datetime_Field) {
1429
+				$field->set_timezone($timezone);
1430
+			}
1431
+		}
1432
+	}
1433
+
1434
+
1435
+
1436
+	/**
1437
+	 * This just returns whatever is set for the current timezone.
1438
+	 *
1439
+	 * @access public
1440
+	 * @return string
1441
+	 */
1442
+	public function get_timezone()
1443
+	{
1444
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1445
+		if (empty($this->_timezone)) {
1446
+			foreach ($this->_fields as $field) {
1447
+				if ($field instanceof EE_Datetime_Field) {
1448
+					$this->set_timezone($field->get_timezone());
1449
+					break;
1450
+				}
1451
+			}
1452
+		}
1453
+		// if timezone STILL empty then return the default timezone for the site.
1454
+		if (empty($this->_timezone)) {
1455
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1456
+		}
1457
+		return $this->_timezone;
1458
+	}
1459
+
1460
+
1461
+
1462
+	/**
1463
+	 * This returns the date formats set for the given field name and also ensures that
1464
+	 * $this->_timezone property is set correctly.
1465
+	 *
1466
+	 * @since 4.6.x
1467
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1468
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1469
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1470
+	 * @return array formats in an array with the date format first, and the time format last.
1471
+	 */
1472
+	public function get_formats_for($field_name, $pretty = false)
1473
+	{
1474
+		$field_settings = $this->field_settings_for($field_name);
1475
+		// if not a valid EE_Datetime_Field then throw error
1476
+		if (! $field_settings instanceof EE_Datetime_Field) {
1477
+			throw new EE_Error(sprintf(esc_html__(
1478
+				'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.',
1479
+				'event_espresso'
1480
+			), $field_name));
1481
+		}
1482
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1483
+		// the field.
1484
+		$this->_timezone = $field_settings->get_timezone();
1485
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1486
+	}
1487
+
1488
+
1489
+
1490
+	/**
1491
+	 * This returns the current time in a format setup for a query on this model.
1492
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1493
+	 * it will return:
1494
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1495
+	 *  NOW
1496
+	 *  - or a unix timestamp (equivalent to time())
1497
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1498
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1499
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1500
+	 * @since 4.6.x
1501
+	 * @param string $field_name       The field the current time is needed for.
1502
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1503
+	 *                                 formatted string matching the set format for the field in the set timezone will
1504
+	 *                                 be returned.
1505
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1506
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1507
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1508
+	 *                                 exception is triggered.
1509
+	 */
1510
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1511
+	{
1512
+		$formats = $this->get_formats_for($field_name);
1513
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1514
+		if ($timestamp) {
1515
+			return $DateTime->format('U');
1516
+		}
1517
+		// not returning timestamp, so return formatted string in timezone.
1518
+		switch ($what) {
1519
+			case 'time':
1520
+				return $DateTime->format($formats[1]);
1521
+				break;
1522
+			case 'date':
1523
+				return $DateTime->format($formats[0]);
1524
+				break;
1525
+			default:
1526
+				return $DateTime->format(implode(' ', $formats));
1527
+				break;
1528
+		}
1529
+	}
1530
+
1531
+
1532
+
1533
+	/**
1534
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1535
+	 * for the model are.  Returns a DateTime object.
1536
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1537
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1538
+	 * ignored.
1539
+	 *
1540
+	 * @param string $field_name      The field being setup.
1541
+	 * @param string $timestring      The date time string being used.
1542
+	 * @param string $incoming_format The format for the time string.
1543
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1544
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1545
+	 *                                format is
1546
+	 *                                'U', this is ignored.
1547
+	 * @return DateTime
1548
+	 * @throws EE_Error
1549
+	 */
1550
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1551
+	{
1552
+		// just using this to ensure the timezone is set correctly internally
1553
+		$this->get_formats_for($field_name);
1554
+		// load EEH_DTT_Helper
1555
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1556
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1557
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1558
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1565
+	 *
1566
+	 * @return EE_Table_Base[]
1567
+	 */
1568
+	public function get_tables()
1569
+	{
1570
+		return $this->_tables;
1571
+	}
1572
+
1573
+
1574
+
1575
+	/**
1576
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1577
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1578
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1579
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1580
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1581
+	 * model object with EVT_ID = 1
1582
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1583
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1584
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1585
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1586
+	 * are not specified)
1587
+	 *
1588
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1589
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1590
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1591
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1592
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1593
+	 *                                         ID=34, we'd use this method as follows:
1594
+	 *                                         EEM_Transaction::instance()->update(
1595
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1596
+	 *                                         array(array('TXN_ID'=>34)));
1597
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1598
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1599
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1600
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1601
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1602
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1603
+	 *                                         TRUE, it is assumed that you've already called
1604
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1605
+	 *                                         malicious javascript. However, if
1606
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1607
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1608
+	 *                                         and every other field, before insertion. We provide this parameter
1609
+	 *                                         because model objects perform their prepare_for_set function on all
1610
+	 *                                         their values, and so don't need to be called again (and in many cases,
1611
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1612
+	 *                                         prepare_for_set method...)
1613
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1614
+	 *                                         in this model's entity map according to $fields_n_values that match
1615
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1616
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1617
+	 *                                         could get out-of-sync with the database
1618
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1619
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1620
+	 *                                         bad)
1621
+	 * @throws EE_Error
1622
+	 */
1623
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624
+	{
1625
+		if (! is_array($query_params)) {
1626
+			EE_Error::doing_it_wrong(
1627
+				'EEM_Base::update',
1628
+				sprintf(
1629
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1630
+					gettype($query_params)
1631
+				),
1632
+				'4.6.0'
1633
+			);
1634
+			$query_params = array();
1635
+		}
1636
+		/**
1637
+		 * Action called before a model update call has been made.
1638
+		 *
1639
+		 * @param EEM_Base $model
1640
+		 * @param array    $fields_n_values the updated fields and their new values
1641
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
+		 */
1643
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1644
+		/**
1645
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1646
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1647
+		 *
1648
+		 * @param array    $fields_n_values fields and their new values
1649
+		 * @param EEM_Base $model           the model being queried
1650
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1651
+		 */
1652
+		$fields_n_values = (array) apply_filters(
1653
+			'FHEE__EEM_Base__update__fields_n_values',
1654
+			$fields_n_values,
1655
+			$this,
1656
+			$query_params
1657
+		);
1658
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1659
+		// to do that, for each table, verify that it's PK isn't null.
1660
+		$tables = $this->get_tables();
1661
+		// 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
1662
+		// NOTE: we should make this code more efficient by NOT querying twice
1663
+		// before the real update, but that needs to first go through ALPHA testing
1664
+		// as it's dangerous. says Mike August 8 2014
1665
+		// we want to make sure the default_where strategy is ignored
1666
+		$this->_ignore_where_strategy = true;
1667
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1668
+		foreach ($wpdb_select_results as $wpdb_result) {
1669
+			// type cast stdClass as array
1670
+			$wpdb_result = (array) $wpdb_result;
1671
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672
+			if ($this->has_primary_key_field()) {
1673
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1674
+			} else {
1675
+				// 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)
1676
+				$main_table_pk_value = null;
1677
+			}
1678
+			// 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
1679
+			// 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
1680
+			if (count($tables) > 1) {
1681
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1682
+				// in that table, and so we'll want to insert one
1683
+				foreach ($tables as $table_obj) {
1684
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1685
+					// if there is no private key for this table on the results, it means there's no entry
1686
+					// in this table, right? so insert a row in the current table, using any fields available
1687
+					if (
1688
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
+						   && $wpdb_result[ $this_table_pk_column ])
1690
+					) {
1691
+						$success = $this->_insert_into_specific_table(
1692
+							$table_obj,
1693
+							$fields_n_values,
1694
+							$main_table_pk_value
1695
+						);
1696
+						// if we died here, report the error
1697
+						if (! $success) {
1698
+							return false;
1699
+						}
1700
+					}
1701
+				}
1702
+			}
1703
+			//              //and now check that if we have cached any models by that ID on the model, that
1704
+			//              //they also get updated properly
1705
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1706
+			//              if( $model_object ){
1707
+			//                  foreach( $fields_n_values as $field => $value ){
1708
+			//                      $model_object->set($field, $value);
1709
+			// let's make sure default_where strategy is followed now
1710
+			$this->_ignore_where_strategy = false;
1711
+		}
1712
+		// if we want to keep model objects in sync, AND
1713
+		// if this wasn't called from a model object (to update itself)
1714
+		// then we want to make sure we keep all the existing
1715
+		// model objects in sync with the db
1716
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1717
+			if ($this->has_primary_key_field()) {
1718
+				$model_objs_affected_ids = $this->get_col($query_params);
1719
+			} else {
1720
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1721
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1722
+				$model_objs_affected_ids = array();
1723
+				foreach ($models_affected_key_columns as $row) {
1724
+					$combined_index_key = $this->get_index_primary_key_string($row);
1725
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1726
+				}
1727
+			}
1728
+			if (! $model_objs_affected_ids) {
1729
+				// wait wait wait- if nothing was affected let's stop here
1730
+				return 0;
1731
+			}
1732
+			foreach ($model_objs_affected_ids as $id) {
1733
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1734
+				if ($model_obj_in_entity_map) {
1735
+					foreach ($fields_n_values as $field => $new_value) {
1736
+						$model_obj_in_entity_map->set($field, $new_value);
1737
+					}
1738
+				}
1739
+			}
1740
+			// if there is a primary key on this model, we can now do a slight optimization
1741
+			if ($this->has_primary_key_field()) {
1742
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1743
+				$query_params = array(
1744
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1745
+					'limit'                    => count($model_objs_affected_ids),
1746
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1747
+				);
1748
+			}
1749
+		}
1750
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1751
+		$SQL = "UPDATE "
1752
+			   . $model_query_info->get_full_join_sql()
1753
+			   . " SET "
1754
+			   . $this->_construct_update_sql($fields_n_values)
1755
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757
+		/**
1758
+		 * Action called after a model update call has been made.
1759
+		 *
1760
+		 * @param EEM_Base $model
1761
+		 * @param array    $fields_n_values the updated fields and their new values
1762
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1763
+		 * @param int      $rows_affected
1764
+		 */
1765
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
+		return $rows_affected;// how many supposedly got updated
1767
+	}
1768
+
1769
+
1770
+
1771
+	/**
1772
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1773
+	 * are teh values of the field specified (or by default the primary key field)
1774
+	 * that matched the query params. Note that you should pass the name of the
1775
+	 * model FIELD, not the database table's column name.
1776
+	 *
1777
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1778
+	 * @param string $field_to_select
1779
+	 * @return array just like $wpdb->get_col()
1780
+	 * @throws EE_Error
1781
+	 */
1782
+	public function get_col($query_params = array(), $field_to_select = null)
1783
+	{
1784
+		if ($field_to_select) {
1785
+			$field = $this->field_settings_for($field_to_select);
1786
+		} elseif ($this->has_primary_key_field()) {
1787
+			$field = $this->get_primary_key_field();
1788
+		} else {
1789
+			// no primary key, just grab the first column
1790
+			$field = reset($this->field_settings());
1791
+		}
1792
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1793
+		$select_expressions = $field->get_qualified_column();
1794
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1795
+		return $this->_do_wpdb_query('get_col', array($SQL));
1796
+	}
1797
+
1798
+
1799
+
1800
+	/**
1801
+	 * Returns a single column value for a single row from the database
1802
+	 *
1803
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1804
+	 * @param string $field_to_select @see EEM_Base::get_col()
1805
+	 * @return string
1806
+	 * @throws EE_Error
1807
+	 */
1808
+	public function get_var($query_params = array(), $field_to_select = null)
1809
+	{
1810
+		$query_params['limit'] = 1;
1811
+		$col = $this->get_col($query_params, $field_to_select);
1812
+		if (! empty($col)) {
1813
+			return reset($col);
1814
+		}
1815
+		return null;
1816
+	}
1817
+
1818
+
1819
+
1820
+	/**
1821
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1822
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1823
+	 * injection, but currently no further filtering is done
1824
+	 *
1825
+	 * @global      $wpdb
1826
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1827
+	 *                               be updated to in the DB
1828
+	 * @return string of SQL
1829
+	 * @throws EE_Error
1830
+	 */
1831
+	public function _construct_update_sql($fields_n_values)
1832
+	{
1833
+		/** @type WPDB $wpdb */
1834
+		global $wpdb;
1835
+		$cols_n_values = array();
1836
+		foreach ($fields_n_values as $field_name => $value) {
1837
+			$field_obj = $this->field_settings_for($field_name);
1838
+			// if the value is NULL, we want to assign the value to that.
1839
+			// wpdb->prepare doesn't really handle that properly
1840
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1841
+			$value_sql = $prepared_value === null ? 'NULL'
1842
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1843
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1844
+		}
1845
+		return implode(",", $cols_n_values);
1846
+	}
1847
+
1848
+
1849
+
1850
+	/**
1851
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1852
+	 * Performs a HARD delete, meaning the database row should always be removed,
1853
+	 * not just have a flag field on it switched
1854
+	 * Wrapper for EEM_Base::delete_permanently()
1855
+	 *
1856
+	 * @param mixed $id
1857
+	 * @param boolean $allow_blocking
1858
+	 * @return int the number of rows deleted
1859
+	 * @throws EE_Error
1860
+	 */
1861
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1862
+	{
1863
+		return $this->delete_permanently(
1864
+			array(
1865
+				array($this->get_primary_key_field()->get_name() => $id),
1866
+				'limit' => 1,
1867
+			),
1868
+			$allow_blocking
1869
+		);
1870
+	}
1871
+
1872
+
1873
+
1874
+	/**
1875
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1876
+	 * Wrapper for EEM_Base::delete()
1877
+	 *
1878
+	 * @param mixed $id
1879
+	 * @param boolean $allow_blocking
1880
+	 * @return int the number of rows deleted
1881
+	 * @throws EE_Error
1882
+	 */
1883
+	public function delete_by_ID($id, $allow_blocking = true)
1884
+	{
1885
+		return $this->delete(
1886
+			array(
1887
+				array($this->get_primary_key_field()->get_name() => $id),
1888
+				'limit' => 1,
1889
+			),
1890
+			$allow_blocking
1891
+		);
1892
+	}
1893
+
1894
+
1895
+
1896
+	/**
1897
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1898
+	 * meaning if the model has a field that indicates its been "trashed" or
1899
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1900
+	 *
1901
+	 * @see EEM_Base::delete_permanently
1902
+	 * @param array   $query_params
1903
+	 * @param boolean $allow_blocking
1904
+	 * @return int how many rows got deleted
1905
+	 * @throws EE_Error
1906
+	 */
1907
+	public function delete($query_params, $allow_blocking = true)
1908
+	{
1909
+		return $this->delete_permanently($query_params, $allow_blocking);
1910
+	}
1911
+
1912
+
1913
+
1914
+	/**
1915
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1916
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1917
+	 * as archived, not actually deleted
1918
+	 *
1919
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1920
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1921
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1922
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1923
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1924
+	 *                                DB
1925
+	 * @return int how many rows got deleted
1926
+	 * @throws EE_Error
1927
+	 */
1928
+	public function delete_permanently($query_params, $allow_blocking = true)
1929
+	{
1930
+		/**
1931
+		 * Action called just before performing a real deletion query. You can use the
1932
+		 * model and its $query_params to find exactly which items will be deleted
1933
+		 *
1934
+		 * @param EEM_Base $model
1935
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1936
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1937
+		 *                                 to block (prevent) this deletion
1938
+		 */
1939
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1940
+		// some MySQL databases may be running safe mode, which may restrict
1941
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1942
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1943
+		// to delete them
1944
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1945
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1946
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1947
+			$columns_and_ids_for_deleting
1948
+		);
1949
+		/**
1950
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1951
+		 *
1952
+		 * @param EEM_Base $this  The model instance being acted on.
1953
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1954
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1955
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1956
+		 *                                                  derived from the incoming query parameters.
1957
+		 *                                                  @see details on the structure of this array in the phpdocs
1958
+		 *                                                  for the `_get_ids_for_delete_method`
1959
+		 *
1960
+		 */
1961
+		do_action(
1962
+			'AHEE__EEM_Base__delete__before_query',
1963
+			$this,
1964
+			$query_params,
1965
+			$allow_blocking,
1966
+			$columns_and_ids_for_deleting
1967
+		);
1968
+		if ($deletion_where_query_part) {
1969
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1970
+			$table_aliases = array_keys($this->_tables);
1971
+			$SQL = "DELETE "
1972
+				   . implode(", ", $table_aliases)
1973
+				   . " FROM "
1974
+				   . $model_query_info->get_full_join_sql()
1975
+				   . " WHERE "
1976
+				   . $deletion_where_query_part;
1977
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1978
+		} else {
1979
+			$rows_deleted = 0;
1980
+		}
1981
+
1982
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1983
+		// there was no error with the delete query.
1984
+		if (
1985
+			$this->has_primary_key_field()
1986
+			&& $rows_deleted !== false
1987
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1988
+		) {
1989
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1990
+			foreach ($ids_for_removal as $id) {
1991
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1992
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1993
+				}
1994
+			}
1995
+
1996
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1997
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1998
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1999
+			// (although it is possible).
2000
+			// Note this can be skipped by using the provided filter and returning false.
2001
+			if (
2002
+				apply_filters(
2003
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2004
+					! $this instanceof EEM_Extra_Meta,
2005
+					$this
2006
+				)
2007
+			) {
2008
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2009
+					0 => array(
2010
+						'EXM_type' => $this->get_this_model_name(),
2011
+						'OBJ_ID'   => array(
2012
+							'IN',
2013
+							$ids_for_removal
2014
+						)
2015
+					)
2016
+				));
2017
+			}
2018
+		}
2019
+
2020
+		/**
2021
+		 * Action called just after performing a real deletion query. Although at this point the
2022
+		 * items should have been deleted
2023
+		 *
2024
+		 * @param EEM_Base $model
2025
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2026
+		 * @param int      $rows_deleted
2027
+		 */
2028
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
+		return $rows_deleted;// how many supposedly got deleted
2030
+	}
2031
+
2032
+
2033
+
2034
+	/**
2035
+	 * Checks all the relations that throw error messages when there are blocking related objects
2036
+	 * for related model objects. If there are any related model objects on those relations,
2037
+	 * adds an EE_Error, and return true
2038
+	 *
2039
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2040
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2041
+	 *                                                 should be ignored when determining whether there are related
2042
+	 *                                                 model objects which block this model object's deletion. Useful
2043
+	 *                                                 if you know A is related to B and are considering deleting A,
2044
+	 *                                                 but want to see if A has any other objects blocking its deletion
2045
+	 *                                                 before removing the relation between A and B
2046
+	 * @return boolean
2047
+	 * @throws EE_Error
2048
+	 */
2049
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2050
+	{
2051
+		// first, if $ignore_this_model_obj was supplied, get its model
2052
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2053
+			$ignored_model = $ignore_this_model_obj->get_model();
2054
+		} else {
2055
+			$ignored_model = null;
2056
+		}
2057
+		// now check all the relations of $this_model_obj_or_id and see if there
2058
+		// are any related model objects blocking it?
2059
+		$is_blocked = false;
2060
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2061
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2062
+				// if $ignore_this_model_obj was supplied, then for the query
2063
+				// on that model needs to be told to ignore $ignore_this_model_obj
2064
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2065
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2066
+						array(
2067
+							$ignored_model->get_primary_key_field()->get_name() => array(
2068
+								'!=',
2069
+								$ignore_this_model_obj->ID(),
2070
+							),
2071
+						),
2072
+					));
2073
+				} else {
2074
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2075
+				}
2076
+				if ($related_model_objects) {
2077
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2078
+					$is_blocked = true;
2079
+				}
2080
+			}
2081
+		}
2082
+		return $is_blocked;
2083
+	}
2084
+
2085
+
2086
+	/**
2087
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2088
+	 * @param array $row_results_for_deleting
2089
+	 * @param bool  $allow_blocking
2090
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2091
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2092
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2093
+	 *                 deleted. Example:
2094
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2095
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2096
+	 *                 where each element is a group of columns and values that get deleted. Example:
2097
+	 *                      array(
2098
+	 *                          0 => array(
2099
+	 *                              'Term_Relationship.object_id' => 1
2100
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2101
+	 *                          ),
2102
+	 *                          1 => array(
2103
+	 *                              'Term_Relationship.object_id' => 1
2104
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2105
+	 *                          )
2106
+	 *                      )
2107
+	 * @throws EE_Error
2108
+	 */
2109
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2110
+	{
2111
+		$ids_to_delete_indexed_by_column = array();
2112
+		if ($this->has_primary_key_field()) {
2113
+			$primary_table = $this->_get_main_table();
2114
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2115
+			$other_tables = $this->_get_other_tables();
2116
+			$ids_to_delete_indexed_by_column = $query = array();
2117
+			foreach ($row_results_for_deleting as $item_to_delete) {
2118
+				// before we mark this item for deletion,
2119
+				// make sure there's no related entities blocking its deletion (if we're checking)
2120
+				if (
2121
+					$allow_blocking
2122
+					&& $this->delete_is_blocked_by_related_models(
2123
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2124
+					)
2125
+				) {
2126
+					continue;
2127
+				}
2128
+				// primary table deletes
2129
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2130
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2131
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2132
+				}
2133
+			}
2134
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2135
+			$fields = $this->get_combined_primary_key_fields();
2136
+			foreach ($row_results_for_deleting as $item_to_delete) {
2137
+				$ids_to_delete_indexed_by_column_for_row = array();
2138
+				foreach ($fields as $cpk_field) {
2139
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2140
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2141
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2142
+					}
2143
+				}
2144
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2145
+			}
2146
+		} else {
2147
+			// so there's no primary key and no combined key...
2148
+			// sorry, can't help you
2149
+			throw new EE_Error(
2150
+				sprintf(
2151
+					esc_html__(
2152
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2153
+						"event_espresso"
2154
+					),
2155
+					get_class($this)
2156
+				)
2157
+			);
2158
+		}
2159
+		return $ids_to_delete_indexed_by_column;
2160
+	}
2161
+
2162
+
2163
+	/**
2164
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2165
+	 * the corresponding query_part for the query performing the delete.
2166
+	 *
2167
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2168
+	 * @return string
2169
+	 * @throws EE_Error
2170
+	 */
2171
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2172
+	{
2173
+		$query_part = '';
2174
+		if (empty($ids_to_delete_indexed_by_column)) {
2175
+			return $query_part;
2176
+		} elseif ($this->has_primary_key_field()) {
2177
+			$query = array();
2178
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2179
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2180
+			}
2181
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2183
+			$ways_to_identify_a_row = array();
2184
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185
+				$values_for_each_combined_primary_key_for_a_row = array();
2186
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2188
+				}
2189
+				$ways_to_identify_a_row[] = '('
2190
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2191
+											. ')';
2192
+			}
2193
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2194
+		}
2195
+		return $query_part;
2196
+	}
2197
+
2198
+
2199
+
2200
+	/**
2201
+	 * Gets the model field by the fully qualified name
2202
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2203
+	 * @return EE_Model_Field_Base
2204
+	 */
2205
+	public function get_field_by_column($qualified_column_name)
2206
+	{
2207
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2208
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2209
+				return $field_obj;
2210
+			}
2211
+		}
2212
+		throw new EE_Error(
2213
+			sprintf(
2214
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2215
+				$this->get_this_model_name(),
2216
+				$qualified_column_name
2217
+			)
2218
+		);
2219
+	}
2220
+
2221
+
2222
+
2223
+	/**
2224
+	 * Count all the rows that match criteria the model query params.
2225
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2226
+	 * column
2227
+	 *
2228
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2229
+	 * @param string $field_to_count field on model to count by (not column name)
2230
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2231
+	 *                               that by the setting $distinct to TRUE;
2232
+	 * @return int
2233
+	 * @throws EE_Error
2234
+	 */
2235
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2236
+	{
2237
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2238
+		if ($field_to_count) {
2239
+			$field_obj = $this->field_settings_for($field_to_count);
2240
+			$column_to_count = $field_obj->get_qualified_column();
2241
+		} elseif ($this->has_primary_key_field()) {
2242
+			$pk_field_obj = $this->get_primary_key_field();
2243
+			$column_to_count = $pk_field_obj->get_qualified_column();
2244
+		} else {
2245
+			// there's no primary key
2246
+			// if we're counting distinct items, and there's no primary key,
2247
+			// we need to list out the columns for distinction;
2248
+			// otherwise we can just use star
2249
+			if ($distinct) {
2250
+				$columns_to_use = array();
2251
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2252
+					$columns_to_use[] = $field_obj->get_qualified_column();
2253
+				}
2254
+				$column_to_count = implode(',', $columns_to_use);
2255
+			} else {
2256
+				$column_to_count = '*';
2257
+			}
2258
+		}
2259
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2262
+	}
2263
+
2264
+
2265
+
2266
+	/**
2267
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2268
+	 *
2269
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2270
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2271
+	 * @return float
2272
+	 * @throws EE_Error
2273
+	 */
2274
+	public function sum($query_params, $field_to_sum = null)
2275
+	{
2276
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2277
+		if ($field_to_sum) {
2278
+			$field_obj = $this->field_settings_for($field_to_sum);
2279
+		} else {
2280
+			$field_obj = $this->get_primary_key_field();
2281
+		}
2282
+		$column_to_count = $field_obj->get_qualified_column();
2283
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2284
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285
+		$data_type = $field_obj->get_wpdb_data_type();
2286
+		if ($data_type === '%d' || $data_type === '%s') {
2287
+			return (float) $return_value;
2288
+		}
2289
+		// must be %f
2290
+		return (float) $return_value;
2291
+	}
2292
+
2293
+
2294
+
2295
+	/**
2296
+	 * Just calls the specified method on $wpdb with the given arguments
2297
+	 * Consolidates a little extra error handling code
2298
+	 *
2299
+	 * @param string $wpdb_method
2300
+	 * @param array  $arguments_to_provide
2301
+	 * @throws EE_Error
2302
+	 * @global wpdb  $wpdb
2303
+	 * @return mixed
2304
+	 */
2305
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2306
+	{
2307
+		// if we're in maintenance mode level 2, DON'T run any queries
2308
+		// because level 2 indicates the database needs updating and
2309
+		// is probably out of sync with the code
2310
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2311
+			throw new EE_Error(sprintf(esc_html__(
2312
+				"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.",
2313
+				"event_espresso"
2314
+			)));
2315
+		}
2316
+		/** @type WPDB $wpdb */
2317
+		global $wpdb;
2318
+		if (! method_exists($wpdb, $wpdb_method)) {
2319
+			throw new EE_Error(sprintf(esc_html__(
2320
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2321
+				'event_espresso'
2322
+			), $wpdb_method));
2323
+		}
2324
+		if (WP_DEBUG) {
2325
+			$old_show_errors_value = $wpdb->show_errors;
2326
+			$wpdb->show_errors(false);
2327
+		}
2328
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2329
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2330
+		if (WP_DEBUG) {
2331
+			$wpdb->show_errors($old_show_errors_value);
2332
+			if (! empty($wpdb->last_error)) {
2333
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2334
+			}
2335
+			if ($result === false) {
2336
+				throw new EE_Error(sprintf(esc_html__(
2337
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2338
+					'event_espresso'
2339
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2340
+			}
2341
+		} elseif ($result === false) {
2342
+			EE_Error::add_error(
2343
+				sprintf(
2344
+					esc_html__(
2345
+						'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"',
2346
+						'event_espresso'
2347
+					),
2348
+					$wpdb_method,
2349
+					var_export($arguments_to_provide, true),
2350
+					$wpdb->last_error
2351
+				),
2352
+				__FILE__,
2353
+				__FUNCTION__,
2354
+				__LINE__
2355
+			);
2356
+		}
2357
+		return $result;
2358
+	}
2359
+
2360
+
2361
+
2362
+	/**
2363
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2364
+	 * and if there's an error tries to verify the DB is correct. Uses
2365
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2366
+	 * we should try to fix the EE core db, the addons, or just give up
2367
+	 *
2368
+	 * @param string $wpdb_method
2369
+	 * @param array  $arguments_to_provide
2370
+	 * @return mixed
2371
+	 */
2372
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2373
+	{
2374
+		/** @type WPDB $wpdb */
2375
+		global $wpdb;
2376
+		$wpdb->last_error = null;
2377
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2378
+		// was there an error running the query? but we don't care on new activations
2379
+		// (we're going to setup the DB anyway on new activations)
2380
+		if (
2381
+			($result === false || ! empty($wpdb->last_error))
2382
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2383
+		) {
2384
+			switch (EEM_Base::$_db_verification_level) {
2385
+				case EEM_Base::db_verified_none:
2386
+					// let's double-check core's DB
2387
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2388
+					break;
2389
+				case EEM_Base::db_verified_core:
2390
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2391
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2392
+					break;
2393
+				case EEM_Base::db_verified_addons:
2394
+					// ummmm... you in trouble
2395
+					return $result;
2396
+					break;
2397
+			}
2398
+			if (! empty($error_message)) {
2399
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2400
+				trigger_error($error_message);
2401
+			}
2402
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2403
+		}
2404
+		return $result;
2405
+	}
2406
+
2407
+
2408
+
2409
+	/**
2410
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2411
+	 * EEM_Base::$_db_verification_level
2412
+	 *
2413
+	 * @param string $wpdb_method
2414
+	 * @param array  $arguments_to_provide
2415
+	 * @return string
2416
+	 */
2417
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2418
+	{
2419
+		/** @type WPDB $wpdb */
2420
+		global $wpdb;
2421
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2422
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2423
+		$error_message = sprintf(
2424
+			esc_html__(
2425
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2426
+				'event_espresso'
2427
+			),
2428
+			$wpdb->last_error,
2429
+			$wpdb_method,
2430
+			wp_json_encode($arguments_to_provide)
2431
+		);
2432
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2433
+		return $error_message;
2434
+	}
2435
+
2436
+
2437
+
2438
+	/**
2439
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2440
+	 * EEM_Base::$_db_verification_level
2441
+	 *
2442
+	 * @param $wpdb_method
2443
+	 * @param $arguments_to_provide
2444
+	 * @return string
2445
+	 */
2446
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2447
+	{
2448
+		/** @type WPDB $wpdb */
2449
+		global $wpdb;
2450
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2451
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2452
+		$error_message = sprintf(
2453
+			esc_html__(
2454
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2455
+				'event_espresso'
2456
+			),
2457
+			$wpdb->last_error,
2458
+			$wpdb_method,
2459
+			wp_json_encode($arguments_to_provide)
2460
+		);
2461
+		EE_System::instance()->initialize_addons();
2462
+		return $error_message;
2463
+	}
2464
+
2465
+
2466
+
2467
+	/**
2468
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2469
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2470
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2471
+	 * ..."
2472
+	 *
2473
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2474
+	 * @return string
2475
+	 */
2476
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2477
+	{
2478
+		return " FROM " . $model_query_info->get_full_join_sql() .
2479
+			   $model_query_info->get_where_sql() .
2480
+			   $model_query_info->get_group_by_sql() .
2481
+			   $model_query_info->get_having_sql() .
2482
+			   $model_query_info->get_order_by_sql() .
2483
+			   $model_query_info->get_limit_sql();
2484
+	}
2485
+
2486
+
2487
+
2488
+	/**
2489
+	 * Set to easily debug the next X queries ran from this model.
2490
+	 *
2491
+	 * @param int $count
2492
+	 */
2493
+	public function show_next_x_db_queries($count = 1)
2494
+	{
2495
+		$this->_show_next_x_db_queries = $count;
2496
+	}
2497
+
2498
+
2499
+
2500
+	/**
2501
+	 * @param $sql_query
2502
+	 */
2503
+	public function show_db_query_if_previously_requested($sql_query)
2504
+	{
2505
+		if ($this->_show_next_x_db_queries > 0) {
2506
+			echo esc_html($sql_query);
2507
+			$this->_show_next_x_db_queries--;
2508
+		}
2509
+	}
2510
+
2511
+
2512
+
2513
+	/**
2514
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2515
+	 * There are the 3 cases:
2516
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2517
+	 * $otherModelObject has no ID, it is first saved.
2518
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2519
+	 * has no ID, it is first saved.
2520
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2521
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2522
+	 * join table
2523
+	 *
2524
+	 * @param        EE_Base_Class                     /int $thisModelObject
2525
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2526
+	 * @param string $relationName                     , key in EEM_Base::_relations
2527
+	 *                                                 an attendee to a group, you also want to specify which role they
2528
+	 *                                                 will have in that group. So you would use this parameter to
2529
+	 *                                                 specify array('role-column-name'=>'role-id')
2530
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2531
+	 *                                                 to for relation to methods that allow you to further specify
2532
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2533
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2534
+	 *                                                 because these will be inserted in any new rows created as well.
2535
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2536
+	 * @throws EE_Error
2537
+	 */
2538
+	public function add_relationship_to(
2539
+		$id_or_obj,
2540
+		$other_model_id_or_obj,
2541
+		$relationName,
2542
+		$extra_join_model_fields_n_values = array()
2543
+	) {
2544
+		$relation_obj = $this->related_settings_for($relationName);
2545
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2546
+	}
2547
+
2548
+
2549
+
2550
+	/**
2551
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2552
+	 * There are the 3 cases:
2553
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2554
+	 * error
2555
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2556
+	 * an error
2557
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2558
+	 *
2559
+	 * @param        EE_Base_Class /int $id_or_obj
2560
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2561
+	 * @param string $relationName key in EEM_Base::_relations
2562
+	 * @return boolean of success
2563
+	 * @throws EE_Error
2564
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2565
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2566
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2567
+	 *                             because these will be inserted in any new rows created as well.
2568
+	 */
2569
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2570
+	{
2571
+		$relation_obj = $this->related_settings_for($relationName);
2572
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2573
+	}
2574
+
2575
+
2576
+
2577
+	/**
2578
+	 * @param mixed           $id_or_obj
2579
+	 * @param string          $relationName
2580
+	 * @param array           $where_query_params
2581
+	 * @param EE_Base_Class[] objects to which relations were removed
2582
+	 * @return \EE_Base_Class[]
2583
+	 * @throws EE_Error
2584
+	 */
2585
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2586
+	{
2587
+		$relation_obj = $this->related_settings_for($relationName);
2588
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2589
+	}
2590
+
2591
+
2592
+
2593
+	/**
2594
+	 * Gets all the related items of the specified $model_name, using $query_params.
2595
+	 * Note: by default, we remove the "default query params"
2596
+	 * because we want to get even deleted items etc.
2597
+	 *
2598
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2599
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2600
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2601
+	 * @return EE_Base_Class[]
2602
+	 * @throws EE_Error
2603
+	 */
2604
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2605
+	{
2606
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2607
+		$relation_settings = $this->related_settings_for($model_name);
2608
+		return $relation_settings->get_all_related($model_obj, $query_params);
2609
+	}
2610
+
2611
+
2612
+
2613
+	/**
2614
+	 * Deletes all the model objects across the relation indicated by $model_name
2615
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2616
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2617
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2618
+	 *
2619
+	 * @param EE_Base_Class|int|string $id_or_obj
2620
+	 * @param string                   $model_name
2621
+	 * @param array                    $query_params
2622
+	 * @return int how many deleted
2623
+	 * @throws EE_Error
2624
+	 */
2625
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2626
+	{
2627
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2628
+		$relation_settings = $this->related_settings_for($model_name);
2629
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2630
+	}
2631
+
2632
+
2633
+
2634
+	/**
2635
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2636
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2637
+	 * the model objects can't be hard deleted because of blocking related model objects,
2638
+	 * just does a soft-delete on them instead.
2639
+	 *
2640
+	 * @param EE_Base_Class|int|string $id_or_obj
2641
+	 * @param string                   $model_name
2642
+	 * @param array                    $query_params
2643
+	 * @return int how many deleted
2644
+	 * @throws EE_Error
2645
+	 */
2646
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2647
+	{
2648
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2649
+		$relation_settings = $this->related_settings_for($model_name);
2650
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2651
+	}
2652
+
2653
+
2654
+
2655
+	/**
2656
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2657
+	 * unless otherwise specified in the $query_params
2658
+	 *
2659
+	 * @param        int             /EE_Base_Class $id_or_obj
2660
+	 * @param string $model_name     like 'Event', or 'Registration'
2661
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2662
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2663
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2664
+	 *                               that by the setting $distinct to TRUE;
2665
+	 * @return int
2666
+	 * @throws EE_Error
2667
+	 */
2668
+	public function count_related(
2669
+		$id_or_obj,
2670
+		$model_name,
2671
+		$query_params = array(),
2672
+		$field_to_count = null,
2673
+		$distinct = false
2674
+	) {
2675
+		$related_model = $this->get_related_model_obj($model_name);
2676
+		// we're just going to use the query params on the related model's normal get_all query,
2677
+		// except add a condition to say to match the current mod
2678
+		if (! isset($query_params['default_where_conditions'])) {
2679
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2680
+		}
2681
+		$this_model_name = $this->get_this_model_name();
2682
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2683
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2684
+		return $related_model->count($query_params, $field_to_count, $distinct);
2685
+	}
2686
+
2687
+
2688
+
2689
+	/**
2690
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2691
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2692
+	 *
2693
+	 * @param        int           /EE_Base_Class $id_or_obj
2694
+	 * @param string $model_name   like 'Event', or 'Registration'
2695
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2696
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2697
+	 * @return float
2698
+	 * @throws EE_Error
2699
+	 */
2700
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2701
+	{
2702
+		$related_model = $this->get_related_model_obj($model_name);
2703
+		if (! is_array($query_params)) {
2704
+			EE_Error::doing_it_wrong(
2705
+				'EEM_Base::sum_related',
2706
+				sprintf(
2707
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2708
+					gettype($query_params)
2709
+				),
2710
+				'4.6.0'
2711
+			);
2712
+			$query_params = array();
2713
+		}
2714
+		// we're just going to use the query params on the related model's normal get_all query,
2715
+		// except add a condition to say to match the current mod
2716
+		if (! isset($query_params['default_where_conditions'])) {
2717
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2718
+		}
2719
+		$this_model_name = $this->get_this_model_name();
2720
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2721
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2722
+		return $related_model->sum($query_params, $field_to_sum);
2723
+	}
2724
+
2725
+
2726
+
2727
+	/**
2728
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2729
+	 * $modelObject
2730
+	 *
2731
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2732
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2733
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2734
+	 * @return EE_Base_Class
2735
+	 * @throws EE_Error
2736
+	 */
2737
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2738
+	{
2739
+		$query_params['limit'] = 1;
2740
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2741
+		if ($results) {
2742
+			return array_shift($results);
2743
+		}
2744
+		return null;
2745
+	}
2746
+
2747
+
2748
+
2749
+	/**
2750
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2751
+	 *
2752
+	 * @return string
2753
+	 */
2754
+	public function get_this_model_name()
2755
+	{
2756
+		return str_replace("EEM_", "", get_class($this));
2757
+	}
2758
+
2759
+
2760
+
2761
+	/**
2762
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2763
+	 *
2764
+	 * @return EE_Any_Foreign_Model_Name_Field
2765
+	 * @throws EE_Error
2766
+	 */
2767
+	public function get_field_containing_related_model_name()
2768
+	{
2769
+		foreach ($this->field_settings(true) as $field) {
2770
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2771
+				$field_with_model_name = $field;
2772
+			}
2773
+		}
2774
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2775
+			throw new EE_Error(sprintf(
2776
+				esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2777
+				$this->get_this_model_name()
2778
+			));
2779
+		}
2780
+		return $field_with_model_name;
2781
+	}
2782
+
2783
+
2784
+
2785
+	/**
2786
+	 * Inserts a new entry into the database, for each table.
2787
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2788
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2789
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2790
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2791
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2792
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2793
+	 *
2794
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2795
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2796
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2797
+	 *                              of EEM_Base)
2798
+	 * @return int|string new primary key on main table that got inserted
2799
+	 * @throws EE_Error
2800
+	 */
2801
+	public function insert($field_n_values)
2802
+	{
2803
+		/**
2804
+		 * Filters the fields and their values before inserting an item using the models
2805
+		 *
2806
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2807
+		 * @param EEM_Base $model           the model used
2808
+		 */
2809
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2810
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2811
+			$main_table = $this->_get_main_table();
2812
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2813
+			if ($new_id !== false) {
2814
+				foreach ($this->_get_other_tables() as $other_table) {
2815
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2816
+				}
2817
+			}
2818
+			/**
2819
+			 * Done just after attempting to insert a new model object
2820
+			 *
2821
+			 * @param EEM_Base   $model           used
2822
+			 * @param array      $fields_n_values fields and their values
2823
+			 * @param int|string the              ID of the newly-inserted model object
2824
+			 */
2825
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2826
+			return $new_id;
2827
+		}
2828
+		return false;
2829
+	}
2830
+
2831
+
2832
+
2833
+	/**
2834
+	 * Checks that the result would satisfy the unique indexes on this model
2835
+	 *
2836
+	 * @param array  $field_n_values
2837
+	 * @param string $action
2838
+	 * @return boolean
2839
+	 * @throws EE_Error
2840
+	 */
2841
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2842
+	{
2843
+		foreach ($this->unique_indexes() as $index_name => $index) {
2844
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2845
+			if ($this->exists(array($uniqueness_where_params))) {
2846
+				EE_Error::add_error(
2847
+					sprintf(
2848
+						esc_html__(
2849
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2850
+							"event_espresso"
2851
+						),
2852
+						$action,
2853
+						$this->_get_class_name(),
2854
+						$index_name,
2855
+						implode(",", $index->field_names()),
2856
+						http_build_query($uniqueness_where_params)
2857
+					),
2858
+					__FILE__,
2859
+					__FUNCTION__,
2860
+					__LINE__
2861
+				);
2862
+				return false;
2863
+			}
2864
+		}
2865
+		return true;
2866
+	}
2867
+
2868
+
2869
+
2870
+	/**
2871
+	 * Checks the database for an item that conflicts (ie, if this item were
2872
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2873
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2874
+	 * can be either an EE_Base_Class or an array of fields n values
2875
+	 *
2876
+	 * @param EE_Base_Class|array $obj_or_fields_array
2877
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2878
+	 *                                                 when looking for conflicts
2879
+	 *                                                 (ie, if false, we ignore the model object's primary key
2880
+	 *                                                 when finding "conflicts". If true, it's also considered).
2881
+	 *                                                 Only works for INT primary key,
2882
+	 *                                                 STRING primary keys cannot be ignored
2883
+	 * @throws EE_Error
2884
+	 * @return EE_Base_Class|array
2885
+	 */
2886
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2887
+	{
2888
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2889
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2890
+		} elseif (is_array($obj_or_fields_array)) {
2891
+			$fields_n_values = $obj_or_fields_array;
2892
+		} else {
2893
+			throw new EE_Error(
2894
+				sprintf(
2895
+					esc_html__(
2896
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2897
+						"event_espresso"
2898
+					),
2899
+					get_class($this),
2900
+					$obj_or_fields_array
2901
+				)
2902
+			);
2903
+		}
2904
+		$query_params = array();
2905
+		if (
2906
+			$this->has_primary_key_field()
2907
+			&& ($include_primary_key
2908
+				|| $this->get_primary_key_field()
2909
+				   instanceof
2910
+				   EE_Primary_Key_String_Field)
2911
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2912
+		) {
2913
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2914
+		}
2915
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2916
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2917
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2918
+		}
2919
+		// if there is nothing to base this search on, then we shouldn't find anything
2920
+		if (empty($query_params)) {
2921
+			return array();
2922
+		}
2923
+		return $this->get_one($query_params);
2924
+	}
2925
+
2926
+
2927
+
2928
+	/**
2929
+	 * Like count, but is optimized and returns a boolean instead of an int
2930
+	 *
2931
+	 * @param array $query_params
2932
+	 * @return boolean
2933
+	 * @throws EE_Error
2934
+	 */
2935
+	public function exists($query_params)
2936
+	{
2937
+		$query_params['limit'] = 1;
2938
+		return $this->count($query_params) > 0;
2939
+	}
2940
+
2941
+
2942
+
2943
+	/**
2944
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2945
+	 *
2946
+	 * @param int|string $id
2947
+	 * @return boolean
2948
+	 * @throws EE_Error
2949
+	 */
2950
+	public function exists_by_ID($id)
2951
+	{
2952
+		return $this->exists(
2953
+			array(
2954
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2955
+				array(
2956
+					$this->primary_key_name() => $id,
2957
+				),
2958
+			)
2959
+		);
2960
+	}
2961
+
2962
+
2963
+
2964
+	/**
2965
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2966
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2967
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2968
+	 * on the main table)
2969
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2970
+	 * cases where we want to call it directly rather than via insert().
2971
+	 *
2972
+	 * @access   protected
2973
+	 * @param EE_Table_Base $table
2974
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2975
+	 *                                       float
2976
+	 * @param int           $new_id          for now we assume only int keys
2977
+	 * @throws EE_Error
2978
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2979
+	 * @return int ID of new row inserted, or FALSE on failure
2980
+	 */
2981
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2982
+	{
2983
+		global $wpdb;
2984
+		$insertion_col_n_values = array();
2985
+		$format_for_insertion = array();
2986
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2987
+		foreach ($fields_on_table as $field_name => $field_obj) {
2988
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2989
+			if ($field_obj->is_auto_increment()) {
2990
+				continue;
2991
+			}
2992
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2993
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2994
+			if ($prepared_value !== null) {
2995
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2996
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2997
+			}
2998
+		}
2999
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3000
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3001
+			// so add the fk to the main table as a column
3002
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3003
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3004
+		}
3005
+		// insert the new entry
3006
+		$result = $this->_do_wpdb_query(
3007
+			'insert',
3008
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3009
+		);
3010
+		if ($result === false) {
3011
+			return false;
3012
+		}
3013
+		// ok, now what do we return for the ID of the newly-inserted thing?
3014
+		if ($this->has_primary_key_field()) {
3015
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3016
+				return $wpdb->insert_id;
3017
+			}
3018
+			// it's not an auto-increment primary key, so
3019
+			// it must have been supplied
3020
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3021
+		}
3022
+		// we can't return a  primary key because there is none. instead return
3023
+		// a unique string indicating this model
3024
+		return $this->get_index_primary_key_string($fields_n_values);
3025
+	}
3026
+
3027
+
3028
+
3029
+	/**
3030
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3031
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3032
+	 * and there is no default, we pass it along. WPDB will take care of it)
3033
+	 *
3034
+	 * @param EE_Model_Field_Base $field_obj
3035
+	 * @param array               $fields_n_values
3036
+	 * @return mixed string|int|float depending on what the table column will be expecting
3037
+	 * @throws EE_Error
3038
+	 */
3039
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3040
+	{
3041
+		// if this field doesn't allow nullable, don't allow it
3042
+		if (
3043
+			! $field_obj->is_nullable()
3044
+			&& (
3045
+				! isset($fields_n_values[ $field_obj->get_name() ])
3046
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3047
+			)
3048
+		) {
3049
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3050
+		}
3051
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3052
+			? $fields_n_values[ $field_obj->get_name() ]
3053
+			: null;
3054
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3055
+	}
3056
+
3057
+
3058
+
3059
+	/**
3060
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3061
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3062
+	 * the field's prepare_for_set() method.
3063
+	 *
3064
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3065
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3066
+	 *                                   top of file)
3067
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3068
+	 *                                   $value is a custom selection
3069
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3070
+	 */
3071
+	private function _prepare_value_for_use_in_db($value, $field)
3072
+	{
3073
+		if ($field && $field instanceof EE_Model_Field_Base) {
3074
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3075
+			switch ($this->_values_already_prepared_by_model_object) {
3076
+				/** @noinspection PhpMissingBreakStatementInspection */
3077
+				case self::not_prepared_by_model_object:
3078
+					$value = $field->prepare_for_set($value);
3079
+				// purposefully left out "return"
3080
+				case self::prepared_by_model_object:
3081
+					/** @noinspection SuspiciousAssignmentsInspection */
3082
+					$value = $field->prepare_for_use_in_db($value);
3083
+				case self::prepared_for_use_in_db:
3084
+					// leave the value alone
3085
+			}
3086
+			return $value;
3087
+			// phpcs:enable
3088
+		}
3089
+		return $value;
3090
+	}
3091
+
3092
+
3093
+
3094
+	/**
3095
+	 * Returns the main table on this model
3096
+	 *
3097
+	 * @return EE_Primary_Table
3098
+	 * @throws EE_Error
3099
+	 */
3100
+	protected function _get_main_table()
3101
+	{
3102
+		foreach ($this->_tables as $table) {
3103
+			if ($table instanceof EE_Primary_Table) {
3104
+				return $table;
3105
+			}
3106
+		}
3107
+		throw new EE_Error(sprintf(esc_html__(
3108
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3109
+			'event_espresso'
3110
+		), get_class($this)));
3111
+	}
3112
+
3113
+
3114
+
3115
+	/**
3116
+	 * table
3117
+	 * returns EE_Primary_Table table name
3118
+	 *
3119
+	 * @return string
3120
+	 * @throws EE_Error
3121
+	 */
3122
+	public function table()
3123
+	{
3124
+		return $this->_get_main_table()->get_table_name();
3125
+	}
3126
+
3127
+
3128
+
3129
+	/**
3130
+	 * table
3131
+	 * returns first EE_Secondary_Table table name
3132
+	 *
3133
+	 * @return string
3134
+	 */
3135
+	public function second_table()
3136
+	{
3137
+		// grab second table from tables array
3138
+		$second_table = end($this->_tables);
3139
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3140
+	}
3141
+
3142
+
3143
+
3144
+	/**
3145
+	 * get_table_obj_by_alias
3146
+	 * returns table name given it's alias
3147
+	 *
3148
+	 * @param string $table_alias
3149
+	 * @return EE_Primary_Table | EE_Secondary_Table
3150
+	 */
3151
+	public function get_table_obj_by_alias($table_alias = '')
3152
+	{
3153
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3154
+	}
3155
+
3156
+
3157
+
3158
+	/**
3159
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3160
+	 *
3161
+	 * @return EE_Secondary_Table[]
3162
+	 */
3163
+	protected function _get_other_tables()
3164
+	{
3165
+		$other_tables = array();
3166
+		foreach ($this->_tables as $table_alias => $table) {
3167
+			if ($table instanceof EE_Secondary_Table) {
3168
+				$other_tables[ $table_alias ] = $table;
3169
+			}
3170
+		}
3171
+		return $other_tables;
3172
+	}
3173
+
3174
+
3175
+
3176
+	/**
3177
+	 * Finds all the fields that correspond to the given table
3178
+	 *
3179
+	 * @param string $table_alias , array key in EEM_Base::_tables
3180
+	 * @return EE_Model_Field_Base[]
3181
+	 */
3182
+	public function _get_fields_for_table($table_alias)
3183
+	{
3184
+		return $this->_fields[ $table_alias ];
3185
+	}
3186
+
3187
+
3188
+
3189
+	/**
3190
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3191
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3192
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3193
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3194
+	 * related Registration, Transaction, and Payment models.
3195
+	 *
3196
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3197
+	 * @return EE_Model_Query_Info_Carrier
3198
+	 * @throws EE_Error
3199
+	 */
3200
+	public function _extract_related_models_from_query($query_params)
3201
+	{
3202
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3203
+		if (array_key_exists(0, $query_params)) {
3204
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3205
+		}
3206
+		if (array_key_exists('group_by', $query_params)) {
3207
+			if (is_array($query_params['group_by'])) {
3208
+				$this->_extract_related_models_from_sub_params_array_values(
3209
+					$query_params['group_by'],
3210
+					$query_info_carrier,
3211
+					'group_by'
3212
+				);
3213
+			} elseif (! empty($query_params['group_by'])) {
3214
+				$this->_extract_related_model_info_from_query_param(
3215
+					$query_params['group_by'],
3216
+					$query_info_carrier,
3217
+					'group_by'
3218
+				);
3219
+			}
3220
+		}
3221
+		if (array_key_exists('having', $query_params)) {
3222
+			$this->_extract_related_models_from_sub_params_array_keys(
3223
+				$query_params[0],
3224
+				$query_info_carrier,
3225
+				'having'
3226
+			);
3227
+		}
3228
+		if (array_key_exists('order_by', $query_params)) {
3229
+			if (is_array($query_params['order_by'])) {
3230
+				$this->_extract_related_models_from_sub_params_array_keys(
3231
+					$query_params['order_by'],
3232
+					$query_info_carrier,
3233
+					'order_by'
3234
+				);
3235
+			} elseif (! empty($query_params['order_by'])) {
3236
+				$this->_extract_related_model_info_from_query_param(
3237
+					$query_params['order_by'],
3238
+					$query_info_carrier,
3239
+					'order_by'
3240
+				);
3241
+			}
3242
+		}
3243
+		if (array_key_exists('force_join', $query_params)) {
3244
+			$this->_extract_related_models_from_sub_params_array_values(
3245
+				$query_params['force_join'],
3246
+				$query_info_carrier,
3247
+				'force_join'
3248
+			);
3249
+		}
3250
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3251
+		return $query_info_carrier;
3252
+	}
3253
+
3254
+
3255
+
3256
+	/**
3257
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3258
+	 *
3259
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3260
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3261
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3262
+	 * @throws EE_Error
3263
+	 * @return \EE_Model_Query_Info_Carrier
3264
+	 */
3265
+	private function _extract_related_models_from_sub_params_array_keys(
3266
+		$sub_query_params,
3267
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3268
+		$query_param_type
3269
+	) {
3270
+		if (! empty($sub_query_params)) {
3271
+			$sub_query_params = (array) $sub_query_params;
3272
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3273
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3274
+				$this->_extract_related_model_info_from_query_param(
3275
+					$param,
3276
+					$model_query_info_carrier,
3277
+					$query_param_type
3278
+				);
3279
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3280
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3281
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3282
+				// of array('Registration.TXN_ID'=>23)
3283
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
+					if (! is_array($possibly_array_of_params)) {
3286
+						throw new EE_Error(sprintf(
3287
+							esc_html__(
3288
+								"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'))",
3289
+								"event_espresso"
3290
+							),
3291
+							$param,
3292
+							$possibly_array_of_params
3293
+						));
3294
+					}
3295
+					$this->_extract_related_models_from_sub_params_array_keys(
3296
+						$possibly_array_of_params,
3297
+						$model_query_info_carrier,
3298
+						$query_param_type
3299
+					);
3300
+				} elseif (
3301
+					$query_param_type === 0 // ie WHERE
3302
+						  && is_array($possibly_array_of_params)
3303
+						  && isset($possibly_array_of_params[2])
3304
+						  && $possibly_array_of_params[2] == true
3305
+				) {
3306
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3307
+					// indicating that $possible_array_of_params[1] is actually a field name,
3308
+					// from which we should extract query parameters!
3309
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3310
+						throw new EE_Error(sprintf(esc_html__(
3311
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3312
+							"event_espresso"
3313
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3314
+					}
3315
+					$this->_extract_related_model_info_from_query_param(
3316
+						$possibly_array_of_params[1],
3317
+						$model_query_info_carrier,
3318
+						$query_param_type
3319
+					);
3320
+				}
3321
+			}
3322
+		}
3323
+		return $model_query_info_carrier;
3324
+	}
3325
+
3326
+
3327
+
3328
+	/**
3329
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3330
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3331
+	 *
3332
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3333
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3334
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3335
+	 * @throws EE_Error
3336
+	 * @return \EE_Model_Query_Info_Carrier
3337
+	 */
3338
+	private function _extract_related_models_from_sub_params_array_values(
3339
+		$sub_query_params,
3340
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3341
+		$query_param_type
3342
+	) {
3343
+		if (! empty($sub_query_params)) {
3344
+			if (! is_array($sub_query_params)) {
3345
+				throw new EE_Error(sprintf(
3346
+					esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3347
+					$sub_query_params
3348
+				));
3349
+			}
3350
+			foreach ($sub_query_params as $param) {
3351
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3352
+				$this->_extract_related_model_info_from_query_param(
3353
+					$param,
3354
+					$model_query_info_carrier,
3355
+					$query_param_type
3356
+				);
3357
+			}
3358
+		}
3359
+		return $model_query_info_carrier;
3360
+	}
3361
+
3362
+
3363
+	/**
3364
+	 * Extract all the query parts from  model query params
3365
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3366
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3367
+	 * but use them in a different order. Eg, we need to know what models we are querying
3368
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3369
+	 * other models before we can finalize the where clause SQL.
3370
+	 *
3371
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3372
+	 * @throws EE_Error
3373
+	 * @return EE_Model_Query_Info_Carrier
3374
+	 * @throws ModelConfigurationException
3375
+	 */
3376
+	public function _create_model_query_info_carrier($query_params)
3377
+	{
3378
+		if (! is_array($query_params)) {
3379
+			EE_Error::doing_it_wrong(
3380
+				'EEM_Base::_create_model_query_info_carrier',
3381
+				sprintf(
3382
+					esc_html__(
3383
+						'$query_params should be an array, you passed a variable of type %s',
3384
+						'event_espresso'
3385
+					),
3386
+					gettype($query_params)
3387
+				),
3388
+				'4.6.0'
3389
+			);
3390
+			$query_params = array();
3391
+		}
3392
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3393
+		// first check if we should alter the query to account for caps or not
3394
+		// because the caps might require us to do extra joins
3395
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3396
+			$query_params[0] = array_replace_recursive(
3397
+				$query_params[0],
3398
+				$this->caps_where_conditions(
3399
+					$query_params['caps']
3400
+				)
3401
+			);
3402
+		}
3403
+
3404
+		// check if we should alter the query to remove data related to protected
3405
+		// custom post types
3406
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3407
+			$where_param_key_for_password = $this->modelChainAndPassword();
3408
+			// only include if related to a cpt where no password has been set
3409
+			$query_params[0]['OR*nopassword'] = array(
3410
+				$where_param_key_for_password => '',
3411
+				$where_param_key_for_password . '*' => array('IS_NULL')
3412
+			);
3413
+		}
3414
+		$query_object = $this->_extract_related_models_from_query($query_params);
3415
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3416
+		foreach ($query_params[0] as $key => $value) {
3417
+			if (is_int($key)) {
3418
+				throw new EE_Error(
3419
+					sprintf(
3420
+						esc_html__(
3421
+							"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.",
3422
+							"event_espresso"
3423
+						),
3424
+						$key,
3425
+						var_export($value, true),
3426
+						var_export($query_params, true),
3427
+						get_class($this)
3428
+					)
3429
+				);
3430
+			}
3431
+		}
3432
+		if (
3433
+			array_key_exists('default_where_conditions', $query_params)
3434
+			&& ! empty($query_params['default_where_conditions'])
3435
+		) {
3436
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3437
+		} else {
3438
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3439
+		}
3440
+		$query_params[0] = array_merge(
3441
+			$this->_get_default_where_conditions_for_models_in_query(
3442
+				$query_object,
3443
+				$use_default_where_conditions,
3444
+				$query_params[0]
3445
+			),
3446
+			$query_params[0]
3447
+		);
3448
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3449
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3450
+		// So we need to setup a subquery and use that for the main join.
3451
+		// Note for now this only works on the primary table for the model.
3452
+		// So for instance, you could set the limit array like this:
3453
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3454
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3455
+			$query_object->set_main_model_join_sql(
3456
+				$this->_construct_limit_join_select(
3457
+					$query_params['on_join_limit'][0],
3458
+					$query_params['on_join_limit'][1]
3459
+				)
3460
+			);
3461
+		}
3462
+		// set limit
3463
+		if (array_key_exists('limit', $query_params)) {
3464
+			if (is_array($query_params['limit'])) {
3465
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3466
+					$e = sprintf(
3467
+						esc_html__(
3468
+							"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)",
3469
+							"event_espresso"
3470
+						),
3471
+						http_build_query($query_params['limit'])
3472
+					);
3473
+					throw new EE_Error($e . "|" . $e);
3474
+				}
3475
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3476
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3477
+			} elseif (! empty($query_params['limit'])) {
3478
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3479
+			}
3480
+		}
3481
+		// set order by
3482
+		if (array_key_exists('order_by', $query_params)) {
3483
+			if (is_array($query_params['order_by'])) {
3484
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3485
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3486
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3487
+				if (array_key_exists('order', $query_params)) {
3488
+					throw new EE_Error(
3489
+						sprintf(
3490
+							esc_html__(
3491
+								"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 ",
3492
+								"event_espresso"
3493
+							),
3494
+							get_class($this),
3495
+							implode(", ", array_keys($query_params['order_by'])),
3496
+							implode(", ", $query_params['order_by']),
3497
+							$query_params['order']
3498
+						)
3499
+					);
3500
+				}
3501
+				$this->_extract_related_models_from_sub_params_array_keys(
3502
+					$query_params['order_by'],
3503
+					$query_object,
3504
+					'order_by'
3505
+				);
3506
+				// assume it's an array of fields to order by
3507
+				$order_array = array();
3508
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3509
+					$order = $this->_extract_order($order);
3510
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3511
+				}
3512
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3513
+			} elseif (! empty($query_params['order_by'])) {
3514
+				$this->_extract_related_model_info_from_query_param(
3515
+					$query_params['order_by'],
3516
+					$query_object,
3517
+					'order',
3518
+					$query_params['order_by']
3519
+				);
3520
+				$order = isset($query_params['order'])
3521
+					? $this->_extract_order($query_params['order'])
3522
+					: 'DESC';
3523
+				$query_object->set_order_by_sql(
3524
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3525
+				);
3526
+			}
3527
+		}
3528
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3529
+		if (
3530
+			! array_key_exists('order_by', $query_params)
3531
+			&& array_key_exists('order', $query_params)
3532
+			&& ! empty($query_params['order'])
3533
+		) {
3534
+			$pk_field = $this->get_primary_key_field();
3535
+			$order = $this->_extract_order($query_params['order']);
3536
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3537
+		}
3538
+		// set group by
3539
+		if (array_key_exists('group_by', $query_params)) {
3540
+			if (is_array($query_params['group_by'])) {
3541
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3542
+				$group_by_array = array();
3543
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3544
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3545
+				}
3546
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3547
+			} elseif (! empty($query_params['group_by'])) {
3548
+				$query_object->set_group_by_sql(
3549
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3550
+				);
3551
+			}
3552
+		}
3553
+		// set having
3554
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3555
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3556
+		}
3557
+		// now, just verify they didn't pass anything wack
3558
+		foreach ($query_params as $query_key => $query_value) {
3559
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3560
+				throw new EE_Error(
3561
+					sprintf(
3562
+						esc_html__(
3563
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3564
+							'event_espresso'
3565
+						),
3566
+						$query_key,
3567
+						get_class($this),
3568
+						//                      print_r( $this->_allowed_query_params, TRUE )
3569
+						implode(',', $this->_allowed_query_params)
3570
+					)
3571
+				);
3572
+			}
3573
+		}
3574
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3575
+		if (empty($main_model_join_sql)) {
3576
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3577
+		}
3578
+		return $query_object;
3579
+	}
3580
+
3581
+
3582
+
3583
+	/**
3584
+	 * Gets the where conditions that should be imposed on the query based on the
3585
+	 * context (eg reading frontend, backend, edit or delete).
3586
+	 *
3587
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3588
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3589
+	 * @throws EE_Error
3590
+	 */
3591
+	public function caps_where_conditions($context = self::caps_read)
3592
+	{
3593
+		EEM_Base::verify_is_valid_cap_context($context);
3594
+		$cap_where_conditions = array();
3595
+		$cap_restrictions = $this->caps_missing($context);
3596
+		/**
3597
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3598
+		 */
3599
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3600
+			$cap_where_conditions = array_replace_recursive(
3601
+				$cap_where_conditions,
3602
+				$restriction_if_no_cap->get_default_where_conditions()
3603
+			);
3604
+		}
3605
+		return apply_filters(
3606
+			'FHEE__EEM_Base__caps_where_conditions__return',
3607
+			$cap_where_conditions,
3608
+			$this,
3609
+			$context,
3610
+			$cap_restrictions
3611
+		);
3612
+	}
3613
+
3614
+
3615
+
3616
+	/**
3617
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3618
+	 * otherwise throws an exception
3619
+	 *
3620
+	 * @param string $should_be_order_string
3621
+	 * @return string either ASC, asc, DESC or desc
3622
+	 * @throws EE_Error
3623
+	 */
3624
+	private function _extract_order($should_be_order_string)
3625
+	{
3626
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3627
+			return $should_be_order_string;
3628
+		}
3629
+		throw new EE_Error(
3630
+			sprintf(
3631
+				esc_html__(
3632
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3633
+					"event_espresso"
3634
+				),
3635
+				get_class($this),
3636
+				$should_be_order_string
3637
+			)
3638
+		);
3639
+	}
3640
+
3641
+
3642
+
3643
+	/**
3644
+	 * Looks at all the models which are included in this query, and asks each
3645
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3646
+	 * so they can be merged
3647
+	 *
3648
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3649
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3650
+	 *                                                                  'none' means NO default where conditions will
3651
+	 *                                                                  be used AT ALL during this query.
3652
+	 *                                                                  'other_models_only' means default where
3653
+	 *                                                                  conditions from other models will be used, but
3654
+	 *                                                                  not for this primary model. 'all', the default,
3655
+	 *                                                                  means default where conditions will apply as
3656
+	 *                                                                  normal
3657
+	 * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3658
+	 * @throws EE_Error
3659
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3660
+	 */
3661
+	private function _get_default_where_conditions_for_models_in_query(
3662
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3663
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3664
+		$where_query_params = array()
3665
+	) {
3666
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3667
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3668
+			throw new EE_Error(sprintf(
3669
+				esc_html__(
3670
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3671
+					"event_espresso"
3672
+				),
3673
+				$use_default_where_conditions,
3674
+				implode(", ", $allowed_used_default_where_conditions_values)
3675
+			));
3676
+		}
3677
+		$universal_query_params = array();
3678
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3679
+			$universal_query_params = $this->_get_default_where_conditions();
3680
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3681
+			$universal_query_params = $this->_get_minimum_where_conditions();
3682
+		}
3683
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3684
+			$related_model = $this->get_related_model_obj($model_name);
3685
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3686
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3687
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3688
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3689
+			} else {
3690
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3691
+				continue;
3692
+			}
3693
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3694
+				$related_model_universal_where_params,
3695
+				$where_query_params,
3696
+				$related_model,
3697
+				$model_relation_path
3698
+			);
3699
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3700
+				$universal_query_params,
3701
+				$overrides
3702
+			);
3703
+		}
3704
+		return $universal_query_params;
3705
+	}
3706
+
3707
+
3708
+
3709
+	/**
3710
+	 * Determines whether or not we should use default where conditions for the model in question
3711
+	 * (this model, or other related models).
3712
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3713
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3714
+	 * We should use default where conditions on related models when they requested to use default where conditions
3715
+	 * on all models, or specifically just on other related models
3716
+	 * @param      $default_where_conditions_value
3717
+	 * @param bool $for_this_model false means this is for OTHER related models
3718
+	 * @return bool
3719
+	 */
3720
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3721
+	{
3722
+		return (
3723
+				   $for_this_model
3724
+				   && in_array(
3725
+					   $default_where_conditions_value,
3726
+					   array(
3727
+						   EEM_Base::default_where_conditions_all,
3728
+						   EEM_Base::default_where_conditions_this_only,
3729
+						   EEM_Base::default_where_conditions_minimum_others,
3730
+					   ),
3731
+					   true
3732
+				   )
3733
+			   )
3734
+			   || (
3735
+				   ! $for_this_model
3736
+				   && in_array(
3737
+					   $default_where_conditions_value,
3738
+					   array(
3739
+						   EEM_Base::default_where_conditions_all,
3740
+						   EEM_Base::default_where_conditions_others_only,
3741
+					   ),
3742
+					   true
3743
+				   )
3744
+			   );
3745
+	}
3746
+
3747
+	/**
3748
+	 * Determines whether or not we should use default minimum conditions for the model in question
3749
+	 * (this model, or other related models).
3750
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3751
+	 * where conditions.
3752
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3753
+	 * on this model or others
3754
+	 * @param      $default_where_conditions_value
3755
+	 * @param bool $for_this_model false means this is for OTHER related models
3756
+	 * @return bool
3757
+	 */
3758
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3759
+	{
3760
+		return (
3761
+				   $for_this_model
3762
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3763
+			   )
3764
+			   || (
3765
+				   ! $for_this_model
3766
+				   && in_array(
3767
+					   $default_where_conditions_value,
3768
+					   array(
3769
+						   EEM_Base::default_where_conditions_minimum_others,
3770
+						   EEM_Base::default_where_conditions_minimum_all,
3771
+					   ),
3772
+					   true
3773
+				   )
3774
+			   );
3775
+	}
3776
+
3777
+
3778
+	/**
3779
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3780
+	 * then we also add a special where condition which allows for that model's primary key
3781
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3782
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3783
+	 *
3784
+	 * @param array    $default_where_conditions
3785
+	 * @param array    $provided_where_conditions
3786
+	 * @param EEM_Base $model
3787
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3788
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3789
+	 * @throws EE_Error
3790
+	 */
3791
+	private function _override_defaults_or_make_null_friendly(
3792
+		$default_where_conditions,
3793
+		$provided_where_conditions,
3794
+		$model,
3795
+		$model_relation_path
3796
+	) {
3797
+		$null_friendly_where_conditions = array();
3798
+		$none_overridden = true;
3799
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3800
+		foreach ($default_where_conditions as $key => $val) {
3801
+			if (isset($provided_where_conditions[ $key ])) {
3802
+				$none_overridden = false;
3803
+			} else {
3804
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3805
+			}
3806
+		}
3807
+		if ($none_overridden && $default_where_conditions) {
3808
+			if ($model->has_primary_key_field()) {
3809
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3810
+																				. "."
3811
+																				. $model->primary_key_name() ] = array('IS NULL');
3812
+			}/*else{
3813 3813
                 //@todo NO PK, use other defaults
3814 3814
             }*/
3815
-        }
3816
-        return $null_friendly_where_conditions;
3817
-    }
3818
-
3819
-
3820
-
3821
-    /**
3822
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3823
-     * default where conditions on all get_all, update, and delete queries done by this model.
3824
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3825
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3826
-     *
3827
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3828
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3829
-     */
3830
-    private function _get_default_where_conditions($model_relation_path = null)
3831
-    {
3832
-        if ($this->_ignore_where_strategy) {
3833
-            return array();
3834
-        }
3835
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3836
-    }
3837
-
3838
-
3839
-
3840
-    /**
3841
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3842
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3843
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3844
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3845
-     * Similar to _get_default_where_conditions
3846
-     *
3847
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3848
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3849
-     */
3850
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3851
-    {
3852
-        if ($this->_ignore_where_strategy) {
3853
-            return array();
3854
-        }
3855
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3856
-    }
3857
-
3858
-
3859
-
3860
-    /**
3861
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3862
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3863
-     *
3864
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3865
-     * @return string
3866
-     * @throws EE_Error
3867
-     */
3868
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3869
-    {
3870
-        $selects = $this->_get_columns_to_select_for_this_model();
3871
-        foreach (
3872
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3873
-        ) {
3874
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3875
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3876
-            foreach ($other_model_selects as $key => $value) {
3877
-                $selects[] = $value;
3878
-            }
3879
-        }
3880
-        return implode(", ", $selects);
3881
-    }
3882
-
3883
-
3884
-
3885
-    /**
3886
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3887
-     * So that's going to be the columns for all the fields on the model
3888
-     *
3889
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3890
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3891
-     */
3892
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3893
-    {
3894
-        $fields = $this->field_settings();
3895
-        $selects = array();
3896
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3897
-            $model_relation_chain,
3898
-            $this->get_this_model_name()
3899
-        );
3900
-        foreach ($fields as $field_obj) {
3901
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3902
-                         . $field_obj->get_table_alias()
3903
-                         . "."
3904
-                         . $field_obj->get_table_column()
3905
-                         . " AS '"
3906
-                         . $table_alias_with_model_relation_chain_prefix
3907
-                         . $field_obj->get_table_alias()
3908
-                         . "."
3909
-                         . $field_obj->get_table_column()
3910
-                         . "'";
3911
-        }
3912
-        // make sure we are also getting the PKs of each table
3913
-        $tables = $this->get_tables();
3914
-        if (count($tables) > 1) {
3915
-            foreach ($tables as $table_obj) {
3916
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3917
-                                       . $table_obj->get_fully_qualified_pk_column();
3918
-                if (! in_array($qualified_pk_column, $selects)) {
3919
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3920
-                }
3921
-            }
3922
-        }
3923
-        return $selects;
3924
-    }
3925
-
3926
-
3927
-
3928
-    /**
3929
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3930
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3931
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3932
-     * SQL for joining, and the data types
3933
-     *
3934
-     * @param null|string                 $original_query_param
3935
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3936
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3937
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3938
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3939
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3940
-     *                                                          or 'Registration's
3941
-     * @param string                      $original_query_param what it originally was (eg
3942
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3943
-     *                                                          matches $query_param
3944
-     * @throws EE_Error
3945
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3946
-     */
3947
-    private function _extract_related_model_info_from_query_param(
3948
-        $query_param,
3949
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3950
-        $query_param_type,
3951
-        $original_query_param = null
3952
-    ) {
3953
-        if ($original_query_param === null) {
3954
-            $original_query_param = $query_param;
3955
-        }
3956
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3957
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3958
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3959
-        $allow_fields = in_array(
3960
-            $query_param_type,
3961
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3962
-            true
3963
-        );
3964
-        // check to see if we have a field on this model
3965
-        $this_model_fields = $this->field_settings(true);
3966
-        if (array_key_exists($query_param, $this_model_fields)) {
3967
-            if ($allow_fields) {
3968
-                return;
3969
-            }
3970
-            throw new EE_Error(
3971
-                sprintf(
3972
-                    esc_html__(
3973
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3974
-                        "event_espresso"
3975
-                    ),
3976
-                    $query_param,
3977
-                    get_class($this),
3978
-                    $query_param_type,
3979
-                    $original_query_param
3980
-                )
3981
-            );
3982
-        }
3983
-        // check if this is a special logic query param
3984
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3985
-            if ($allow_logic_query_params) {
3986
-                return;
3987
-            }
3988
-            throw new EE_Error(
3989
-                sprintf(
3990
-                    esc_html__(
3991
-                        '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',
3992
-                        'event_espresso'
3993
-                    ),
3994
-                    implode('", "', $this->_logic_query_param_keys),
3995
-                    $query_param,
3996
-                    get_class($this),
3997
-                    '<br />',
3998
-                    "\t"
3999
-                    . ' $passed_in_query_info = <pre>'
4000
-                    . print_r($passed_in_query_info, true)
4001
-                    . '</pre>'
4002
-                    . "\n\t"
4003
-                    . ' $query_param_type = '
4004
-                    . $query_param_type
4005
-                    . "\n\t"
4006
-                    . ' $original_query_param = '
4007
-                    . $original_query_param
4008
-                )
4009
-            );
4010
-        }
4011
-        // check if it's a custom selection
4012
-        if (
4013
-            $this->_custom_selections instanceof CustomSelects
4014
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4015
-        ) {
4016
-            return;
4017
-        }
4018
-        // check if has a model name at the beginning
4019
-        // and
4020
-        // check if it's a field on a related model
4021
-        if (
4022
-            $this->extractJoinModelFromQueryParams(
4023
-                $passed_in_query_info,
4024
-                $query_param,
4025
-                $original_query_param,
4026
-                $query_param_type
4027
-            )
4028
-        ) {
4029
-            return;
4030
-        }
4031
-
4032
-        // ok so $query_param didn't start with a model name
4033
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4034
-        // it's wack, that's what it is
4035
-        throw new EE_Error(
4036
-            sprintf(
4037
-                esc_html__(
4038
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4039
-                    "event_espresso"
4040
-                ),
4041
-                $query_param,
4042
-                get_class($this),
4043
-                $query_param_type,
4044
-                $original_query_param
4045
-            )
4046
-        );
4047
-    }
4048
-
4049
-
4050
-    /**
4051
-     * Extracts any possible join model information from the provided possible_join_string.
4052
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4053
-     * parts that should be added to the query.
4054
-     *
4055
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4056
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4057
-     * @param null|string                 $original_query_param
4058
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4059
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4060
-     * @return bool  returns true if a join was added and false if not.
4061
-     * @throws EE_Error
4062
-     */
4063
-    private function extractJoinModelFromQueryParams(
4064
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4065
-        $possible_join_string,
4066
-        $original_query_param,
4067
-        $query_parameter_type
4068
-    ) {
4069
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4070
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4071
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4072
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4073
-                if ($possible_join_string === '') {
4074
-                    // nothing left to $query_param
4075
-                    // we should actually end in a field name, not a model like this!
4076
-                    throw new EE_Error(
4077
-                        sprintf(
4078
-                            esc_html__(
4079
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4080
-                                "event_espresso"
4081
-                            ),
4082
-                            $possible_join_string,
4083
-                            $query_parameter_type,
4084
-                            get_class($this),
4085
-                            $valid_related_model_name
4086
-                        )
4087
-                    );
4088
-                }
4089
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4090
-                $related_model_obj->_extract_related_model_info_from_query_param(
4091
-                    $possible_join_string,
4092
-                    $query_info_carrier,
4093
-                    $query_parameter_type,
4094
-                    $original_query_param
4095
-                );
4096
-                return true;
4097
-            }
4098
-            if ($possible_join_string === $valid_related_model_name) {
4099
-                $this->_add_join_to_model(
4100
-                    $valid_related_model_name,
4101
-                    $query_info_carrier,
4102
-                    $original_query_param
4103
-                );
4104
-                return true;
4105
-            }
4106
-        }
4107
-        return false;
4108
-    }
4109
-
4110
-
4111
-    /**
4112
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4113
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4114
-     * @throws EE_Error
4115
-     */
4116
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4117
-    {
4118
-        if (
4119
-            $this->_custom_selections instanceof CustomSelects
4120
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4121
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4122
-            )
4123
-        ) {
4124
-            $original_selects = $this->_custom_selections->originalSelects();
4125
-            foreach ($original_selects as $alias => $select_configuration) {
4126
-                $this->extractJoinModelFromQueryParams(
4127
-                    $query_info_carrier,
4128
-                    $select_configuration[0],
4129
-                    $select_configuration[0],
4130
-                    'custom_selects'
4131
-                );
4132
-            }
4133
-        }
4134
-    }
4135
-
4136
-
4137
-
4138
-    /**
4139
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4140
-     * and store it on $passed_in_query_info
4141
-     *
4142
-     * @param string                      $model_name
4143
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4144
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4145
-     *                                                          model and $model_name. Eg, if we are querying Event,
4146
-     *                                                          and are adding a join to 'Payment' with the original
4147
-     *                                                          query param key
4148
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4149
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4150
-     *                                                          Payment wants to add default query params so that it
4151
-     *                                                          will know what models to prepend onto its default query
4152
-     *                                                          params or in case it wants to rename tables (in case
4153
-     *                                                          there are multiple joins to the same table)
4154
-     * @return void
4155
-     * @throws EE_Error
4156
-     */
4157
-    private function _add_join_to_model(
4158
-        $model_name,
4159
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4160
-        $original_query_param
4161
-    ) {
4162
-        $relation_obj = $this->related_settings_for($model_name);
4163
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4164
-        // check if the relation is HABTM, because then we're essentially doing two joins
4165
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4166
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4167
-            $join_model_obj = $relation_obj->get_join_model();
4168
-            // replace the model specified with the join model for this relation chain, whi
4169
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4170
-                $model_name,
4171
-                $join_model_obj->get_this_model_name(),
4172
-                $model_relation_chain
4173
-            );
4174
-            $passed_in_query_info->merge(
4175
-                new EE_Model_Query_Info_Carrier(
4176
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4177
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4178
-                )
4179
-            );
4180
-        }
4181
-        // now just join to the other table pointed to by the relation object, and add its data types
4182
-        $passed_in_query_info->merge(
4183
-            new EE_Model_Query_Info_Carrier(
4184
-                array($model_relation_chain => $model_name),
4185
-                $relation_obj->get_join_statement($model_relation_chain)
4186
-            )
4187
-        );
4188
-    }
4189
-
4190
-
4191
-
4192
-    /**
4193
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4194
-     *
4195
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4196
-     * @return string of SQL
4197
-     * @throws EE_Error
4198
-     */
4199
-    private function _construct_where_clause($where_params)
4200
-    {
4201
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4202
-        if ($SQL) {
4203
-            return " WHERE " . $SQL;
4204
-        }
4205
-        return '';
4206
-    }
4207
-
4208
-
4209
-
4210
-    /**
4211
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4212
-     * and should be passed HAVING parameters, not WHERE parameters
4213
-     *
4214
-     * @param array $having_params
4215
-     * @return string
4216
-     * @throws EE_Error
4217
-     */
4218
-    private function _construct_having_clause($having_params)
4219
-    {
4220
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4221
-        if ($SQL) {
4222
-            return " HAVING " . $SQL;
4223
-        }
4224
-        return '';
4225
-    }
4226
-
4227
-
4228
-    /**
4229
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4230
-     * Event_Meta.meta_value = 'foo'))"
4231
-     *
4232
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4233
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4234
-     * @throws EE_Error
4235
-     * @return string of SQL
4236
-     */
4237
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4238
-    {
4239
-        $where_clauses = array();
4240
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4241
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4242
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4243
-                switch ($query_param) {
4244
-                    case 'not':
4245
-                    case 'NOT':
4246
-                        $where_clauses[] = "! ("
4247
-                                           . $this->_construct_condition_clause_recursive(
4248
-                                               $op_and_value_or_sub_condition,
4249
-                                               $glue
4250
-                                           )
4251
-                                           . ")";
4252
-                        break;
4253
-                    case 'and':
4254
-                    case 'AND':
4255
-                        $where_clauses[] = " ("
4256
-                                           . $this->_construct_condition_clause_recursive(
4257
-                                               $op_and_value_or_sub_condition,
4258
-                                               ' AND '
4259
-                                           )
4260
-                                           . ")";
4261
-                        break;
4262
-                    case 'or':
4263
-                    case 'OR':
4264
-                        $where_clauses[] = " ("
4265
-                                           . $this->_construct_condition_clause_recursive(
4266
-                                               $op_and_value_or_sub_condition,
4267
-                                               ' OR '
4268
-                                           )
4269
-                                           . ")";
4270
-                        break;
4271
-                }
4272
-            } else {
4273
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4274
-                // if it's not a normal field, maybe it's a custom selection?
4275
-                if (! $field_obj) {
4276
-                    if ($this->_custom_selections instanceof CustomSelects) {
4277
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4278
-                    } else {
4279
-                        throw new EE_Error(sprintf(esc_html__(
4280
-                            "%s is neither a valid model field name, nor a custom selection",
4281
-                            "event_espresso"
4282
-                        ), $query_param));
4283
-                    }
4284
-                }
4285
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4286
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4287
-            }
4288
-        }
4289
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4290
-    }
4291
-
4292
-
4293
-
4294
-    /**
4295
-     * Takes the input parameter and extract the table name (alias) and column name
4296
-     *
4297
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4298
-     * @throws EE_Error
4299
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4300
-     */
4301
-    private function _deduce_column_name_from_query_param($query_param)
4302
-    {
4303
-        $field = $this->_deduce_field_from_query_param($query_param);
4304
-        if ($field) {
4305
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4306
-                $field->get_model_name(),
4307
-                $query_param
4308
-            );
4309
-            return $table_alias_prefix . $field->get_qualified_column();
4310
-        }
4311
-        if (
4312
-            $this->_custom_selections instanceof CustomSelects
4313
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4314
-        ) {
4315
-            // maybe it's custom selection item?
4316
-            // if so, just use it as the "column name"
4317
-            return $query_param;
4318
-        }
4319
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4320
-            ? implode(',', $this->_custom_selections->columnAliases())
4321
-            : '';
4322
-        throw new EE_Error(
4323
-            sprintf(
4324
-                esc_html__(
4325
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4326
-                    "event_espresso"
4327
-                ),
4328
-                $query_param,
4329
-                $custom_select_aliases
4330
-            )
4331
-        );
4332
-    }
4333
-
4334
-
4335
-
4336
-    /**
4337
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4338
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4339
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4340
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4341
-     *
4342
-     * @param string $condition_query_param_key
4343
-     * @return string
4344
-     */
4345
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4346
-    {
4347
-        $pos_of_star = strpos($condition_query_param_key, '*');
4348
-        if ($pos_of_star === false) {
4349
-            return $condition_query_param_key;
4350
-        }
4351
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4352
-        return $condition_query_param_sans_star;
4353
-    }
4354
-
4355
-
4356
-
4357
-    /**
4358
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4359
-     *
4360
-     * @param                            mixed      array | string    $op_and_value
4361
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4362
-     * @throws EE_Error
4363
-     * @return string
4364
-     */
4365
-    private function _construct_op_and_value($op_and_value, $field_obj)
4366
-    {
4367
-        if (is_array($op_and_value)) {
4368
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4369
-            if (! $operator) {
4370
-                $php_array_like_string = array();
4371
-                foreach ($op_and_value as $key => $value) {
4372
-                    $php_array_like_string[] = "$key=>$value";
4373
-                }
4374
-                throw new EE_Error(
4375
-                    sprintf(
4376
-                        esc_html__(
4377
-                            "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))",
4378
-                            "event_espresso"
4379
-                        ),
4380
-                        implode(",", $php_array_like_string)
4381
-                    )
4382
-                );
4383
-            }
4384
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4385
-        } else {
4386
-            $operator = '=';
4387
-            $value = $op_and_value;
4388
-        }
4389
-        // check to see if the value is actually another field
4390
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4391
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4392
-        }
4393
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4394
-            // in this case, the value should be an array, or at least a comma-separated list
4395
-            // it will need to handle a little differently
4396
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4397
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4398
-            return $operator . SP . $cleaned_value;
4399
-        }
4400
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4401
-            // the value should be an array with count of two.
4402
-            if (count($value) !== 2) {
4403
-                throw new EE_Error(
4404
-                    sprintf(
4405
-                        esc_html__(
4406
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4407
-                            'event_espresso'
4408
-                        ),
4409
-                        "BETWEEN"
4410
-                    )
4411
-                );
4412
-            }
4413
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4414
-            return $operator . SP . $cleaned_value;
4415
-        }
4416
-        if (in_array($operator, $this->valid_null_style_operators())) {
4417
-            if ($value !== null) {
4418
-                throw new EE_Error(
4419
-                    sprintf(
4420
-                        esc_html__(
4421
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4422
-                            "event_espresso"
4423
-                        ),
4424
-                        $value,
4425
-                        $operator
4426
-                    )
4427
-                );
4428
-            }
4429
-            return $operator;
4430
-        }
4431
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4432
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4433
-            // remove other junk. So just treat it as a string.
4434
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4435
-        }
4436
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4438
-        }
4439
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4440
-            throw new EE_Error(
4441
-                sprintf(
4442
-                    esc_html__(
4443
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4444
-                        'event_espresso'
4445
-                    ),
4446
-                    $operator,
4447
-                    $operator
4448
-                )
4449
-            );
4450
-        }
4451
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452
-            throw new EE_Error(
4453
-                sprintf(
4454
-                    esc_html__(
4455
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4456
-                        'event_espresso'
4457
-                    ),
4458
-                    $operator,
4459
-                    $operator
4460
-                )
4461
-            );
4462
-        }
4463
-        throw new EE_Error(
4464
-            sprintf(
4465
-                esc_html__(
4466
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4467
-                    "event_espresso"
4468
-                ),
4469
-                http_build_query($op_and_value)
4470
-            )
4471
-        );
4472
-    }
4473
-
4474
-
4475
-
4476
-    /**
4477
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4478
-     *
4479
-     * @param array                      $values
4480
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4481
-     *                                              '%s'
4482
-     * @return string
4483
-     * @throws EE_Error
4484
-     */
4485
-    public function _construct_between_value($values, $field_obj)
4486
-    {
4487
-        $cleaned_values = array();
4488
-        foreach ($values as $value) {
4489
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4490
-        }
4491
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4492
-    }
4493
-
4494
-
4495
-    /**
4496
-     * Takes an array or a comma-separated list of $values and cleans them
4497
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4498
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4499
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4500
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4501
-     *
4502
-     * @param mixed                      $values    array or comma-separated string
4503
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4504
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4505
-     * @throws EE_Error
4506
-     */
4507
-    public function _construct_in_value($values, $field_obj)
4508
-    {
4509
-        $prepped = [];
4510
-        // check if the value is a CSV list
4511
-        if (is_string($values)) {
4512
-            // in which case, turn it into an array
4513
-            $values = explode(',', $values);
4514
-        }
4515
-        // make sure we only have one of each value in the list
4516
-        $values = array_unique($values);
4517
-        foreach ($values as $value) {
4518
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4519
-        }
4520
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4521
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4522
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4523
-        if (empty($prepped)) {
4524
-            $all_fields = $this->field_settings();
4525
-            $first_field    = reset($all_fields);
4526
-            $main_table = $this->_get_main_table();
4527
-            $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4528
-        }
4529
-        return '(' . implode(',', $prepped) . ')';
4530
-    }
4531
-
4532
-
4533
-
4534
-    /**
4535
-     * @param mixed                      $value
4536
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4537
-     * @throws EE_Error
4538
-     * @return false|null|string
4539
-     */
4540
-    private function _wpdb_prepare_using_field($value, $field_obj)
4541
-    {
4542
-        /** @type WPDB $wpdb */
4543
-        global $wpdb;
4544
-        if ($field_obj instanceof EE_Model_Field_Base) {
4545
-            return $wpdb->prepare(
4546
-                $field_obj->get_wpdb_data_type(),
4547
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4548
-            );
4549
-        } //$field_obj should really just be a data type
4550
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4551
-            throw new EE_Error(
4552
-                sprintf(
4553
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4554
-                    $field_obj,
4555
-                    implode(",", $this->_valid_wpdb_data_types)
4556
-                )
4557
-            );
4558
-        }
4559
-        return $wpdb->prepare($field_obj, $value);
4560
-    }
4561
-
4562
-
4563
-
4564
-    /**
4565
-     * Takes the input parameter and finds the model field that it indicates.
4566
-     *
4567
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4568
-     * @throws EE_Error
4569
-     * @return EE_Model_Field_Base
4570
-     */
4571
-    protected function _deduce_field_from_query_param($query_param_name)
4572
-    {
4573
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4574
-        // which will help us find the database table and column
4575
-        $query_param_parts = explode(".", $query_param_name);
4576
-        if (empty($query_param_parts)) {
4577
-            throw new EE_Error(sprintf(esc_html__(
4578
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4579
-                'event_espresso'
4580
-            ), $query_param_name));
4581
-        }
4582
-        $number_of_parts = count($query_param_parts);
4583
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4584
-        if ($number_of_parts === 1) {
4585
-            $field_name = $last_query_param_part;
4586
-            $model_obj = $this;
4587
-        } else {// $number_of_parts >= 2
4588
-            // the last part is the column name, and there are only 2parts. therefore...
4589
-            $field_name = $last_query_param_part;
4590
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4591
-        }
4592
-        try {
4593
-            return $model_obj->field_settings_for($field_name);
4594
-        } catch (EE_Error $e) {
4595
-            return null;
4596
-        }
4597
-    }
4598
-
4599
-
4600
-
4601
-    /**
4602
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4603
-     * alias and column which corresponds to it
4604
-     *
4605
-     * @param string $field_name
4606
-     * @throws EE_Error
4607
-     * @return string
4608
-     */
4609
-    public function _get_qualified_column_for_field($field_name)
4610
-    {
4611
-        $all_fields = $this->field_settings();
4612
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4613
-        if ($field) {
4614
-            return $field->get_qualified_column();
4615
-        }
4616
-        throw new EE_Error(
4617
-            sprintf(
4618
-                esc_html__(
4619
-                    "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.",
4620
-                    'event_espresso'
4621
-                ),
4622
-                $field_name,
4623
-                get_class($this)
4624
-            )
4625
-        );
4626
-    }
4627
-
4628
-
4629
-
4630
-    /**
4631
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4632
-     * Example usage:
4633
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4634
-     *      array(),
4635
-     *      ARRAY_A,
4636
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4637
-     *  );
4638
-     * is equivalent to
4639
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4640
-     * and
4641
-     *  EEM_Event::instance()->get_all_wpdb_results(
4642
-     *      array(
4643
-     *          array(
4644
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4645
-     *          ),
4646
-     *          ARRAY_A,
4647
-     *          implode(
4648
-     *              ', ',
4649
-     *              array_merge(
4650
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4651
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4652
-     *              )
4653
-     *          )
4654
-     *      )
4655
-     *  );
4656
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4657
-     *
4658
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4659
-     *                                            and the one whose fields you are selecting for example: when querying
4660
-     *                                            tickets model and selecting fields from the tickets model you would
4661
-     *                                            leave this parameter empty, because no models are needed to join
4662
-     *                                            between the queried model and the selected one. Likewise when
4663
-     *                                            querying the datetime model and selecting fields from the tickets
4664
-     *                                            model, it would also be left empty, because there is a direct
4665
-     *                                            relation from datetimes to tickets, so no model is needed to join
4666
-     *                                            them together. However, when querying from the event model and
4667
-     *                                            selecting fields from the ticket model, you should provide the string
4668
-     *                                            'Datetime', indicating that the event model must first join to the
4669
-     *                                            datetime model in order to find its relation to ticket model.
4670
-     *                                            Also, when querying from the venue model and selecting fields from
4671
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4672
-     *                                            indicating you need to join the venue model to the event model,
4673
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4674
-     *                                            This string is used to deduce the prefix that gets added onto the
4675
-     *                                            models' tables qualified columns
4676
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4677
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4678
-     *                                            qualified column names
4679
-     * @return array|string
4680
-     */
4681
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4682
-    {
4683
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4684
-        $qualified_columns = array();
4685
-        foreach ($this->field_settings() as $field_name => $field) {
4686
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4687
-        }
4688
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4689
-    }
4690
-
4691
-
4692
-
4693
-    /**
4694
-     * constructs the select use on special limit joins
4695
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4696
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4697
-     * (as that is typically where the limits would be set).
4698
-     *
4699
-     * @param  string       $table_alias The table the select is being built for
4700
-     * @param  mixed|string $limit       The limit for this select
4701
-     * @return string                The final select join element for the query.
4702
-     */
4703
-    public function _construct_limit_join_select($table_alias, $limit)
4704
-    {
4705
-        $SQL = '';
4706
-        foreach ($this->_tables as $table_obj) {
4707
-            if ($table_obj instanceof EE_Primary_Table) {
4708
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4709
-                    ? $table_obj->get_select_join_limit($limit)
4710
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4711
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4712
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4713
-                    ? $table_obj->get_select_join_limit_join($limit)
4714
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4715
-            }
4716
-        }
4717
-        return $SQL;
4718
-    }
4719
-
4720
-
4721
-
4722
-    /**
4723
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4724
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4725
-     *
4726
-     * @return string SQL
4727
-     * @throws EE_Error
4728
-     */
4729
-    public function _construct_internal_join()
4730
-    {
4731
-        $SQL = $this->_get_main_table()->get_table_sql();
4732
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4733
-        return $SQL;
4734
-    }
4735
-
4736
-
4737
-
4738
-    /**
4739
-     * Constructs the SQL for joining all the tables on this model.
4740
-     * Normally $alias should be the primary table's alias, but in cases where
4741
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4742
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4743
-     * alias, this will construct SQL like:
4744
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4745
-     * With $alias being a secondary table's alias, this will construct SQL like:
4746
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
-     *
4748
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4749
-     * @return string
4750
-     */
4751
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4752
-    {
4753
-        $SQL = '';
4754
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4755
-        foreach ($this->_tables as $table_obj) {
4756
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4757
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4758
-                    // so we're joining to this table, meaning the table is already in
4759
-                    // the FROM statement, BUT the primary table isn't. So we want
4760
-                    // to add the inverse join sql
4761
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4762
-                } else {
4763
-                    // just add a regular JOIN to this table from the primary table
4764
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4765
-                }
4766
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4767
-        }
4768
-        return $SQL;
4769
-    }
4770
-
4771
-
4772
-
4773
-    /**
4774
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4775
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4776
-     * their data type (eg, '%s', '%d', etc)
4777
-     *
4778
-     * @return array
4779
-     */
4780
-    public function _get_data_types()
4781
-    {
4782
-        $data_types = array();
4783
-        foreach ($this->field_settings() as $field_obj) {
4784
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4785
-            /** @var $field_obj EE_Model_Field_Base */
4786
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4787
-        }
4788
-        return $data_types;
4789
-    }
4790
-
4791
-
4792
-
4793
-    /**
4794
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4795
-     *
4796
-     * @param string $model_name
4797
-     * @throws EE_Error
4798
-     * @return EEM_Base
4799
-     */
4800
-    public function get_related_model_obj($model_name)
4801
-    {
4802
-        $model_classname = "EEM_" . $model_name;
4803
-        if (! class_exists($model_classname)) {
4804
-            throw new EE_Error(sprintf(esc_html__(
4805
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4806
-                'event_espresso'
4807
-            ), $model_name, $model_classname));
4808
-        }
4809
-        return call_user_func($model_classname . "::instance");
4810
-    }
4811
-
4812
-
4813
-
4814
-    /**
4815
-     * Returns the array of EE_ModelRelations for this model.
4816
-     *
4817
-     * @return EE_Model_Relation_Base[]
4818
-     */
4819
-    public function relation_settings()
4820
-    {
4821
-        return $this->_model_relations;
4822
-    }
4823
-
4824
-
4825
-
4826
-    /**
4827
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4828
-     * because without THOSE models, this model probably doesn't have much purpose.
4829
-     * (Eg, without an event, datetimes have little purpose.)
4830
-     *
4831
-     * @return EE_Belongs_To_Relation[]
4832
-     */
4833
-    public function belongs_to_relations()
4834
-    {
4835
-        $belongs_to_relations = array();
4836
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4837
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4838
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4839
-            }
4840
-        }
4841
-        return $belongs_to_relations;
4842
-    }
4843
-
4844
-
4845
-
4846
-    /**
4847
-     * Returns the specified EE_Model_Relation, or throws an exception
4848
-     *
4849
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4850
-     * @throws EE_Error
4851
-     * @return EE_Model_Relation_Base
4852
-     */
4853
-    public function related_settings_for($relation_name)
4854
-    {
4855
-        $relatedModels = $this->relation_settings();
4856
-        if (! array_key_exists($relation_name, $relatedModels)) {
4857
-            throw new EE_Error(
4858
-                sprintf(
4859
-                    esc_html__(
4860
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4861
-                        'event_espresso'
4862
-                    ),
4863
-                    $relation_name,
4864
-                    $this->_get_class_name(),
4865
-                    implode(', ', array_keys($relatedModels))
4866
-                )
4867
-            );
4868
-        }
4869
-        return $relatedModels[ $relation_name ];
4870
-    }
4871
-
4872
-
4873
-
4874
-    /**
4875
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4876
-     * fields
4877
-     *
4878
-     * @param string $fieldName
4879
-     * @param boolean $include_db_only_fields
4880
-     * @throws EE_Error
4881
-     * @return EE_Model_Field_Base
4882
-     */
4883
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4884
-    {
4885
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4886
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4887
-            throw new EE_Error(sprintf(
4888
-                esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4889
-                $fieldName,
4890
-                get_class($this)
4891
-            ));
4892
-        }
4893
-        return $fieldSettings[ $fieldName ];
4894
-    }
4895
-
4896
-
4897
-
4898
-    /**
4899
-     * Checks if this field exists on this model
4900
-     *
4901
-     * @param string $fieldName a key in the model's _field_settings array
4902
-     * @return boolean
4903
-     */
4904
-    public function has_field($fieldName)
4905
-    {
4906
-        $fieldSettings = $this->field_settings(true);
4907
-        if (isset($fieldSettings[ $fieldName ])) {
4908
-            return true;
4909
-        }
4910
-        return false;
4911
-    }
4912
-
4913
-
4914
-
4915
-    /**
4916
-     * Returns whether or not this model has a relation to the specified model
4917
-     *
4918
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4919
-     * @return boolean
4920
-     */
4921
-    public function has_relation($relation_name)
4922
-    {
4923
-        $relations = $this->relation_settings();
4924
-        if (isset($relations[ $relation_name ])) {
4925
-            return true;
4926
-        }
4927
-        return false;
4928
-    }
4929
-
4930
-
4931
-
4932
-    /**
4933
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4934
-     * Eg, on EE_Answer that would be ANS_ID field object
4935
-     *
4936
-     * @param $field_obj
4937
-     * @return boolean
4938
-     */
4939
-    public function is_primary_key_field($field_obj)
4940
-    {
4941
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4942
-    }
4943
-
4944
-
4945
-
4946
-    /**
4947
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4948
-     * Eg, on EE_Answer that would be ANS_ID field object
4949
-     *
4950
-     * @return EE_Model_Field_Base
4951
-     * @throws EE_Error
4952
-     */
4953
-    public function get_primary_key_field()
4954
-    {
4955
-        if ($this->_primary_key_field === null) {
4956
-            foreach ($this->field_settings(true) as $field_obj) {
4957
-                if ($this->is_primary_key_field($field_obj)) {
4958
-                    $this->_primary_key_field = $field_obj;
4959
-                    break;
4960
-                }
4961
-            }
4962
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4963
-                throw new EE_Error(sprintf(
4964
-                    esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4965
-                    get_class($this)
4966
-                ));
4967
-            }
4968
-        }
4969
-        return $this->_primary_key_field;
4970
-    }
4971
-
4972
-
4973
-
4974
-    /**
4975
-     * Returns whether or not not there is a primary key on this model.
4976
-     * Internally does some caching.
4977
-     *
4978
-     * @return boolean
4979
-     */
4980
-    public function has_primary_key_field()
4981
-    {
4982
-        if ($this->_has_primary_key_field === null) {
4983
-            try {
4984
-                $this->get_primary_key_field();
4985
-                $this->_has_primary_key_field = true;
4986
-            } catch (EE_Error $e) {
4987
-                $this->_has_primary_key_field = false;
4988
-            }
4989
-        }
4990
-        return $this->_has_primary_key_field;
4991
-    }
4992
-
4993
-
4994
-
4995
-    /**
4996
-     * Finds the first field of type $field_class_name.
4997
-     *
4998
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4999
-     *                                 EE_Foreign_Key_Field, etc
5000
-     * @return EE_Model_Field_Base or null if none is found
5001
-     */
5002
-    public function get_a_field_of_type($field_class_name)
5003
-    {
5004
-        foreach ($this->field_settings() as $field) {
5005
-            if ($field instanceof $field_class_name) {
5006
-                return $field;
5007
-            }
5008
-        }
5009
-        return null;
5010
-    }
5011
-
5012
-
5013
-
5014
-    /**
5015
-     * Gets a foreign key field pointing to model.
5016
-     *
5017
-     * @param string $model_name eg Event, Registration, not EEM_Event
5018
-     * @return EE_Foreign_Key_Field_Base
5019
-     * @throws EE_Error
5020
-     */
5021
-    public function get_foreign_key_to($model_name)
5022
-    {
5023
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5024
-            foreach ($this->field_settings() as $field) {
5025
-                if (
5026
-                    $field instanceof EE_Foreign_Key_Field_Base
5027
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5028
-                ) {
5029
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5030
-                    break;
5031
-                }
5032
-            }
5033
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5034
-                throw new EE_Error(sprintf(esc_html__(
5035
-                    "There is no foreign key field pointing to model %s on model %s",
5036
-                    'event_espresso'
5037
-                ), $model_name, get_class($this)));
5038
-            }
5039
-        }
5040
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5041
-    }
5042
-
5043
-
5044
-
5045
-    /**
5046
-     * Gets the table name (including $wpdb->prefix) for the table alias
5047
-     *
5048
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5049
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5050
-     *                            Either one works
5051
-     * @return string
5052
-     */
5053
-    public function get_table_for_alias($table_alias)
5054
-    {
5055
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5056
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5057
-    }
5058
-
5059
-
5060
-
5061
-    /**
5062
-     * Returns a flat array of all field son this model, instead of organizing them
5063
-     * by table_alias as they are in the constructor.
5064
-     *
5065
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5066
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5067
-     */
5068
-    public function field_settings($include_db_only_fields = false)
5069
-    {
5070
-        if ($include_db_only_fields) {
5071
-            if ($this->_cached_fields === null) {
5072
-                $this->_cached_fields = array();
5073
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5074
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5075
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5076
-                    }
5077
-                }
5078
-            }
5079
-            return $this->_cached_fields;
5080
-        }
5081
-        if ($this->_cached_fields_non_db_only === null) {
5082
-            $this->_cached_fields_non_db_only = array();
5083
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5084
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5085
-                    /** @var $field_obj EE_Model_Field_Base */
5086
-                    if (! $field_obj->is_db_only_field()) {
5087
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5088
-                    }
5089
-                }
5090
-            }
5091
-        }
5092
-        return $this->_cached_fields_non_db_only;
5093
-    }
5094
-
5095
-
5096
-
5097
-    /**
5098
-     *        cycle though array of attendees and create objects out of each item
5099
-     *
5100
-     * @access        private
5101
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5102
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5103
-     *                           numerically indexed)
5104
-     * @throws EE_Error
5105
-     */
5106
-    protected function _create_objects($rows = array())
5107
-    {
5108
-        $array_of_objects = array();
5109
-        if (empty($rows)) {
5110
-            return array();
5111
-        }
5112
-        $count_if_model_has_no_primary_key = 0;
5113
-        $has_primary_key = $this->has_primary_key_field();
5114
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5115
-        foreach ((array) $rows as $row) {
5116
-            if (empty($row)) {
5117
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5118
-                return array();
5119
-            }
5120
-            // check if we've already set this object in the results array,
5121
-            // in which case there's no need to process it further (again)
5122
-            if ($has_primary_key) {
5123
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5124
-                    $row,
5125
-                    $primary_key_field->get_qualified_column(),
5126
-                    $primary_key_field->get_table_column()
5127
-                );
5128
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5129
-                    continue;
5130
-                }
5131
-            }
5132
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5133
-            if (! $classInstance) {
5134
-                throw new EE_Error(
5135
-                    sprintf(
5136
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5137
-                        $this->get_this_model_name(),
5138
-                        http_build_query($row)
5139
-                    )
5140
-                );
5141
-            }
5142
-            // set the timezone on the instantiated objects
5143
-            $classInstance->set_timezone($this->_timezone);
5144
-            // make sure if there is any timezone setting present that we set the timezone for the object
5145
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5146
-            $array_of_objects[ $key ] = $classInstance;
5147
-            // also, for all the relations of type BelongsTo, see if we can cache
5148
-            // those related models
5149
-            // (we could do this for other relations too, but if there are conditions
5150
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5151
-            // so it requires a little more thought than just caching them immediately...)
5152
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5153
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5154
-                    // check if this model's INFO is present. If so, cache it on the model
5155
-                    $other_model = $relation_obj->get_other_model();
5156
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5157
-                    // if we managed to make a model object from the results, cache it on the main model object
5158
-                    if ($other_model_obj_maybe) {
5159
-                        // set timezone on these other model objects if they are present
5160
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5161
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5162
-                    }
5163
-                }
5164
-            }
5165
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5166
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5167
-            // the field in the CustomSelects object
5168
-            if ($this->_custom_selections instanceof CustomSelects) {
5169
-                $classInstance->setCustomSelectsValues(
5170
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5171
-                );
5172
-            }
5173
-        }
5174
-        return $array_of_objects;
5175
-    }
5176
-
5177
-
5178
-    /**
5179
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5180
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5181
-     *
5182
-     * @param array $db_results_row
5183
-     * @return array
5184
-     */
5185
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5186
-    {
5187
-        $results = array();
5188
-        if ($this->_custom_selections instanceof CustomSelects) {
5189
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5190
-                if (isset($db_results_row[ $alias ])) {
5191
-                    $results[ $alias ] = $this->convertValueToDataType(
5192
-                        $db_results_row[ $alias ],
5193
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5194
-                    );
5195
-                }
5196
-            }
5197
-        }
5198
-        return $results;
5199
-    }
5200
-
5201
-
5202
-    /**
5203
-     * This will set the value for the given alias
5204
-     * @param string $value
5205
-     * @param string $datatype (one of %d, %s, %f)
5206
-     * @return int|string|float (int for %d, string for %s, float for %f)
5207
-     */
5208
-    protected function convertValueToDataType($value, $datatype)
5209
-    {
5210
-        switch ($datatype) {
5211
-            case '%f':
5212
-                return (float) $value;
5213
-            case '%d':
5214
-                return (int) $value;
5215
-            default:
5216
-                return (string) $value;
5217
-        }
5218
-    }
5219
-
5220
-
5221
-    /**
5222
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5223
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5224
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5225
-     * object (as set in the model_field!).
5226
-     *
5227
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5228
-     */
5229
-    public function create_default_object()
5230
-    {
5231
-        $this_model_fields_and_values = array();
5232
-        // setup the row using default values;
5233
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5234
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5235
-        }
5236
-        $className = $this->_get_class_name();
5237
-        $classInstance = EE_Registry::instance()
5238
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5239
-        return $classInstance;
5240
-    }
5241
-
5242
-
5243
-
5244
-    /**
5245
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5246
-     *                             or an stdClass where each property is the name of a column,
5247
-     * @return EE_Base_Class
5248
-     * @throws EE_Error
5249
-     */
5250
-    public function instantiate_class_from_array_or_object($cols_n_values)
5251
-    {
5252
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5253
-            $cols_n_values = get_object_vars($cols_n_values);
5254
-        }
5255
-        $primary_key = null;
5256
-        // make sure the array only has keys that are fields/columns on this model
5257
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5258
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5259
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5260
-        }
5261
-        $className = $this->_get_class_name();
5262
-        // check we actually found results that we can use to build our model object
5263
-        // if not, return null
5264
-        if ($this->has_primary_key_field()) {
5265
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5266
-                return null;
5267
-            }
5268
-        } elseif ($this->unique_indexes()) {
5269
-            $first_column = reset($this_model_fields_n_values);
5270
-            if (empty($first_column)) {
5271
-                return null;
5272
-            }
5273
-        }
5274
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5275
-        if ($primary_key) {
5276
-            $classInstance = $this->get_from_entity_map($primary_key);
5277
-            if (! $classInstance) {
5278
-                $classInstance = EE_Registry::instance()
5279
-                                            ->load_class(
5280
-                                                $className,
5281
-                                                array($this_model_fields_n_values, $this->_timezone),
5282
-                                                true,
5283
-                                                false
5284
-                                            );
5285
-                // add this new object to the entity map
5286
-                $classInstance = $this->add_to_entity_map($classInstance);
5287
-            }
5288
-        } else {
5289
-            $classInstance = EE_Registry::instance()
5290
-                                        ->load_class(
5291
-                                            $className,
5292
-                                            array($this_model_fields_n_values, $this->_timezone),
5293
-                                            true,
5294
-                                            false
5295
-                                        );
5296
-        }
5297
-        return $classInstance;
5298
-    }
5299
-
5300
-
5301
-
5302
-    /**
5303
-     * Gets the model object from the  entity map if it exists
5304
-     *
5305
-     * @param int|string $id the ID of the model object
5306
-     * @return EE_Base_Class
5307
-     */
5308
-    public function get_from_entity_map($id)
5309
-    {
5310
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5311
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5312
-    }
5313
-
5314
-
5315
-
5316
-    /**
5317
-     * add_to_entity_map
5318
-     * Adds the object to the model's entity mappings
5319
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5320
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5321
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5322
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5323
-     *        then this method should be called immediately after the update query
5324
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5325
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5326
-     *
5327
-     * @param    EE_Base_Class $object
5328
-     * @throws EE_Error
5329
-     * @return \EE_Base_Class
5330
-     */
5331
-    public function add_to_entity_map(EE_Base_Class $object)
5332
-    {
5333
-        $className = $this->_get_class_name();
5334
-        if (! $object instanceof $className) {
5335
-            throw new EE_Error(sprintf(
5336
-                esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5337
-                is_object($object) ? get_class($object) : $object,
5338
-                $className
5339
-            ));
5340
-        }
5341
-        /** @var $object EE_Base_Class */
5342
-        if (! $object->ID()) {
5343
-            throw new EE_Error(sprintf(esc_html__(
5344
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5345
-                "event_espresso"
5346
-            ), get_class($this)));
5347
-        }
5348
-        // double check it's not already there
5349
-        $classInstance = $this->get_from_entity_map($object->ID());
5350
-        if ($classInstance) {
5351
-            return $classInstance;
5352
-        }
5353
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5354
-        return $object;
5355
-    }
5356
-
5357
-
5358
-
5359
-    /**
5360
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5361
-     * if no identifier is provided, then the entire entity map is emptied
5362
-     *
5363
-     * @param int|string $id the ID of the model object
5364
-     * @return boolean
5365
-     */
5366
-    public function clear_entity_map($id = null)
5367
-    {
5368
-        if (empty($id)) {
5369
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5370
-            return true;
5371
-        }
5372
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5373
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5374
-            return true;
5375
-        }
5376
-        return false;
5377
-    }
5378
-
5379
-
5380
-
5381
-    /**
5382
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5383
-     * Given an array where keys are column (or column alias) names and values,
5384
-     * returns an array of their corresponding field names and database values
5385
-     *
5386
-     * @param array $cols_n_values
5387
-     * @return array
5388
-     */
5389
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5390
-    {
5391
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5392
-    }
5393
-
5394
-
5395
-
5396
-    /**
5397
-     * _deduce_fields_n_values_from_cols_n_values
5398
-     * Given an array where keys are column (or column alias) names and values,
5399
-     * returns an array of their corresponding field names and database values
5400
-     *
5401
-     * @param string $cols_n_values
5402
-     * @return array
5403
-     */
5404
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5405
-    {
5406
-        $this_model_fields_n_values = array();
5407
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5408
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5409
-                $cols_n_values,
5410
-                $table_obj->get_fully_qualified_pk_column(),
5411
-                $table_obj->get_pk_column()
5412
-            );
5413
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5414
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5415
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5416
-                    if (! $field_obj->is_db_only_field()) {
5417
-                        // prepare field as if its coming from db
5418
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5419
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5420
-                    }
5421
-                }
5422
-            } else {
5423
-                // the table's rows existed. Use their values
5424
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5425
-                    if (! $field_obj->is_db_only_field()) {
5426
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5427
-                            $cols_n_values,
5428
-                            $field_obj->get_qualified_column(),
5429
-                            $field_obj->get_table_column()
5430
-                        );
5431
-                    }
5432
-                }
5433
-            }
5434
-        }
5435
-        return $this_model_fields_n_values;
5436
-    }
5437
-
5438
-
5439
-    /**
5440
-     * @param $cols_n_values
5441
-     * @param $qualified_column
5442
-     * @param $regular_column
5443
-     * @return null
5444
-     * @throws EE_Error
5445
-     * @throws ReflectionException
5446
-     */
5447
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5448
-    {
5449
-        $value = null;
5450
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5451
-        // does the field on the model relate to this column retrieved from the db?
5452
-        // or is it a db-only field? (not relating to the model)
5453
-        if (isset($cols_n_values[ $qualified_column ])) {
5454
-            $value = $cols_n_values[ $qualified_column ];
5455
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5456
-            $value = $cols_n_values[ $regular_column ];
5457
-        } elseif (! empty($this->foreign_key_aliases)) {
5458
-            // no PK?  ok check if there is a foreign key alias set for this table
5459
-            // then check if that alias exists in the incoming data
5460
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5461
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5462
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5463
-                    $value = $cols_n_values[ $FK_alias ];
5464
-                    list($pk_class) = explode('.', $PK_column);
5465
-                    $pk_model_name = "EEM_{$pk_class}";
5466
-                    /** @var EEM_Base $pk_model */
5467
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5468
-                    if ($pk_model instanceof EEM_Base) {
5469
-                        // make sure object is pulled from db and added to entity map
5470
-                        $pk_model->get_one_by_ID($value);
5471
-                    }
5472
-                    break;
5473
-                }
5474
-            }
5475
-        }
5476
-        return $value;
5477
-    }
5478
-
5479
-
5480
-
5481
-    /**
5482
-     * refresh_entity_map_from_db
5483
-     * Makes sure the model object in the entity map at $id assumes the values
5484
-     * of the database (opposite of EE_base_Class::save())
5485
-     *
5486
-     * @param int|string $id
5487
-     * @return EE_Base_Class
5488
-     * @throws EE_Error
5489
-     */
5490
-    public function refresh_entity_map_from_db($id)
5491
-    {
5492
-        $obj_in_map = $this->get_from_entity_map($id);
5493
-        if ($obj_in_map) {
5494
-            $wpdb_results = $this->_get_all_wpdb_results(
5495
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5496
-            );
5497
-            if ($wpdb_results && is_array($wpdb_results)) {
5498
-                $one_row = reset($wpdb_results);
5499
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5500
-                    $obj_in_map->set_from_db($field_name, $db_value);
5501
-                }
5502
-                // clear the cache of related model objects
5503
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5504
-                    $obj_in_map->clear_cache($relation_name, null, true);
5505
-                }
5506
-            }
5507
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5508
-            return $obj_in_map;
5509
-        }
5510
-        return $this->get_one_by_ID($id);
5511
-    }
5512
-
5513
-
5514
-
5515
-    /**
5516
-     * refresh_entity_map_with
5517
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5518
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5519
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5520
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5521
-     *
5522
-     * @param int|string    $id
5523
-     * @param EE_Base_Class $replacing_model_obj
5524
-     * @return \EE_Base_Class
5525
-     * @throws EE_Error
5526
-     */
5527
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5528
-    {
5529
-        $obj_in_map = $this->get_from_entity_map($id);
5530
-        if ($obj_in_map) {
5531
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5532
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5533
-                    $obj_in_map->set($field_name, $value);
5534
-                }
5535
-                // make the model object in the entity map's cache match the $replacing_model_obj
5536
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5537
-                    $obj_in_map->clear_cache($relation_name, null, true);
5538
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5539
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5540
-                    }
5541
-                }
5542
-            }
5543
-            return $obj_in_map;
5544
-        }
5545
-        $this->add_to_entity_map($replacing_model_obj);
5546
-        return $replacing_model_obj;
5547
-    }
5548
-
5549
-
5550
-
5551
-    /**
5552
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5553
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5554
-     * require_once($this->_getClassName().".class.php");
5555
-     *
5556
-     * @return string
5557
-     */
5558
-    private function _get_class_name()
5559
-    {
5560
-        return "EE_" . $this->get_this_model_name();
5561
-    }
5562
-
5563
-
5564
-
5565
-    /**
5566
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5567
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5568
-     * it would be 'Events'.
5569
-     *
5570
-     * @param int $quantity
5571
-     * @return string
5572
-     */
5573
-    public function item_name($quantity = 1)
5574
-    {
5575
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5576
-    }
5577
-
5578
-
5579
-
5580
-    /**
5581
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5582
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5583
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5584
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5585
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5586
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5587
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5588
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5589
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5590
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5591
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5592
-     *        return $previousReturnValue.$returnString;
5593
-     * }
5594
-     * require('EEM_Answer.model.php');
5595
-     * $answer=EEM_Answer::instance();
5596
-     * echo $answer->my_callback('monkeys',100);
5597
-     * //will output "you called my_callback! and passed args:monkeys,100"
5598
-     *
5599
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5600
-     * @param array  $args       array of original arguments passed to the function
5601
-     * @throws EE_Error
5602
-     * @return mixed whatever the plugin which calls add_filter decides
5603
-     */
5604
-    public function __call($methodName, $args)
5605
-    {
5606
-        $className = get_class($this);
5607
-        $tagName = "FHEE__{$className}__{$methodName}";
5608
-        if (! has_filter($tagName)) {
5609
-            throw new EE_Error(
5610
-                sprintf(
5611
-                    esc_html__(
5612
-                        '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 );',
5613
-                        'event_espresso'
5614
-                    ),
5615
-                    $methodName,
5616
-                    $className,
5617
-                    $tagName,
5618
-                    '<br />'
5619
-                )
5620
-            );
5621
-        }
5622
-        return apply_filters($tagName, null, $this, $args);
5623
-    }
5624
-
5625
-
5626
-
5627
-    /**
5628
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5629
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5630
-     *
5631
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5632
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5633
-     *                                                       the object's class name
5634
-     *                                                       or object's ID
5635
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5636
-     *                                                       exists in the database. If it does not, we add it
5637
-     * @throws EE_Error
5638
-     * @return EE_Base_Class
5639
-     */
5640
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5641
-    {
5642
-        $className = $this->_get_class_name();
5643
-        if ($base_class_obj_or_id instanceof $className) {
5644
-            $model_object = $base_class_obj_or_id;
5645
-        } else {
5646
-            $primary_key_field = $this->get_primary_key_field();
5647
-            if (
5648
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5649
-                && (
5650
-                    is_int($base_class_obj_or_id)
5651
-                    || is_string($base_class_obj_or_id)
5652
-                )
5653
-            ) {
5654
-                // assume it's an ID.
5655
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5656
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5657
-            } elseif (
5658
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5659
-                && is_string($base_class_obj_or_id)
5660
-            ) {
5661
-                // assume its a string representation of the object
5662
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5663
-            } else {
5664
-                throw new EE_Error(
5665
-                    sprintf(
5666
-                        esc_html__(
5667
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5668
-                            'event_espresso'
5669
-                        ),
5670
-                        $base_class_obj_or_id,
5671
-                        $this->_get_class_name(),
5672
-                        print_r($base_class_obj_or_id, true)
5673
-                    )
5674
-                );
5675
-            }
5676
-        }
5677
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5678
-            $model_object->save();
5679
-        }
5680
-        return $model_object;
5681
-    }
5682
-
5683
-
5684
-
5685
-    /**
5686
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5687
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5688
-     * returns it ID.
5689
-     *
5690
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5691
-     * @return int|string depending on the type of this model object's ID
5692
-     * @throws EE_Error
5693
-     */
5694
-    public function ensure_is_ID($base_class_obj_or_id)
5695
-    {
5696
-        $className = $this->_get_class_name();
5697
-        if ($base_class_obj_or_id instanceof $className) {
5698
-            /** @var $base_class_obj_or_id EE_Base_Class */
5699
-            $id = $base_class_obj_or_id->ID();
5700
-        } elseif (is_int($base_class_obj_or_id)) {
5701
-            // assume it's an ID
5702
-            $id = $base_class_obj_or_id;
5703
-        } elseif (is_string($base_class_obj_or_id)) {
5704
-            // assume its a string representation of the object
5705
-            $id = $base_class_obj_or_id;
5706
-        } else {
5707
-            throw new EE_Error(sprintf(
5708
-                esc_html__(
5709
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5710
-                    'event_espresso'
5711
-                ),
5712
-                $base_class_obj_or_id,
5713
-                $this->_get_class_name(),
5714
-                print_r($base_class_obj_or_id, true)
5715
-            ));
5716
-        }
5717
-        return $id;
5718
-    }
5719
-
5720
-
5721
-
5722
-    /**
5723
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5724
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5725
-     * been sanitized and converted into the appropriate domain.
5726
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5727
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5728
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5729
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5730
-     * $EVT = EEM_Event::instance(); $old_setting =
5731
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5732
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5733
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5734
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5735
-     *
5736
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5737
-     * @return void
5738
-     */
5739
-    public function assume_values_already_prepared_by_model_object(
5740
-        $values_already_prepared = self::not_prepared_by_model_object
5741
-    ) {
5742
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5743
-    }
5744
-
5745
-
5746
-
5747
-    /**
5748
-     * Read comments for assume_values_already_prepared_by_model_object()
5749
-     *
5750
-     * @return int
5751
-     */
5752
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5753
-    {
5754
-        return $this->_values_already_prepared_by_model_object;
5755
-    }
5756
-
5757
-
5758
-
5759
-    /**
5760
-     * Gets all the indexes on this model
5761
-     *
5762
-     * @return EE_Index[]
5763
-     */
5764
-    public function indexes()
5765
-    {
5766
-        return $this->_indexes;
5767
-    }
5768
-
5769
-
5770
-
5771
-    /**
5772
-     * Gets all the Unique Indexes on this model
5773
-     *
5774
-     * @return EE_Unique_Index[]
5775
-     */
5776
-    public function unique_indexes()
5777
-    {
5778
-        $unique_indexes = array();
5779
-        foreach ($this->_indexes as $name => $index) {
5780
-            if ($index instanceof EE_Unique_Index) {
5781
-                $unique_indexes [ $name ] = $index;
5782
-            }
5783
-        }
5784
-        return $unique_indexes;
5785
-    }
5786
-
5787
-
5788
-
5789
-    /**
5790
-     * Gets all the fields which, when combined, make the primary key.
5791
-     * This is usually just an array with 1 element (the primary key), but in cases
5792
-     * where there is no primary key, it's a combination of fields as defined
5793
-     * on a primary index
5794
-     *
5795
-     * @return EE_Model_Field_Base[] indexed by the field's name
5796
-     * @throws EE_Error
5797
-     */
5798
-    public function get_combined_primary_key_fields()
5799
-    {
5800
-        foreach ($this->indexes() as $index) {
5801
-            if ($index instanceof EE_Primary_Key_Index) {
5802
-                return $index->fields();
5803
-            }
5804
-        }
5805
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5806
-    }
5807
-
5808
-
5809
-
5810
-    /**
5811
-     * Used to build a primary key string (when the model has no primary key),
5812
-     * which can be used a unique string to identify this model object.
5813
-     *
5814
-     * @param array $fields_n_values keys are field names, values are their values.
5815
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5816
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5817
-     *                               before passing it to this function (that will convert it from columns-n-values
5818
-     *                               to field-names-n-values).
5819
-     * @return string
5820
-     * @throws EE_Error
5821
-     */
5822
-    public function get_index_primary_key_string($fields_n_values)
5823
-    {
5824
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5825
-            $fields_n_values,
5826
-            $this->get_combined_primary_key_fields()
5827
-        );
5828
-        return http_build_query($cols_n_values_for_primary_key_index);
5829
-    }
5830
-
5831
-
5832
-
5833
-    /**
5834
-     * Gets the field values from the primary key string
5835
-     *
5836
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5837
-     * @param string $index_primary_key_string
5838
-     * @return null|array
5839
-     * @throws EE_Error
5840
-     */
5841
-    public function parse_index_primary_key_string($index_primary_key_string)
5842
-    {
5843
-        $key_fields = $this->get_combined_primary_key_fields();
5844
-        // check all of them are in the $id
5845
-        $key_vals_in_combined_pk = array();
5846
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5847
-        foreach ($key_fields as $key_field_name => $field_obj) {
5848
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5849
-                return null;
5850
-            }
5851
-        }
5852
-        return $key_vals_in_combined_pk;
5853
-    }
5854
-
5855
-
5856
-
5857
-    /**
5858
-     * verifies that an array of key-value pairs for model fields has a key
5859
-     * for each field comprising the primary key index
5860
-     *
5861
-     * @param array $key_vals
5862
-     * @return boolean
5863
-     * @throws EE_Error
5864
-     */
5865
-    public function has_all_combined_primary_key_fields($key_vals)
5866
-    {
5867
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5868
-        foreach ($keys_it_should_have as $key) {
5869
-            if (! isset($key_vals[ $key ])) {
5870
-                return false;
5871
-            }
5872
-        }
5873
-        return true;
5874
-    }
5875
-
5876
-
5877
-
5878
-    /**
5879
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5880
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5881
-     *
5882
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5883
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5884
-     * @throws EE_Error
5885
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5886
-     *                                                              indexed)
5887
-     */
5888
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5889
-    {
5890
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5891
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5892
-        } elseif (is_array($model_object_or_attributes_array)) {
5893
-            $attributes_array = $model_object_or_attributes_array;
5894
-        } else {
5895
-            throw new EE_Error(sprintf(esc_html__(
5896
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5897
-                "event_espresso"
5898
-            ), $model_object_or_attributes_array));
5899
-        }
5900
-        // even copies obviously won't have the same ID, so remove the primary key
5901
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5902
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5903
-            unset($attributes_array[ $this->primary_key_name() ]);
5904
-        }
5905
-        if (isset($query_params[0])) {
5906
-            $query_params[0] = array_merge($attributes_array, $query_params);
5907
-        } else {
5908
-            $query_params[0] = $attributes_array;
5909
-        }
5910
-        return $this->get_all($query_params);
5911
-    }
5912
-
5913
-
5914
-
5915
-    /**
5916
-     * Gets the first copy we find. See get_all_copies for more details
5917
-     *
5918
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5919
-     * @param array $query_params
5920
-     * @return EE_Base_Class
5921
-     * @throws EE_Error
5922
-     */
5923
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5924
-    {
5925
-        if (! is_array($query_params)) {
5926
-            EE_Error::doing_it_wrong(
5927
-                'EEM_Base::get_one_copy',
5928
-                sprintf(
5929
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5930
-                    gettype($query_params)
5931
-                ),
5932
-                '4.6.0'
5933
-            );
5934
-            $query_params = array();
5935
-        }
5936
-        $query_params['limit'] = 1;
5937
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5938
-        if (is_array($copies)) {
5939
-            return array_shift($copies);
5940
-        }
5941
-        return null;
5942
-    }
5943
-
5944
-
5945
-
5946
-    /**
5947
-     * Updates the item with the specified id. Ignores default query parameters because
5948
-     * we have specified the ID, and its assumed we KNOW what we're doing
5949
-     *
5950
-     * @param array      $fields_n_values keys are field names, values are their new values
5951
-     * @param int|string $id              the value of the primary key to update
5952
-     * @return int number of rows updated
5953
-     * @throws EE_Error
5954
-     */
5955
-    public function update_by_ID($fields_n_values, $id)
5956
-    {
5957
-        $query_params = array(
5958
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5959
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5960
-        );
5961
-        return $this->update($fields_n_values, $query_params);
5962
-    }
5963
-
5964
-
5965
-
5966
-    /**
5967
-     * Changes an operator which was supplied to the models into one usable in SQL
5968
-     *
5969
-     * @param string $operator_supplied
5970
-     * @return string an operator which can be used in SQL
5971
-     * @throws EE_Error
5972
-     */
5973
-    private function _prepare_operator_for_sql($operator_supplied)
5974
-    {
5975
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5976
-            : null;
5977
-        if ($sql_operator) {
5978
-            return $sql_operator;
5979
-        }
5980
-        throw new EE_Error(
5981
-            sprintf(
5982
-                esc_html__(
5983
-                    "The operator '%s' is not in the list of valid operators: %s",
5984
-                    "event_espresso"
5985
-                ),
5986
-                $operator_supplied,
5987
-                implode(",", array_keys($this->_valid_operators))
5988
-            )
5989
-        );
5990
-    }
5991
-
5992
-
5993
-
5994
-    /**
5995
-     * Gets the valid operators
5996
-     * @return array keys are accepted strings, values are the SQL they are converted to
5997
-     */
5998
-    public function valid_operators()
5999
-    {
6000
-        return $this->_valid_operators;
6001
-    }
6002
-
6003
-
6004
-
6005
-    /**
6006
-     * Gets the between-style operators (take 2 arguments).
6007
-     * @return array keys are accepted strings, values are the SQL they are converted to
6008
-     */
6009
-    public function valid_between_style_operators()
6010
-    {
6011
-        return array_intersect(
6012
-            $this->valid_operators(),
6013
-            $this->_between_style_operators
6014
-        );
6015
-    }
6016
-
6017
-    /**
6018
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6019
-     * @return array keys are accepted strings, values are the SQL they are converted to
6020
-     */
6021
-    public function valid_like_style_operators()
6022
-    {
6023
-        return array_intersect(
6024
-            $this->valid_operators(),
6025
-            $this->_like_style_operators
6026
-        );
6027
-    }
6028
-
6029
-    /**
6030
-     * Gets the "in"-style operators
6031
-     * @return array keys are accepted strings, values are the SQL they are converted to
6032
-     */
6033
-    public function valid_in_style_operators()
6034
-    {
6035
-        return array_intersect(
6036
-            $this->valid_operators(),
6037
-            $this->_in_style_operators
6038
-        );
6039
-    }
6040
-
6041
-    /**
6042
-     * Gets the "null"-style operators (accept no arguments)
6043
-     * @return array keys are accepted strings, values are the SQL they are converted to
6044
-     */
6045
-    public function valid_null_style_operators()
6046
-    {
6047
-        return array_intersect(
6048
-            $this->valid_operators(),
6049
-            $this->_null_style_operators
6050
-        );
6051
-    }
6052
-
6053
-    /**
6054
-     * Gets an array where keys are the primary keys and values are their 'names'
6055
-     * (as determined by the model object's name() function, which is often overridden)
6056
-     *
6057
-     * @param array $query_params like get_all's
6058
-     * @return string[]
6059
-     * @throws EE_Error
6060
-     */
6061
-    public function get_all_names($query_params = array())
6062
-    {
6063
-        $objs = $this->get_all($query_params);
6064
-        $names = array();
6065
-        foreach ($objs as $obj) {
6066
-            $names[ $obj->ID() ] = $obj->name();
6067
-        }
6068
-        return $names;
6069
-    }
6070
-
6071
-
6072
-
6073
-    /**
6074
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6075
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6076
-     * this is duplicated effort and reduces efficiency) you would be better to use
6077
-     * array_keys() on $model_objects.
6078
-     *
6079
-     * @param \EE_Base_Class[] $model_objects
6080
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6081
-     *                                               in the returned array
6082
-     * @return array
6083
-     * @throws EE_Error
6084
-     */
6085
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6086
-    {
6087
-        if (! $this->has_primary_key_field()) {
6088
-            if (WP_DEBUG) {
6089
-                EE_Error::add_error(
6090
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6091
-                    __FILE__,
6092
-                    __FUNCTION__,
6093
-                    __LINE__
6094
-                );
6095
-            }
6096
-        }
6097
-        $IDs = array();
6098
-        foreach ($model_objects as $model_object) {
6099
-            $id = $model_object->ID();
6100
-            if (! $id) {
6101
-                if ($filter_out_empty_ids) {
6102
-                    continue;
6103
-                }
6104
-                if (WP_DEBUG) {
6105
-                    EE_Error::add_error(
6106
-                        esc_html__(
6107
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6108
-                            'event_espresso'
6109
-                        ),
6110
-                        __FILE__,
6111
-                        __FUNCTION__,
6112
-                        __LINE__
6113
-                    );
6114
-                }
6115
-            }
6116
-            $IDs[] = $id;
6117
-        }
6118
-        return $IDs;
6119
-    }
6120
-
6121
-
6122
-
6123
-    /**
6124
-     * Returns the string used in capabilities relating to this model. If there
6125
-     * are no capabilities that relate to this model returns false
6126
-     *
6127
-     * @return string|false
6128
-     */
6129
-    public function cap_slug()
6130
-    {
6131
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6132
-    }
6133
-
6134
-
6135
-
6136
-    /**
6137
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6138
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6139
-     * only returns the cap restrictions array in that context (ie, the array
6140
-     * at that key)
6141
-     *
6142
-     * @param string $context
6143
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6144
-     * @throws EE_Error
6145
-     */
6146
-    public function cap_restrictions($context = EEM_Base::caps_read)
6147
-    {
6148
-        EEM_Base::verify_is_valid_cap_context($context);
6149
-        // check if we ought to run the restriction generator first
6150
-        if (
6151
-            isset($this->_cap_restriction_generators[ $context ])
6152
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6153
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6154
-        ) {
6155
-            $this->_cap_restrictions[ $context ] = array_merge(
6156
-                $this->_cap_restrictions[ $context ],
6157
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6158
-            );
6159
-        }
6160
-        // and make sure we've finalized the construction of each restriction
6161
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6162
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6163
-                $where_conditions_obj->_finalize_construct($this);
6164
-            }
6165
-        }
6166
-        return $this->_cap_restrictions[ $context ];
6167
-    }
6168
-
6169
-
6170
-
6171
-    /**
6172
-     * Indicating whether or not this model thinks its a wp core model
6173
-     *
6174
-     * @return boolean
6175
-     */
6176
-    public function is_wp_core_model()
6177
-    {
6178
-        return $this->_wp_core_model;
6179
-    }
6180
-
6181
-
6182
-
6183
-    /**
6184
-     * Gets all the caps that are missing which impose a restriction on
6185
-     * queries made in this context
6186
-     *
6187
-     * @param string $context one of EEM_Base::caps_ constants
6188
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6189
-     * @throws EE_Error
6190
-     */
6191
-    public function caps_missing($context = EEM_Base::caps_read)
6192
-    {
6193
-        $missing_caps = array();
6194
-        $cap_restrictions = $this->cap_restrictions($context);
6195
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6196
-            if (
6197
-                ! EE_Capabilities::instance()
6198
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6199
-            ) {
6200
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6201
-            }
6202
-        }
6203
-        return $missing_caps;
6204
-    }
6205
-
6206
-
6207
-
6208
-    /**
6209
-     * Gets the mapping from capability contexts to action strings used in capability names
6210
-     *
6211
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6212
-     * one of 'read', 'edit', or 'delete'
6213
-     */
6214
-    public function cap_contexts_to_cap_action_map()
6215
-    {
6216
-        return apply_filters(
6217
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6218
-            $this->_cap_contexts_to_cap_action_map,
6219
-            $this
6220
-        );
6221
-    }
6222
-
6223
-
6224
-
6225
-    /**
6226
-     * Gets the action string for the specified capability context
6227
-     *
6228
-     * @param string $context
6229
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6230
-     * @throws EE_Error
6231
-     */
6232
-    public function cap_action_for_context($context)
6233
-    {
6234
-        $mapping = $this->cap_contexts_to_cap_action_map();
6235
-        if (isset($mapping[ $context ])) {
6236
-            return $mapping[ $context ];
6237
-        }
6238
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6239
-            return $action;
6240
-        }
6241
-        throw new EE_Error(
6242
-            sprintf(
6243
-                esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6244
-                $context,
6245
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6246
-            )
6247
-        );
6248
-    }
6249
-
6250
-
6251
-
6252
-    /**
6253
-     * Returns all the capability contexts which are valid when querying models
6254
-     *
6255
-     * @return array
6256
-     */
6257
-    public static function valid_cap_contexts()
6258
-    {
6259
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6260
-            self::caps_read,
6261
-            self::caps_read_admin,
6262
-            self::caps_edit,
6263
-            self::caps_delete,
6264
-        ));
6265
-    }
6266
-
6267
-
6268
-
6269
-    /**
6270
-     * Returns all valid options for 'default_where_conditions'
6271
-     *
6272
-     * @return array
6273
-     */
6274
-    public static function valid_default_where_conditions()
6275
-    {
6276
-        return array(
6277
-            EEM_Base::default_where_conditions_all,
6278
-            EEM_Base::default_where_conditions_this_only,
6279
-            EEM_Base::default_where_conditions_others_only,
6280
-            EEM_Base::default_where_conditions_minimum_all,
6281
-            EEM_Base::default_where_conditions_minimum_others,
6282
-            EEM_Base::default_where_conditions_none
6283
-        );
6284
-    }
6285
-
6286
-    // public static function default_where_conditions_full
6287
-    /**
6288
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6289
-     *
6290
-     * @param string $context
6291
-     * @return bool
6292
-     * @throws EE_Error
6293
-     */
6294
-    public static function verify_is_valid_cap_context($context)
6295
-    {
6296
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6297
-        if (in_array($context, $valid_cap_contexts)) {
6298
-            return true;
6299
-        }
6300
-        throw new EE_Error(
6301
-            sprintf(
6302
-                esc_html__(
6303
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6304
-                    'event_espresso'
6305
-                ),
6306
-                $context,
6307
-                'EEM_Base',
6308
-                implode(',', $valid_cap_contexts)
6309
-            )
6310
-        );
6311
-    }
6312
-
6313
-
6314
-
6315
-    /**
6316
-     * Clears all the models field caches. This is only useful when a sub-class
6317
-     * might have added a field or something and these caches might be invalidated
6318
-     */
6319
-    protected function _invalidate_field_caches()
6320
-    {
6321
-        $this->_cache_foreign_key_to_fields = array();
6322
-        $this->_cached_fields = null;
6323
-        $this->_cached_fields_non_db_only = null;
6324
-    }
6325
-
6326
-
6327
-
6328
-    /**
6329
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6330
-     * (eg "and", "or", "not").
6331
-     *
6332
-     * @return array
6333
-     */
6334
-    public function logic_query_param_keys()
6335
-    {
6336
-        return $this->_logic_query_param_keys;
6337
-    }
6338
-
6339
-
6340
-
6341
-    /**
6342
-     * Determines whether or not the where query param array key is for a logic query param.
6343
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6344
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6345
-     *
6346
-     * @param $query_param_key
6347
-     * @return bool
6348
-     */
6349
-    public function is_logic_query_param_key($query_param_key)
6350
-    {
6351
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6352
-            if (
6353
-                $query_param_key === $logic_query_param_key
6354
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6355
-            ) {
6356
-                return true;
6357
-            }
6358
-        }
6359
-        return false;
6360
-    }
6361
-
6362
-    /**
6363
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6364
-     * @since 4.9.74.p
6365
-     * @return boolean
6366
-     */
6367
-    public function hasPassword()
6368
-    {
6369
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6370
-        if ($this->has_password_field === null) {
6371
-            $password_field = $this->getPasswordField();
6372
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6373
-        }
6374
-        return $this->has_password_field;
6375
-    }
6376
-
6377
-    /**
6378
-     * Returns the password field on this model, if there is one
6379
-     * @since 4.9.74.p
6380
-     * @return EE_Password_Field|null
6381
-     */
6382
-    public function getPasswordField()
6383
-    {
6384
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6385
-        // there's no need to search for it. If we don't know yet, then find out
6386
-        if ($this->has_password_field === null && $this->password_field === null) {
6387
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6388
-        }
6389
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6390
-        return $this->password_field;
6391
-    }
6392
-
6393
-
6394
-    /**
6395
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6396
-     * @since 4.9.74.p
6397
-     * @return EE_Model_Field_Base[]
6398
-     * @throws EE_Error
6399
-     */
6400
-    public function getPasswordProtectedFields()
6401
-    {
6402
-        $password_field = $this->getPasswordField();
6403
-        $fields = array();
6404
-        if ($password_field instanceof EE_Password_Field) {
6405
-            $field_names = $password_field->protectedFields();
6406
-            foreach ($field_names as $field_name) {
6407
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6408
-            }
6409
-        }
6410
-        return $fields;
6411
-    }
6412
-
6413
-
6414
-    /**
6415
-     * Checks if the current user can perform the requested action on this model
6416
-     * @since 4.9.74.p
6417
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6418
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6419
-     * @return bool
6420
-     * @throws EE_Error
6421
-     * @throws InvalidArgumentException
6422
-     * @throws InvalidDataTypeException
6423
-     * @throws InvalidInterfaceException
6424
-     * @throws ReflectionException
6425
-     * @throws UnexpectedEntityException
6426
-     */
6427
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6428
-    {
6429
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6430
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6431
-        }
6432
-        if (!is_array($model_obj_or_fields_n_values)) {
6433
-            throw new UnexpectedEntityException(
6434
-                $model_obj_or_fields_n_values,
6435
-                'EE_Base_Class',
6436
-                sprintf(
6437
-                    esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6438
-                    __FUNCTION__
6439
-                )
6440
-            );
6441
-        }
6442
-        return $this->exists(
6443
-            $this->alter_query_params_to_restrict_by_ID(
6444
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6445
-                array(
6446
-                    'default_where_conditions' => 'none',
6447
-                    'caps'                     => $cap_to_check,
6448
-                )
6449
-            )
6450
-        );
6451
-    }
6452
-
6453
-    /**
6454
-     * Returns the query param where conditions key to the password affecting this model.
6455
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6456
-     * @since 4.9.74.p
6457
-     * @return null|string
6458
-     * @throws EE_Error
6459
-     * @throws InvalidArgumentException
6460
-     * @throws InvalidDataTypeException
6461
-     * @throws InvalidInterfaceException
6462
-     * @throws ModelConfigurationException
6463
-     * @throws ReflectionException
6464
-     */
6465
-    public function modelChainAndPassword()
6466
-    {
6467
-        if ($this->model_chain_to_password === null) {
6468
-            throw new ModelConfigurationException(
6469
-                $this,
6470
-                esc_html_x(
6471
-                // @codingStandardsIgnoreStart
6472
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6473
-                    // @codingStandardsIgnoreEnd
6474
-                    '1: model name',
6475
-                    'event_espresso'
6476
-                )
6477
-            );
6478
-        }
6479
-        if ($this->model_chain_to_password === '') {
6480
-            $model_with_password = $this;
6481
-        } else {
6482
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6483
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6484
-            } else {
6485
-                $last_model_in_chain = $this->model_chain_to_password;
6486
-            }
6487
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6488
-        }
6489
-
6490
-        $password_field = $model_with_password->getPasswordField();
6491
-        if ($password_field instanceof EE_Password_Field) {
6492
-            $password_field_name = $password_field->get_name();
6493
-        } else {
6494
-            throw new ModelConfigurationException(
6495
-                $this,
6496
-                sprintf(
6497
-                    esc_html_x(
6498
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6499
-                        '1: model name, 2: special string',
6500
-                        'event_espresso'
6501
-                    ),
6502
-                    $model_with_password->get_this_model_name(),
6503
-                    $this->model_chain_to_password
6504
-                )
6505
-            );
6506
-        }
6507
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6508
-    }
6509
-
6510
-    /**
6511
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6512
-     * or if this model itself has a password affecting access to some of its other fields.
6513
-     * @since 4.9.74.p
6514
-     * @return boolean
6515
-     */
6516
-    public function restrictedByRelatedModelPassword()
6517
-    {
6518
-        return $this->model_chain_to_password !== null;
6519
-    }
3815
+		}
3816
+		return $null_friendly_where_conditions;
3817
+	}
3818
+
3819
+
3820
+
3821
+	/**
3822
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3823
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3824
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3825
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3826
+	 *
3827
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3828
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3829
+	 */
3830
+	private function _get_default_where_conditions($model_relation_path = null)
3831
+	{
3832
+		if ($this->_ignore_where_strategy) {
3833
+			return array();
3834
+		}
3835
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3836
+	}
3837
+
3838
+
3839
+
3840
+	/**
3841
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3842
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3843
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3844
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3845
+	 * Similar to _get_default_where_conditions
3846
+	 *
3847
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3848
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3849
+	 */
3850
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3851
+	{
3852
+		if ($this->_ignore_where_strategy) {
3853
+			return array();
3854
+		}
3855
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3856
+	}
3857
+
3858
+
3859
+
3860
+	/**
3861
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3862
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3863
+	 *
3864
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3865
+	 * @return string
3866
+	 * @throws EE_Error
3867
+	 */
3868
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3869
+	{
3870
+		$selects = $this->_get_columns_to_select_for_this_model();
3871
+		foreach (
3872
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3873
+		) {
3874
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3875
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3876
+			foreach ($other_model_selects as $key => $value) {
3877
+				$selects[] = $value;
3878
+			}
3879
+		}
3880
+		return implode(", ", $selects);
3881
+	}
3882
+
3883
+
3884
+
3885
+	/**
3886
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3887
+	 * So that's going to be the columns for all the fields on the model
3888
+	 *
3889
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3890
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3891
+	 */
3892
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3893
+	{
3894
+		$fields = $this->field_settings();
3895
+		$selects = array();
3896
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3897
+			$model_relation_chain,
3898
+			$this->get_this_model_name()
3899
+		);
3900
+		foreach ($fields as $field_obj) {
3901
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3902
+						 . $field_obj->get_table_alias()
3903
+						 . "."
3904
+						 . $field_obj->get_table_column()
3905
+						 . " AS '"
3906
+						 . $table_alias_with_model_relation_chain_prefix
3907
+						 . $field_obj->get_table_alias()
3908
+						 . "."
3909
+						 . $field_obj->get_table_column()
3910
+						 . "'";
3911
+		}
3912
+		// make sure we are also getting the PKs of each table
3913
+		$tables = $this->get_tables();
3914
+		if (count($tables) > 1) {
3915
+			foreach ($tables as $table_obj) {
3916
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3917
+									   . $table_obj->get_fully_qualified_pk_column();
3918
+				if (! in_array($qualified_pk_column, $selects)) {
3919
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3920
+				}
3921
+			}
3922
+		}
3923
+		return $selects;
3924
+	}
3925
+
3926
+
3927
+
3928
+	/**
3929
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3930
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3931
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3932
+	 * SQL for joining, and the data types
3933
+	 *
3934
+	 * @param null|string                 $original_query_param
3935
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3936
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3937
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3938
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3939
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3940
+	 *                                                          or 'Registration's
3941
+	 * @param string                      $original_query_param what it originally was (eg
3942
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3943
+	 *                                                          matches $query_param
3944
+	 * @throws EE_Error
3945
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3946
+	 */
3947
+	private function _extract_related_model_info_from_query_param(
3948
+		$query_param,
3949
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3950
+		$query_param_type,
3951
+		$original_query_param = null
3952
+	) {
3953
+		if ($original_query_param === null) {
3954
+			$original_query_param = $query_param;
3955
+		}
3956
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3957
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3958
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3959
+		$allow_fields = in_array(
3960
+			$query_param_type,
3961
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3962
+			true
3963
+		);
3964
+		// check to see if we have a field on this model
3965
+		$this_model_fields = $this->field_settings(true);
3966
+		if (array_key_exists($query_param, $this_model_fields)) {
3967
+			if ($allow_fields) {
3968
+				return;
3969
+			}
3970
+			throw new EE_Error(
3971
+				sprintf(
3972
+					esc_html__(
3973
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3974
+						"event_espresso"
3975
+					),
3976
+					$query_param,
3977
+					get_class($this),
3978
+					$query_param_type,
3979
+					$original_query_param
3980
+				)
3981
+			);
3982
+		}
3983
+		// check if this is a special logic query param
3984
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3985
+			if ($allow_logic_query_params) {
3986
+				return;
3987
+			}
3988
+			throw new EE_Error(
3989
+				sprintf(
3990
+					esc_html__(
3991
+						'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',
3992
+						'event_espresso'
3993
+					),
3994
+					implode('", "', $this->_logic_query_param_keys),
3995
+					$query_param,
3996
+					get_class($this),
3997
+					'<br />',
3998
+					"\t"
3999
+					. ' $passed_in_query_info = <pre>'
4000
+					. print_r($passed_in_query_info, true)
4001
+					. '</pre>'
4002
+					. "\n\t"
4003
+					. ' $query_param_type = '
4004
+					. $query_param_type
4005
+					. "\n\t"
4006
+					. ' $original_query_param = '
4007
+					. $original_query_param
4008
+				)
4009
+			);
4010
+		}
4011
+		// check if it's a custom selection
4012
+		if (
4013
+			$this->_custom_selections instanceof CustomSelects
4014
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4015
+		) {
4016
+			return;
4017
+		}
4018
+		// check if has a model name at the beginning
4019
+		// and
4020
+		// check if it's a field on a related model
4021
+		if (
4022
+			$this->extractJoinModelFromQueryParams(
4023
+				$passed_in_query_info,
4024
+				$query_param,
4025
+				$original_query_param,
4026
+				$query_param_type
4027
+			)
4028
+		) {
4029
+			return;
4030
+		}
4031
+
4032
+		// ok so $query_param didn't start with a model name
4033
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4034
+		// it's wack, that's what it is
4035
+		throw new EE_Error(
4036
+			sprintf(
4037
+				esc_html__(
4038
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4039
+					"event_espresso"
4040
+				),
4041
+				$query_param,
4042
+				get_class($this),
4043
+				$query_param_type,
4044
+				$original_query_param
4045
+			)
4046
+		);
4047
+	}
4048
+
4049
+
4050
+	/**
4051
+	 * Extracts any possible join model information from the provided possible_join_string.
4052
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4053
+	 * parts that should be added to the query.
4054
+	 *
4055
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4056
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4057
+	 * @param null|string                 $original_query_param
4058
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4059
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4060
+	 * @return bool  returns true if a join was added and false if not.
4061
+	 * @throws EE_Error
4062
+	 */
4063
+	private function extractJoinModelFromQueryParams(
4064
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4065
+		$possible_join_string,
4066
+		$original_query_param,
4067
+		$query_parameter_type
4068
+	) {
4069
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4070
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4071
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4072
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4073
+				if ($possible_join_string === '') {
4074
+					// nothing left to $query_param
4075
+					// we should actually end in a field name, not a model like this!
4076
+					throw new EE_Error(
4077
+						sprintf(
4078
+							esc_html__(
4079
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4080
+								"event_espresso"
4081
+							),
4082
+							$possible_join_string,
4083
+							$query_parameter_type,
4084
+							get_class($this),
4085
+							$valid_related_model_name
4086
+						)
4087
+					);
4088
+				}
4089
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4090
+				$related_model_obj->_extract_related_model_info_from_query_param(
4091
+					$possible_join_string,
4092
+					$query_info_carrier,
4093
+					$query_parameter_type,
4094
+					$original_query_param
4095
+				);
4096
+				return true;
4097
+			}
4098
+			if ($possible_join_string === $valid_related_model_name) {
4099
+				$this->_add_join_to_model(
4100
+					$valid_related_model_name,
4101
+					$query_info_carrier,
4102
+					$original_query_param
4103
+				);
4104
+				return true;
4105
+			}
4106
+		}
4107
+		return false;
4108
+	}
4109
+
4110
+
4111
+	/**
4112
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4113
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4114
+	 * @throws EE_Error
4115
+	 */
4116
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4117
+	{
4118
+		if (
4119
+			$this->_custom_selections instanceof CustomSelects
4120
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4121
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4122
+			)
4123
+		) {
4124
+			$original_selects = $this->_custom_selections->originalSelects();
4125
+			foreach ($original_selects as $alias => $select_configuration) {
4126
+				$this->extractJoinModelFromQueryParams(
4127
+					$query_info_carrier,
4128
+					$select_configuration[0],
4129
+					$select_configuration[0],
4130
+					'custom_selects'
4131
+				);
4132
+			}
4133
+		}
4134
+	}
4135
+
4136
+
4137
+
4138
+	/**
4139
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4140
+	 * and store it on $passed_in_query_info
4141
+	 *
4142
+	 * @param string                      $model_name
4143
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4144
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4145
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4146
+	 *                                                          and are adding a join to 'Payment' with the original
4147
+	 *                                                          query param key
4148
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4149
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4150
+	 *                                                          Payment wants to add default query params so that it
4151
+	 *                                                          will know what models to prepend onto its default query
4152
+	 *                                                          params or in case it wants to rename tables (in case
4153
+	 *                                                          there are multiple joins to the same table)
4154
+	 * @return void
4155
+	 * @throws EE_Error
4156
+	 */
4157
+	private function _add_join_to_model(
4158
+		$model_name,
4159
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4160
+		$original_query_param
4161
+	) {
4162
+		$relation_obj = $this->related_settings_for($model_name);
4163
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4164
+		// check if the relation is HABTM, because then we're essentially doing two joins
4165
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4166
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4167
+			$join_model_obj = $relation_obj->get_join_model();
4168
+			// replace the model specified with the join model for this relation chain, whi
4169
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4170
+				$model_name,
4171
+				$join_model_obj->get_this_model_name(),
4172
+				$model_relation_chain
4173
+			);
4174
+			$passed_in_query_info->merge(
4175
+				new EE_Model_Query_Info_Carrier(
4176
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4177
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4178
+				)
4179
+			);
4180
+		}
4181
+		// now just join to the other table pointed to by the relation object, and add its data types
4182
+		$passed_in_query_info->merge(
4183
+			new EE_Model_Query_Info_Carrier(
4184
+				array($model_relation_chain => $model_name),
4185
+				$relation_obj->get_join_statement($model_relation_chain)
4186
+			)
4187
+		);
4188
+	}
4189
+
4190
+
4191
+
4192
+	/**
4193
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4194
+	 *
4195
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4196
+	 * @return string of SQL
4197
+	 * @throws EE_Error
4198
+	 */
4199
+	private function _construct_where_clause($where_params)
4200
+	{
4201
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4202
+		if ($SQL) {
4203
+			return " WHERE " . $SQL;
4204
+		}
4205
+		return '';
4206
+	}
4207
+
4208
+
4209
+
4210
+	/**
4211
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4212
+	 * and should be passed HAVING parameters, not WHERE parameters
4213
+	 *
4214
+	 * @param array $having_params
4215
+	 * @return string
4216
+	 * @throws EE_Error
4217
+	 */
4218
+	private function _construct_having_clause($having_params)
4219
+	{
4220
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4221
+		if ($SQL) {
4222
+			return " HAVING " . $SQL;
4223
+		}
4224
+		return '';
4225
+	}
4226
+
4227
+
4228
+	/**
4229
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4230
+	 * Event_Meta.meta_value = 'foo'))"
4231
+	 *
4232
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4233
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4234
+	 * @throws EE_Error
4235
+	 * @return string of SQL
4236
+	 */
4237
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4238
+	{
4239
+		$where_clauses = array();
4240
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4241
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4242
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4243
+				switch ($query_param) {
4244
+					case 'not':
4245
+					case 'NOT':
4246
+						$where_clauses[] = "! ("
4247
+										   . $this->_construct_condition_clause_recursive(
4248
+											   $op_and_value_or_sub_condition,
4249
+											   $glue
4250
+										   )
4251
+										   . ")";
4252
+						break;
4253
+					case 'and':
4254
+					case 'AND':
4255
+						$where_clauses[] = " ("
4256
+										   . $this->_construct_condition_clause_recursive(
4257
+											   $op_and_value_or_sub_condition,
4258
+											   ' AND '
4259
+										   )
4260
+										   . ")";
4261
+						break;
4262
+					case 'or':
4263
+					case 'OR':
4264
+						$where_clauses[] = " ("
4265
+										   . $this->_construct_condition_clause_recursive(
4266
+											   $op_and_value_or_sub_condition,
4267
+											   ' OR '
4268
+										   )
4269
+										   . ")";
4270
+						break;
4271
+				}
4272
+			} else {
4273
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4274
+				// if it's not a normal field, maybe it's a custom selection?
4275
+				if (! $field_obj) {
4276
+					if ($this->_custom_selections instanceof CustomSelects) {
4277
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4278
+					} else {
4279
+						throw new EE_Error(sprintf(esc_html__(
4280
+							"%s is neither a valid model field name, nor a custom selection",
4281
+							"event_espresso"
4282
+						), $query_param));
4283
+					}
4284
+				}
4285
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4286
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4287
+			}
4288
+		}
4289
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4290
+	}
4291
+
4292
+
4293
+
4294
+	/**
4295
+	 * Takes the input parameter and extract the table name (alias) and column name
4296
+	 *
4297
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4298
+	 * @throws EE_Error
4299
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4300
+	 */
4301
+	private function _deduce_column_name_from_query_param($query_param)
4302
+	{
4303
+		$field = $this->_deduce_field_from_query_param($query_param);
4304
+		if ($field) {
4305
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4306
+				$field->get_model_name(),
4307
+				$query_param
4308
+			);
4309
+			return $table_alias_prefix . $field->get_qualified_column();
4310
+		}
4311
+		if (
4312
+			$this->_custom_selections instanceof CustomSelects
4313
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4314
+		) {
4315
+			// maybe it's custom selection item?
4316
+			// if so, just use it as the "column name"
4317
+			return $query_param;
4318
+		}
4319
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4320
+			? implode(',', $this->_custom_selections->columnAliases())
4321
+			: '';
4322
+		throw new EE_Error(
4323
+			sprintf(
4324
+				esc_html__(
4325
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4326
+					"event_espresso"
4327
+				),
4328
+				$query_param,
4329
+				$custom_select_aliases
4330
+			)
4331
+		);
4332
+	}
4333
+
4334
+
4335
+
4336
+	/**
4337
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4338
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4339
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4340
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4341
+	 *
4342
+	 * @param string $condition_query_param_key
4343
+	 * @return string
4344
+	 */
4345
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4346
+	{
4347
+		$pos_of_star = strpos($condition_query_param_key, '*');
4348
+		if ($pos_of_star === false) {
4349
+			return $condition_query_param_key;
4350
+		}
4351
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4352
+		return $condition_query_param_sans_star;
4353
+	}
4354
+
4355
+
4356
+
4357
+	/**
4358
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4359
+	 *
4360
+	 * @param                            mixed      array | string    $op_and_value
4361
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4362
+	 * @throws EE_Error
4363
+	 * @return string
4364
+	 */
4365
+	private function _construct_op_and_value($op_and_value, $field_obj)
4366
+	{
4367
+		if (is_array($op_and_value)) {
4368
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4369
+			if (! $operator) {
4370
+				$php_array_like_string = array();
4371
+				foreach ($op_and_value as $key => $value) {
4372
+					$php_array_like_string[] = "$key=>$value";
4373
+				}
4374
+				throw new EE_Error(
4375
+					sprintf(
4376
+						esc_html__(
4377
+							"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))",
4378
+							"event_espresso"
4379
+						),
4380
+						implode(",", $php_array_like_string)
4381
+					)
4382
+				);
4383
+			}
4384
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4385
+		} else {
4386
+			$operator = '=';
4387
+			$value = $op_and_value;
4388
+		}
4389
+		// check to see if the value is actually another field
4390
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4391
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4392
+		}
4393
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4394
+			// in this case, the value should be an array, or at least a comma-separated list
4395
+			// it will need to handle a little differently
4396
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4397
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4398
+			return $operator . SP . $cleaned_value;
4399
+		}
4400
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4401
+			// the value should be an array with count of two.
4402
+			if (count($value) !== 2) {
4403
+				throw new EE_Error(
4404
+					sprintf(
4405
+						esc_html__(
4406
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4407
+							'event_espresso'
4408
+						),
4409
+						"BETWEEN"
4410
+					)
4411
+				);
4412
+			}
4413
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4414
+			return $operator . SP . $cleaned_value;
4415
+		}
4416
+		if (in_array($operator, $this->valid_null_style_operators())) {
4417
+			if ($value !== null) {
4418
+				throw new EE_Error(
4419
+					sprintf(
4420
+						esc_html__(
4421
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4422
+							"event_espresso"
4423
+						),
4424
+						$value,
4425
+						$operator
4426
+					)
4427
+				);
4428
+			}
4429
+			return $operator;
4430
+		}
4431
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4432
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4433
+			// remove other junk. So just treat it as a string.
4434
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4435
+		}
4436
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4438
+		}
4439
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4440
+			throw new EE_Error(
4441
+				sprintf(
4442
+					esc_html__(
4443
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4444
+						'event_espresso'
4445
+					),
4446
+					$operator,
4447
+					$operator
4448
+				)
4449
+			);
4450
+		}
4451
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452
+			throw new EE_Error(
4453
+				sprintf(
4454
+					esc_html__(
4455
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4456
+						'event_espresso'
4457
+					),
4458
+					$operator,
4459
+					$operator
4460
+				)
4461
+			);
4462
+		}
4463
+		throw new EE_Error(
4464
+			sprintf(
4465
+				esc_html__(
4466
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4467
+					"event_espresso"
4468
+				),
4469
+				http_build_query($op_and_value)
4470
+			)
4471
+		);
4472
+	}
4473
+
4474
+
4475
+
4476
+	/**
4477
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4478
+	 *
4479
+	 * @param array                      $values
4480
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4481
+	 *                                              '%s'
4482
+	 * @return string
4483
+	 * @throws EE_Error
4484
+	 */
4485
+	public function _construct_between_value($values, $field_obj)
4486
+	{
4487
+		$cleaned_values = array();
4488
+		foreach ($values as $value) {
4489
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4490
+		}
4491
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4492
+	}
4493
+
4494
+
4495
+	/**
4496
+	 * Takes an array or a comma-separated list of $values and cleans them
4497
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4498
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4499
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4500
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4501
+	 *
4502
+	 * @param mixed                      $values    array or comma-separated string
4503
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4504
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4505
+	 * @throws EE_Error
4506
+	 */
4507
+	public function _construct_in_value($values, $field_obj)
4508
+	{
4509
+		$prepped = [];
4510
+		// check if the value is a CSV list
4511
+		if (is_string($values)) {
4512
+			// in which case, turn it into an array
4513
+			$values = explode(',', $values);
4514
+		}
4515
+		// make sure we only have one of each value in the list
4516
+		$values = array_unique($values);
4517
+		foreach ($values as $value) {
4518
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4519
+		}
4520
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4521
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4522
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4523
+		if (empty($prepped)) {
4524
+			$all_fields = $this->field_settings();
4525
+			$first_field    = reset($all_fields);
4526
+			$main_table = $this->_get_main_table();
4527
+			$prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4528
+		}
4529
+		return '(' . implode(',', $prepped) . ')';
4530
+	}
4531
+
4532
+
4533
+
4534
+	/**
4535
+	 * @param mixed                      $value
4536
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4537
+	 * @throws EE_Error
4538
+	 * @return false|null|string
4539
+	 */
4540
+	private function _wpdb_prepare_using_field($value, $field_obj)
4541
+	{
4542
+		/** @type WPDB $wpdb */
4543
+		global $wpdb;
4544
+		if ($field_obj instanceof EE_Model_Field_Base) {
4545
+			return $wpdb->prepare(
4546
+				$field_obj->get_wpdb_data_type(),
4547
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4548
+			);
4549
+		} //$field_obj should really just be a data type
4550
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4551
+			throw new EE_Error(
4552
+				sprintf(
4553
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4554
+					$field_obj,
4555
+					implode(",", $this->_valid_wpdb_data_types)
4556
+				)
4557
+			);
4558
+		}
4559
+		return $wpdb->prepare($field_obj, $value);
4560
+	}
4561
+
4562
+
4563
+
4564
+	/**
4565
+	 * Takes the input parameter and finds the model field that it indicates.
4566
+	 *
4567
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4568
+	 * @throws EE_Error
4569
+	 * @return EE_Model_Field_Base
4570
+	 */
4571
+	protected function _deduce_field_from_query_param($query_param_name)
4572
+	{
4573
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4574
+		// which will help us find the database table and column
4575
+		$query_param_parts = explode(".", $query_param_name);
4576
+		if (empty($query_param_parts)) {
4577
+			throw new EE_Error(sprintf(esc_html__(
4578
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4579
+				'event_espresso'
4580
+			), $query_param_name));
4581
+		}
4582
+		$number_of_parts = count($query_param_parts);
4583
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4584
+		if ($number_of_parts === 1) {
4585
+			$field_name = $last_query_param_part;
4586
+			$model_obj = $this;
4587
+		} else {// $number_of_parts >= 2
4588
+			// the last part is the column name, and there are only 2parts. therefore...
4589
+			$field_name = $last_query_param_part;
4590
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4591
+		}
4592
+		try {
4593
+			return $model_obj->field_settings_for($field_name);
4594
+		} catch (EE_Error $e) {
4595
+			return null;
4596
+		}
4597
+	}
4598
+
4599
+
4600
+
4601
+	/**
4602
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4603
+	 * alias and column which corresponds to it
4604
+	 *
4605
+	 * @param string $field_name
4606
+	 * @throws EE_Error
4607
+	 * @return string
4608
+	 */
4609
+	public function _get_qualified_column_for_field($field_name)
4610
+	{
4611
+		$all_fields = $this->field_settings();
4612
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4613
+		if ($field) {
4614
+			return $field->get_qualified_column();
4615
+		}
4616
+		throw new EE_Error(
4617
+			sprintf(
4618
+				esc_html__(
4619
+					"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.",
4620
+					'event_espresso'
4621
+				),
4622
+				$field_name,
4623
+				get_class($this)
4624
+			)
4625
+		);
4626
+	}
4627
+
4628
+
4629
+
4630
+	/**
4631
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4632
+	 * Example usage:
4633
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4634
+	 *      array(),
4635
+	 *      ARRAY_A,
4636
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4637
+	 *  );
4638
+	 * is equivalent to
4639
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4640
+	 * and
4641
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4642
+	 *      array(
4643
+	 *          array(
4644
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4645
+	 *          ),
4646
+	 *          ARRAY_A,
4647
+	 *          implode(
4648
+	 *              ', ',
4649
+	 *              array_merge(
4650
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4651
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4652
+	 *              )
4653
+	 *          )
4654
+	 *      )
4655
+	 *  );
4656
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4657
+	 *
4658
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4659
+	 *                                            and the one whose fields you are selecting for example: when querying
4660
+	 *                                            tickets model and selecting fields from the tickets model you would
4661
+	 *                                            leave this parameter empty, because no models are needed to join
4662
+	 *                                            between the queried model and the selected one. Likewise when
4663
+	 *                                            querying the datetime model and selecting fields from the tickets
4664
+	 *                                            model, it would also be left empty, because there is a direct
4665
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4666
+	 *                                            them together. However, when querying from the event model and
4667
+	 *                                            selecting fields from the ticket model, you should provide the string
4668
+	 *                                            'Datetime', indicating that the event model must first join to the
4669
+	 *                                            datetime model in order to find its relation to ticket model.
4670
+	 *                                            Also, when querying from the venue model and selecting fields from
4671
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4672
+	 *                                            indicating you need to join the venue model to the event model,
4673
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4674
+	 *                                            This string is used to deduce the prefix that gets added onto the
4675
+	 *                                            models' tables qualified columns
4676
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4677
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4678
+	 *                                            qualified column names
4679
+	 * @return array|string
4680
+	 */
4681
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4682
+	{
4683
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4684
+		$qualified_columns = array();
4685
+		foreach ($this->field_settings() as $field_name => $field) {
4686
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4687
+		}
4688
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4689
+	}
4690
+
4691
+
4692
+
4693
+	/**
4694
+	 * constructs the select use on special limit joins
4695
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4696
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4697
+	 * (as that is typically where the limits would be set).
4698
+	 *
4699
+	 * @param  string       $table_alias The table the select is being built for
4700
+	 * @param  mixed|string $limit       The limit for this select
4701
+	 * @return string                The final select join element for the query.
4702
+	 */
4703
+	public function _construct_limit_join_select($table_alias, $limit)
4704
+	{
4705
+		$SQL = '';
4706
+		foreach ($this->_tables as $table_obj) {
4707
+			if ($table_obj instanceof EE_Primary_Table) {
4708
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4709
+					? $table_obj->get_select_join_limit($limit)
4710
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4711
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4712
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4713
+					? $table_obj->get_select_join_limit_join($limit)
4714
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4715
+			}
4716
+		}
4717
+		return $SQL;
4718
+	}
4719
+
4720
+
4721
+
4722
+	/**
4723
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4724
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4725
+	 *
4726
+	 * @return string SQL
4727
+	 * @throws EE_Error
4728
+	 */
4729
+	public function _construct_internal_join()
4730
+	{
4731
+		$SQL = $this->_get_main_table()->get_table_sql();
4732
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4733
+		return $SQL;
4734
+	}
4735
+
4736
+
4737
+
4738
+	/**
4739
+	 * Constructs the SQL for joining all the tables on this model.
4740
+	 * Normally $alias should be the primary table's alias, but in cases where
4741
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4742
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4743
+	 * alias, this will construct SQL like:
4744
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4745
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4746
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
+	 *
4748
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4749
+	 * @return string
4750
+	 */
4751
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4752
+	{
4753
+		$SQL = '';
4754
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4755
+		foreach ($this->_tables as $table_obj) {
4756
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4757
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4758
+					// so we're joining to this table, meaning the table is already in
4759
+					// the FROM statement, BUT the primary table isn't. So we want
4760
+					// to add the inverse join sql
4761
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4762
+				} else {
4763
+					// just add a regular JOIN to this table from the primary table
4764
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4765
+				}
4766
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4767
+		}
4768
+		return $SQL;
4769
+	}
4770
+
4771
+
4772
+
4773
+	/**
4774
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4775
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4776
+	 * their data type (eg, '%s', '%d', etc)
4777
+	 *
4778
+	 * @return array
4779
+	 */
4780
+	public function _get_data_types()
4781
+	{
4782
+		$data_types = array();
4783
+		foreach ($this->field_settings() as $field_obj) {
4784
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4785
+			/** @var $field_obj EE_Model_Field_Base */
4786
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4787
+		}
4788
+		return $data_types;
4789
+	}
4790
+
4791
+
4792
+
4793
+	/**
4794
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4795
+	 *
4796
+	 * @param string $model_name
4797
+	 * @throws EE_Error
4798
+	 * @return EEM_Base
4799
+	 */
4800
+	public function get_related_model_obj($model_name)
4801
+	{
4802
+		$model_classname = "EEM_" . $model_name;
4803
+		if (! class_exists($model_classname)) {
4804
+			throw new EE_Error(sprintf(esc_html__(
4805
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4806
+				'event_espresso'
4807
+			), $model_name, $model_classname));
4808
+		}
4809
+		return call_user_func($model_classname . "::instance");
4810
+	}
4811
+
4812
+
4813
+
4814
+	/**
4815
+	 * Returns the array of EE_ModelRelations for this model.
4816
+	 *
4817
+	 * @return EE_Model_Relation_Base[]
4818
+	 */
4819
+	public function relation_settings()
4820
+	{
4821
+		return $this->_model_relations;
4822
+	}
4823
+
4824
+
4825
+
4826
+	/**
4827
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4828
+	 * because without THOSE models, this model probably doesn't have much purpose.
4829
+	 * (Eg, without an event, datetimes have little purpose.)
4830
+	 *
4831
+	 * @return EE_Belongs_To_Relation[]
4832
+	 */
4833
+	public function belongs_to_relations()
4834
+	{
4835
+		$belongs_to_relations = array();
4836
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4837
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4838
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4839
+			}
4840
+		}
4841
+		return $belongs_to_relations;
4842
+	}
4843
+
4844
+
4845
+
4846
+	/**
4847
+	 * Returns the specified EE_Model_Relation, or throws an exception
4848
+	 *
4849
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4850
+	 * @throws EE_Error
4851
+	 * @return EE_Model_Relation_Base
4852
+	 */
4853
+	public function related_settings_for($relation_name)
4854
+	{
4855
+		$relatedModels = $this->relation_settings();
4856
+		if (! array_key_exists($relation_name, $relatedModels)) {
4857
+			throw new EE_Error(
4858
+				sprintf(
4859
+					esc_html__(
4860
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4861
+						'event_espresso'
4862
+					),
4863
+					$relation_name,
4864
+					$this->_get_class_name(),
4865
+					implode(', ', array_keys($relatedModels))
4866
+				)
4867
+			);
4868
+		}
4869
+		return $relatedModels[ $relation_name ];
4870
+	}
4871
+
4872
+
4873
+
4874
+	/**
4875
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4876
+	 * fields
4877
+	 *
4878
+	 * @param string $fieldName
4879
+	 * @param boolean $include_db_only_fields
4880
+	 * @throws EE_Error
4881
+	 * @return EE_Model_Field_Base
4882
+	 */
4883
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4884
+	{
4885
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4886
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4887
+			throw new EE_Error(sprintf(
4888
+				esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4889
+				$fieldName,
4890
+				get_class($this)
4891
+			));
4892
+		}
4893
+		return $fieldSettings[ $fieldName ];
4894
+	}
4895
+
4896
+
4897
+
4898
+	/**
4899
+	 * Checks if this field exists on this model
4900
+	 *
4901
+	 * @param string $fieldName a key in the model's _field_settings array
4902
+	 * @return boolean
4903
+	 */
4904
+	public function has_field($fieldName)
4905
+	{
4906
+		$fieldSettings = $this->field_settings(true);
4907
+		if (isset($fieldSettings[ $fieldName ])) {
4908
+			return true;
4909
+		}
4910
+		return false;
4911
+	}
4912
+
4913
+
4914
+
4915
+	/**
4916
+	 * Returns whether or not this model has a relation to the specified model
4917
+	 *
4918
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4919
+	 * @return boolean
4920
+	 */
4921
+	public function has_relation($relation_name)
4922
+	{
4923
+		$relations = $this->relation_settings();
4924
+		if (isset($relations[ $relation_name ])) {
4925
+			return true;
4926
+		}
4927
+		return false;
4928
+	}
4929
+
4930
+
4931
+
4932
+	/**
4933
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4934
+	 * Eg, on EE_Answer that would be ANS_ID field object
4935
+	 *
4936
+	 * @param $field_obj
4937
+	 * @return boolean
4938
+	 */
4939
+	public function is_primary_key_field($field_obj)
4940
+	{
4941
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4942
+	}
4943
+
4944
+
4945
+
4946
+	/**
4947
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4948
+	 * Eg, on EE_Answer that would be ANS_ID field object
4949
+	 *
4950
+	 * @return EE_Model_Field_Base
4951
+	 * @throws EE_Error
4952
+	 */
4953
+	public function get_primary_key_field()
4954
+	{
4955
+		if ($this->_primary_key_field === null) {
4956
+			foreach ($this->field_settings(true) as $field_obj) {
4957
+				if ($this->is_primary_key_field($field_obj)) {
4958
+					$this->_primary_key_field = $field_obj;
4959
+					break;
4960
+				}
4961
+			}
4962
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4963
+				throw new EE_Error(sprintf(
4964
+					esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4965
+					get_class($this)
4966
+				));
4967
+			}
4968
+		}
4969
+		return $this->_primary_key_field;
4970
+	}
4971
+
4972
+
4973
+
4974
+	/**
4975
+	 * Returns whether or not not there is a primary key on this model.
4976
+	 * Internally does some caching.
4977
+	 *
4978
+	 * @return boolean
4979
+	 */
4980
+	public function has_primary_key_field()
4981
+	{
4982
+		if ($this->_has_primary_key_field === null) {
4983
+			try {
4984
+				$this->get_primary_key_field();
4985
+				$this->_has_primary_key_field = true;
4986
+			} catch (EE_Error $e) {
4987
+				$this->_has_primary_key_field = false;
4988
+			}
4989
+		}
4990
+		return $this->_has_primary_key_field;
4991
+	}
4992
+
4993
+
4994
+
4995
+	/**
4996
+	 * Finds the first field of type $field_class_name.
4997
+	 *
4998
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4999
+	 *                                 EE_Foreign_Key_Field, etc
5000
+	 * @return EE_Model_Field_Base or null if none is found
5001
+	 */
5002
+	public function get_a_field_of_type($field_class_name)
5003
+	{
5004
+		foreach ($this->field_settings() as $field) {
5005
+			if ($field instanceof $field_class_name) {
5006
+				return $field;
5007
+			}
5008
+		}
5009
+		return null;
5010
+	}
5011
+
5012
+
5013
+
5014
+	/**
5015
+	 * Gets a foreign key field pointing to model.
5016
+	 *
5017
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5018
+	 * @return EE_Foreign_Key_Field_Base
5019
+	 * @throws EE_Error
5020
+	 */
5021
+	public function get_foreign_key_to($model_name)
5022
+	{
5023
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5024
+			foreach ($this->field_settings() as $field) {
5025
+				if (
5026
+					$field instanceof EE_Foreign_Key_Field_Base
5027
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5028
+				) {
5029
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5030
+					break;
5031
+				}
5032
+			}
5033
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5034
+				throw new EE_Error(sprintf(esc_html__(
5035
+					"There is no foreign key field pointing to model %s on model %s",
5036
+					'event_espresso'
5037
+				), $model_name, get_class($this)));
5038
+			}
5039
+		}
5040
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5041
+	}
5042
+
5043
+
5044
+
5045
+	/**
5046
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5047
+	 *
5048
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5049
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5050
+	 *                            Either one works
5051
+	 * @return string
5052
+	 */
5053
+	public function get_table_for_alias($table_alias)
5054
+	{
5055
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5056
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5057
+	}
5058
+
5059
+
5060
+
5061
+	/**
5062
+	 * Returns a flat array of all field son this model, instead of organizing them
5063
+	 * by table_alias as they are in the constructor.
5064
+	 *
5065
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5066
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5067
+	 */
5068
+	public function field_settings($include_db_only_fields = false)
5069
+	{
5070
+		if ($include_db_only_fields) {
5071
+			if ($this->_cached_fields === null) {
5072
+				$this->_cached_fields = array();
5073
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5074
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5075
+						$this->_cached_fields[ $field_name ] = $field_obj;
5076
+					}
5077
+				}
5078
+			}
5079
+			return $this->_cached_fields;
5080
+		}
5081
+		if ($this->_cached_fields_non_db_only === null) {
5082
+			$this->_cached_fields_non_db_only = array();
5083
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5084
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5085
+					/** @var $field_obj EE_Model_Field_Base */
5086
+					if (! $field_obj->is_db_only_field()) {
5087
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5088
+					}
5089
+				}
5090
+			}
5091
+		}
5092
+		return $this->_cached_fields_non_db_only;
5093
+	}
5094
+
5095
+
5096
+
5097
+	/**
5098
+	 *        cycle though array of attendees and create objects out of each item
5099
+	 *
5100
+	 * @access        private
5101
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5102
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5103
+	 *                           numerically indexed)
5104
+	 * @throws EE_Error
5105
+	 */
5106
+	protected function _create_objects($rows = array())
5107
+	{
5108
+		$array_of_objects = array();
5109
+		if (empty($rows)) {
5110
+			return array();
5111
+		}
5112
+		$count_if_model_has_no_primary_key = 0;
5113
+		$has_primary_key = $this->has_primary_key_field();
5114
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5115
+		foreach ((array) $rows as $row) {
5116
+			if (empty($row)) {
5117
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5118
+				return array();
5119
+			}
5120
+			// check if we've already set this object in the results array,
5121
+			// in which case there's no need to process it further (again)
5122
+			if ($has_primary_key) {
5123
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5124
+					$row,
5125
+					$primary_key_field->get_qualified_column(),
5126
+					$primary_key_field->get_table_column()
5127
+				);
5128
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5129
+					continue;
5130
+				}
5131
+			}
5132
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5133
+			if (! $classInstance) {
5134
+				throw new EE_Error(
5135
+					sprintf(
5136
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5137
+						$this->get_this_model_name(),
5138
+						http_build_query($row)
5139
+					)
5140
+				);
5141
+			}
5142
+			// set the timezone on the instantiated objects
5143
+			$classInstance->set_timezone($this->_timezone);
5144
+			// make sure if there is any timezone setting present that we set the timezone for the object
5145
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5146
+			$array_of_objects[ $key ] = $classInstance;
5147
+			// also, for all the relations of type BelongsTo, see if we can cache
5148
+			// those related models
5149
+			// (we could do this for other relations too, but if there are conditions
5150
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5151
+			// so it requires a little more thought than just caching them immediately...)
5152
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5153
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5154
+					// check if this model's INFO is present. If so, cache it on the model
5155
+					$other_model = $relation_obj->get_other_model();
5156
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5157
+					// if we managed to make a model object from the results, cache it on the main model object
5158
+					if ($other_model_obj_maybe) {
5159
+						// set timezone on these other model objects if they are present
5160
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5161
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5162
+					}
5163
+				}
5164
+			}
5165
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5166
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5167
+			// the field in the CustomSelects object
5168
+			if ($this->_custom_selections instanceof CustomSelects) {
5169
+				$classInstance->setCustomSelectsValues(
5170
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5171
+				);
5172
+			}
5173
+		}
5174
+		return $array_of_objects;
5175
+	}
5176
+
5177
+
5178
+	/**
5179
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5180
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5181
+	 *
5182
+	 * @param array $db_results_row
5183
+	 * @return array
5184
+	 */
5185
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5186
+	{
5187
+		$results = array();
5188
+		if ($this->_custom_selections instanceof CustomSelects) {
5189
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5190
+				if (isset($db_results_row[ $alias ])) {
5191
+					$results[ $alias ] = $this->convertValueToDataType(
5192
+						$db_results_row[ $alias ],
5193
+						$this->_custom_selections->getDataTypeForAlias($alias)
5194
+					);
5195
+				}
5196
+			}
5197
+		}
5198
+		return $results;
5199
+	}
5200
+
5201
+
5202
+	/**
5203
+	 * This will set the value for the given alias
5204
+	 * @param string $value
5205
+	 * @param string $datatype (one of %d, %s, %f)
5206
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5207
+	 */
5208
+	protected function convertValueToDataType($value, $datatype)
5209
+	{
5210
+		switch ($datatype) {
5211
+			case '%f':
5212
+				return (float) $value;
5213
+			case '%d':
5214
+				return (int) $value;
5215
+			default:
5216
+				return (string) $value;
5217
+		}
5218
+	}
5219
+
5220
+
5221
+	/**
5222
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5223
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5224
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5225
+	 * object (as set in the model_field!).
5226
+	 *
5227
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5228
+	 */
5229
+	public function create_default_object()
5230
+	{
5231
+		$this_model_fields_and_values = array();
5232
+		// setup the row using default values;
5233
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5234
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5235
+		}
5236
+		$className = $this->_get_class_name();
5237
+		$classInstance = EE_Registry::instance()
5238
+									->load_class($className, array($this_model_fields_and_values), false, false);
5239
+		return $classInstance;
5240
+	}
5241
+
5242
+
5243
+
5244
+	/**
5245
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5246
+	 *                             or an stdClass where each property is the name of a column,
5247
+	 * @return EE_Base_Class
5248
+	 * @throws EE_Error
5249
+	 */
5250
+	public function instantiate_class_from_array_or_object($cols_n_values)
5251
+	{
5252
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5253
+			$cols_n_values = get_object_vars($cols_n_values);
5254
+		}
5255
+		$primary_key = null;
5256
+		// make sure the array only has keys that are fields/columns on this model
5257
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5258
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5259
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5260
+		}
5261
+		$className = $this->_get_class_name();
5262
+		// check we actually found results that we can use to build our model object
5263
+		// if not, return null
5264
+		if ($this->has_primary_key_field()) {
5265
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5266
+				return null;
5267
+			}
5268
+		} elseif ($this->unique_indexes()) {
5269
+			$first_column = reset($this_model_fields_n_values);
5270
+			if (empty($first_column)) {
5271
+				return null;
5272
+			}
5273
+		}
5274
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5275
+		if ($primary_key) {
5276
+			$classInstance = $this->get_from_entity_map($primary_key);
5277
+			if (! $classInstance) {
5278
+				$classInstance = EE_Registry::instance()
5279
+											->load_class(
5280
+												$className,
5281
+												array($this_model_fields_n_values, $this->_timezone),
5282
+												true,
5283
+												false
5284
+											);
5285
+				// add this new object to the entity map
5286
+				$classInstance = $this->add_to_entity_map($classInstance);
5287
+			}
5288
+		} else {
5289
+			$classInstance = EE_Registry::instance()
5290
+										->load_class(
5291
+											$className,
5292
+											array($this_model_fields_n_values, $this->_timezone),
5293
+											true,
5294
+											false
5295
+										);
5296
+		}
5297
+		return $classInstance;
5298
+	}
5299
+
5300
+
5301
+
5302
+	/**
5303
+	 * Gets the model object from the  entity map if it exists
5304
+	 *
5305
+	 * @param int|string $id the ID of the model object
5306
+	 * @return EE_Base_Class
5307
+	 */
5308
+	public function get_from_entity_map($id)
5309
+	{
5310
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5311
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5312
+	}
5313
+
5314
+
5315
+
5316
+	/**
5317
+	 * add_to_entity_map
5318
+	 * Adds the object to the model's entity mappings
5319
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5320
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5321
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5322
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5323
+	 *        then this method should be called immediately after the update query
5324
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5325
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5326
+	 *
5327
+	 * @param    EE_Base_Class $object
5328
+	 * @throws EE_Error
5329
+	 * @return \EE_Base_Class
5330
+	 */
5331
+	public function add_to_entity_map(EE_Base_Class $object)
5332
+	{
5333
+		$className = $this->_get_class_name();
5334
+		if (! $object instanceof $className) {
5335
+			throw new EE_Error(sprintf(
5336
+				esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5337
+				is_object($object) ? get_class($object) : $object,
5338
+				$className
5339
+			));
5340
+		}
5341
+		/** @var $object EE_Base_Class */
5342
+		if (! $object->ID()) {
5343
+			throw new EE_Error(sprintf(esc_html__(
5344
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5345
+				"event_espresso"
5346
+			), get_class($this)));
5347
+		}
5348
+		// double check it's not already there
5349
+		$classInstance = $this->get_from_entity_map($object->ID());
5350
+		if ($classInstance) {
5351
+			return $classInstance;
5352
+		}
5353
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5354
+		return $object;
5355
+	}
5356
+
5357
+
5358
+
5359
+	/**
5360
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5361
+	 * if no identifier is provided, then the entire entity map is emptied
5362
+	 *
5363
+	 * @param int|string $id the ID of the model object
5364
+	 * @return boolean
5365
+	 */
5366
+	public function clear_entity_map($id = null)
5367
+	{
5368
+		if (empty($id)) {
5369
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5370
+			return true;
5371
+		}
5372
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5373
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5374
+			return true;
5375
+		}
5376
+		return false;
5377
+	}
5378
+
5379
+
5380
+
5381
+	/**
5382
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5383
+	 * Given an array where keys are column (or column alias) names and values,
5384
+	 * returns an array of their corresponding field names and database values
5385
+	 *
5386
+	 * @param array $cols_n_values
5387
+	 * @return array
5388
+	 */
5389
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5390
+	{
5391
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5392
+	}
5393
+
5394
+
5395
+
5396
+	/**
5397
+	 * _deduce_fields_n_values_from_cols_n_values
5398
+	 * Given an array where keys are column (or column alias) names and values,
5399
+	 * returns an array of their corresponding field names and database values
5400
+	 *
5401
+	 * @param string $cols_n_values
5402
+	 * @return array
5403
+	 */
5404
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5405
+	{
5406
+		$this_model_fields_n_values = array();
5407
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5408
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5409
+				$cols_n_values,
5410
+				$table_obj->get_fully_qualified_pk_column(),
5411
+				$table_obj->get_pk_column()
5412
+			);
5413
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5414
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5415
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5416
+					if (! $field_obj->is_db_only_field()) {
5417
+						// prepare field as if its coming from db
5418
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5419
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5420
+					}
5421
+				}
5422
+			} else {
5423
+				// the table's rows existed. Use their values
5424
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5425
+					if (! $field_obj->is_db_only_field()) {
5426
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5427
+							$cols_n_values,
5428
+							$field_obj->get_qualified_column(),
5429
+							$field_obj->get_table_column()
5430
+						);
5431
+					}
5432
+				}
5433
+			}
5434
+		}
5435
+		return $this_model_fields_n_values;
5436
+	}
5437
+
5438
+
5439
+	/**
5440
+	 * @param $cols_n_values
5441
+	 * @param $qualified_column
5442
+	 * @param $regular_column
5443
+	 * @return null
5444
+	 * @throws EE_Error
5445
+	 * @throws ReflectionException
5446
+	 */
5447
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5448
+	{
5449
+		$value = null;
5450
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5451
+		// does the field on the model relate to this column retrieved from the db?
5452
+		// or is it a db-only field? (not relating to the model)
5453
+		if (isset($cols_n_values[ $qualified_column ])) {
5454
+			$value = $cols_n_values[ $qualified_column ];
5455
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5456
+			$value = $cols_n_values[ $regular_column ];
5457
+		} elseif (! empty($this->foreign_key_aliases)) {
5458
+			// no PK?  ok check if there is a foreign key alias set for this table
5459
+			// then check if that alias exists in the incoming data
5460
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5461
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5462
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5463
+					$value = $cols_n_values[ $FK_alias ];
5464
+					list($pk_class) = explode('.', $PK_column);
5465
+					$pk_model_name = "EEM_{$pk_class}";
5466
+					/** @var EEM_Base $pk_model */
5467
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5468
+					if ($pk_model instanceof EEM_Base) {
5469
+						// make sure object is pulled from db and added to entity map
5470
+						$pk_model->get_one_by_ID($value);
5471
+					}
5472
+					break;
5473
+				}
5474
+			}
5475
+		}
5476
+		return $value;
5477
+	}
5478
+
5479
+
5480
+
5481
+	/**
5482
+	 * refresh_entity_map_from_db
5483
+	 * Makes sure the model object in the entity map at $id assumes the values
5484
+	 * of the database (opposite of EE_base_Class::save())
5485
+	 *
5486
+	 * @param int|string $id
5487
+	 * @return EE_Base_Class
5488
+	 * @throws EE_Error
5489
+	 */
5490
+	public function refresh_entity_map_from_db($id)
5491
+	{
5492
+		$obj_in_map = $this->get_from_entity_map($id);
5493
+		if ($obj_in_map) {
5494
+			$wpdb_results = $this->_get_all_wpdb_results(
5495
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5496
+			);
5497
+			if ($wpdb_results && is_array($wpdb_results)) {
5498
+				$one_row = reset($wpdb_results);
5499
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5500
+					$obj_in_map->set_from_db($field_name, $db_value);
5501
+				}
5502
+				// clear the cache of related model objects
5503
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5504
+					$obj_in_map->clear_cache($relation_name, null, true);
5505
+				}
5506
+			}
5507
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5508
+			return $obj_in_map;
5509
+		}
5510
+		return $this->get_one_by_ID($id);
5511
+	}
5512
+
5513
+
5514
+
5515
+	/**
5516
+	 * refresh_entity_map_with
5517
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5518
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5519
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5520
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5521
+	 *
5522
+	 * @param int|string    $id
5523
+	 * @param EE_Base_Class $replacing_model_obj
5524
+	 * @return \EE_Base_Class
5525
+	 * @throws EE_Error
5526
+	 */
5527
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5528
+	{
5529
+		$obj_in_map = $this->get_from_entity_map($id);
5530
+		if ($obj_in_map) {
5531
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5532
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5533
+					$obj_in_map->set($field_name, $value);
5534
+				}
5535
+				// make the model object in the entity map's cache match the $replacing_model_obj
5536
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5537
+					$obj_in_map->clear_cache($relation_name, null, true);
5538
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5539
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5540
+					}
5541
+				}
5542
+			}
5543
+			return $obj_in_map;
5544
+		}
5545
+		$this->add_to_entity_map($replacing_model_obj);
5546
+		return $replacing_model_obj;
5547
+	}
5548
+
5549
+
5550
+
5551
+	/**
5552
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5553
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5554
+	 * require_once($this->_getClassName().".class.php");
5555
+	 *
5556
+	 * @return string
5557
+	 */
5558
+	private function _get_class_name()
5559
+	{
5560
+		return "EE_" . $this->get_this_model_name();
5561
+	}
5562
+
5563
+
5564
+
5565
+	/**
5566
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5567
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5568
+	 * it would be 'Events'.
5569
+	 *
5570
+	 * @param int $quantity
5571
+	 * @return string
5572
+	 */
5573
+	public function item_name($quantity = 1)
5574
+	{
5575
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5576
+	}
5577
+
5578
+
5579
+
5580
+	/**
5581
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5582
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5583
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5584
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5585
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5586
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5587
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5588
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5589
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5590
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5591
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5592
+	 *        return $previousReturnValue.$returnString;
5593
+	 * }
5594
+	 * require('EEM_Answer.model.php');
5595
+	 * $answer=EEM_Answer::instance();
5596
+	 * echo $answer->my_callback('monkeys',100);
5597
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5598
+	 *
5599
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5600
+	 * @param array  $args       array of original arguments passed to the function
5601
+	 * @throws EE_Error
5602
+	 * @return mixed whatever the plugin which calls add_filter decides
5603
+	 */
5604
+	public function __call($methodName, $args)
5605
+	{
5606
+		$className = get_class($this);
5607
+		$tagName = "FHEE__{$className}__{$methodName}";
5608
+		if (! has_filter($tagName)) {
5609
+			throw new EE_Error(
5610
+				sprintf(
5611
+					esc_html__(
5612
+						'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 );',
5613
+						'event_espresso'
5614
+					),
5615
+					$methodName,
5616
+					$className,
5617
+					$tagName,
5618
+					'<br />'
5619
+				)
5620
+			);
5621
+		}
5622
+		return apply_filters($tagName, null, $this, $args);
5623
+	}
5624
+
5625
+
5626
+
5627
+	/**
5628
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5629
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5630
+	 *
5631
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5632
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5633
+	 *                                                       the object's class name
5634
+	 *                                                       or object's ID
5635
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5636
+	 *                                                       exists in the database. If it does not, we add it
5637
+	 * @throws EE_Error
5638
+	 * @return EE_Base_Class
5639
+	 */
5640
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5641
+	{
5642
+		$className = $this->_get_class_name();
5643
+		if ($base_class_obj_or_id instanceof $className) {
5644
+			$model_object = $base_class_obj_or_id;
5645
+		} else {
5646
+			$primary_key_field = $this->get_primary_key_field();
5647
+			if (
5648
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5649
+				&& (
5650
+					is_int($base_class_obj_or_id)
5651
+					|| is_string($base_class_obj_or_id)
5652
+				)
5653
+			) {
5654
+				// assume it's an ID.
5655
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5656
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5657
+			} elseif (
5658
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5659
+				&& is_string($base_class_obj_or_id)
5660
+			) {
5661
+				// assume its a string representation of the object
5662
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5663
+			} else {
5664
+				throw new EE_Error(
5665
+					sprintf(
5666
+						esc_html__(
5667
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5668
+							'event_espresso'
5669
+						),
5670
+						$base_class_obj_or_id,
5671
+						$this->_get_class_name(),
5672
+						print_r($base_class_obj_or_id, true)
5673
+					)
5674
+				);
5675
+			}
5676
+		}
5677
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5678
+			$model_object->save();
5679
+		}
5680
+		return $model_object;
5681
+	}
5682
+
5683
+
5684
+
5685
+	/**
5686
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5687
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5688
+	 * returns it ID.
5689
+	 *
5690
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5691
+	 * @return int|string depending on the type of this model object's ID
5692
+	 * @throws EE_Error
5693
+	 */
5694
+	public function ensure_is_ID($base_class_obj_or_id)
5695
+	{
5696
+		$className = $this->_get_class_name();
5697
+		if ($base_class_obj_or_id instanceof $className) {
5698
+			/** @var $base_class_obj_or_id EE_Base_Class */
5699
+			$id = $base_class_obj_or_id->ID();
5700
+		} elseif (is_int($base_class_obj_or_id)) {
5701
+			// assume it's an ID
5702
+			$id = $base_class_obj_or_id;
5703
+		} elseif (is_string($base_class_obj_or_id)) {
5704
+			// assume its a string representation of the object
5705
+			$id = $base_class_obj_or_id;
5706
+		} else {
5707
+			throw new EE_Error(sprintf(
5708
+				esc_html__(
5709
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5710
+					'event_espresso'
5711
+				),
5712
+				$base_class_obj_or_id,
5713
+				$this->_get_class_name(),
5714
+				print_r($base_class_obj_or_id, true)
5715
+			));
5716
+		}
5717
+		return $id;
5718
+	}
5719
+
5720
+
5721
+
5722
+	/**
5723
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5724
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5725
+	 * been sanitized and converted into the appropriate domain.
5726
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5727
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5728
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5729
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5730
+	 * $EVT = EEM_Event::instance(); $old_setting =
5731
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5732
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5733
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5734
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5735
+	 *
5736
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5737
+	 * @return void
5738
+	 */
5739
+	public function assume_values_already_prepared_by_model_object(
5740
+		$values_already_prepared = self::not_prepared_by_model_object
5741
+	) {
5742
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5743
+	}
5744
+
5745
+
5746
+
5747
+	/**
5748
+	 * Read comments for assume_values_already_prepared_by_model_object()
5749
+	 *
5750
+	 * @return int
5751
+	 */
5752
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5753
+	{
5754
+		return $this->_values_already_prepared_by_model_object;
5755
+	}
5756
+
5757
+
5758
+
5759
+	/**
5760
+	 * Gets all the indexes on this model
5761
+	 *
5762
+	 * @return EE_Index[]
5763
+	 */
5764
+	public function indexes()
5765
+	{
5766
+		return $this->_indexes;
5767
+	}
5768
+
5769
+
5770
+
5771
+	/**
5772
+	 * Gets all the Unique Indexes on this model
5773
+	 *
5774
+	 * @return EE_Unique_Index[]
5775
+	 */
5776
+	public function unique_indexes()
5777
+	{
5778
+		$unique_indexes = array();
5779
+		foreach ($this->_indexes as $name => $index) {
5780
+			if ($index instanceof EE_Unique_Index) {
5781
+				$unique_indexes [ $name ] = $index;
5782
+			}
5783
+		}
5784
+		return $unique_indexes;
5785
+	}
5786
+
5787
+
5788
+
5789
+	/**
5790
+	 * Gets all the fields which, when combined, make the primary key.
5791
+	 * This is usually just an array with 1 element (the primary key), but in cases
5792
+	 * where there is no primary key, it's a combination of fields as defined
5793
+	 * on a primary index
5794
+	 *
5795
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5796
+	 * @throws EE_Error
5797
+	 */
5798
+	public function get_combined_primary_key_fields()
5799
+	{
5800
+		foreach ($this->indexes() as $index) {
5801
+			if ($index instanceof EE_Primary_Key_Index) {
5802
+				return $index->fields();
5803
+			}
5804
+		}
5805
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5806
+	}
5807
+
5808
+
5809
+
5810
+	/**
5811
+	 * Used to build a primary key string (when the model has no primary key),
5812
+	 * which can be used a unique string to identify this model object.
5813
+	 *
5814
+	 * @param array $fields_n_values keys are field names, values are their values.
5815
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5816
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5817
+	 *                               before passing it to this function (that will convert it from columns-n-values
5818
+	 *                               to field-names-n-values).
5819
+	 * @return string
5820
+	 * @throws EE_Error
5821
+	 */
5822
+	public function get_index_primary_key_string($fields_n_values)
5823
+	{
5824
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5825
+			$fields_n_values,
5826
+			$this->get_combined_primary_key_fields()
5827
+		);
5828
+		return http_build_query($cols_n_values_for_primary_key_index);
5829
+	}
5830
+
5831
+
5832
+
5833
+	/**
5834
+	 * Gets the field values from the primary key string
5835
+	 *
5836
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5837
+	 * @param string $index_primary_key_string
5838
+	 * @return null|array
5839
+	 * @throws EE_Error
5840
+	 */
5841
+	public function parse_index_primary_key_string($index_primary_key_string)
5842
+	{
5843
+		$key_fields = $this->get_combined_primary_key_fields();
5844
+		// check all of them are in the $id
5845
+		$key_vals_in_combined_pk = array();
5846
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5847
+		foreach ($key_fields as $key_field_name => $field_obj) {
5848
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5849
+				return null;
5850
+			}
5851
+		}
5852
+		return $key_vals_in_combined_pk;
5853
+	}
5854
+
5855
+
5856
+
5857
+	/**
5858
+	 * verifies that an array of key-value pairs for model fields has a key
5859
+	 * for each field comprising the primary key index
5860
+	 *
5861
+	 * @param array $key_vals
5862
+	 * @return boolean
5863
+	 * @throws EE_Error
5864
+	 */
5865
+	public function has_all_combined_primary_key_fields($key_vals)
5866
+	{
5867
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5868
+		foreach ($keys_it_should_have as $key) {
5869
+			if (! isset($key_vals[ $key ])) {
5870
+				return false;
5871
+			}
5872
+		}
5873
+		return true;
5874
+	}
5875
+
5876
+
5877
+
5878
+	/**
5879
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5880
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5881
+	 *
5882
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5883
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5884
+	 * @throws EE_Error
5885
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5886
+	 *                                                              indexed)
5887
+	 */
5888
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5889
+	{
5890
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5891
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5892
+		} elseif (is_array($model_object_or_attributes_array)) {
5893
+			$attributes_array = $model_object_or_attributes_array;
5894
+		} else {
5895
+			throw new EE_Error(sprintf(esc_html__(
5896
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5897
+				"event_espresso"
5898
+			), $model_object_or_attributes_array));
5899
+		}
5900
+		// even copies obviously won't have the same ID, so remove the primary key
5901
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5902
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5903
+			unset($attributes_array[ $this->primary_key_name() ]);
5904
+		}
5905
+		if (isset($query_params[0])) {
5906
+			$query_params[0] = array_merge($attributes_array, $query_params);
5907
+		} else {
5908
+			$query_params[0] = $attributes_array;
5909
+		}
5910
+		return $this->get_all($query_params);
5911
+	}
5912
+
5913
+
5914
+
5915
+	/**
5916
+	 * Gets the first copy we find. See get_all_copies for more details
5917
+	 *
5918
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5919
+	 * @param array $query_params
5920
+	 * @return EE_Base_Class
5921
+	 * @throws EE_Error
5922
+	 */
5923
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5924
+	{
5925
+		if (! is_array($query_params)) {
5926
+			EE_Error::doing_it_wrong(
5927
+				'EEM_Base::get_one_copy',
5928
+				sprintf(
5929
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5930
+					gettype($query_params)
5931
+				),
5932
+				'4.6.0'
5933
+			);
5934
+			$query_params = array();
5935
+		}
5936
+		$query_params['limit'] = 1;
5937
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5938
+		if (is_array($copies)) {
5939
+			return array_shift($copies);
5940
+		}
5941
+		return null;
5942
+	}
5943
+
5944
+
5945
+
5946
+	/**
5947
+	 * Updates the item with the specified id. Ignores default query parameters because
5948
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5949
+	 *
5950
+	 * @param array      $fields_n_values keys are field names, values are their new values
5951
+	 * @param int|string $id              the value of the primary key to update
5952
+	 * @return int number of rows updated
5953
+	 * @throws EE_Error
5954
+	 */
5955
+	public function update_by_ID($fields_n_values, $id)
5956
+	{
5957
+		$query_params = array(
5958
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5959
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5960
+		);
5961
+		return $this->update($fields_n_values, $query_params);
5962
+	}
5963
+
5964
+
5965
+
5966
+	/**
5967
+	 * Changes an operator which was supplied to the models into one usable in SQL
5968
+	 *
5969
+	 * @param string $operator_supplied
5970
+	 * @return string an operator which can be used in SQL
5971
+	 * @throws EE_Error
5972
+	 */
5973
+	private function _prepare_operator_for_sql($operator_supplied)
5974
+	{
5975
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5976
+			: null;
5977
+		if ($sql_operator) {
5978
+			return $sql_operator;
5979
+		}
5980
+		throw new EE_Error(
5981
+			sprintf(
5982
+				esc_html__(
5983
+					"The operator '%s' is not in the list of valid operators: %s",
5984
+					"event_espresso"
5985
+				),
5986
+				$operator_supplied,
5987
+				implode(",", array_keys($this->_valid_operators))
5988
+			)
5989
+		);
5990
+	}
5991
+
5992
+
5993
+
5994
+	/**
5995
+	 * Gets the valid operators
5996
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5997
+	 */
5998
+	public function valid_operators()
5999
+	{
6000
+		return $this->_valid_operators;
6001
+	}
6002
+
6003
+
6004
+
6005
+	/**
6006
+	 * Gets the between-style operators (take 2 arguments).
6007
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6008
+	 */
6009
+	public function valid_between_style_operators()
6010
+	{
6011
+		return array_intersect(
6012
+			$this->valid_operators(),
6013
+			$this->_between_style_operators
6014
+		);
6015
+	}
6016
+
6017
+	/**
6018
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6019
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6020
+	 */
6021
+	public function valid_like_style_operators()
6022
+	{
6023
+		return array_intersect(
6024
+			$this->valid_operators(),
6025
+			$this->_like_style_operators
6026
+		);
6027
+	}
6028
+
6029
+	/**
6030
+	 * Gets the "in"-style operators
6031
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6032
+	 */
6033
+	public function valid_in_style_operators()
6034
+	{
6035
+		return array_intersect(
6036
+			$this->valid_operators(),
6037
+			$this->_in_style_operators
6038
+		);
6039
+	}
6040
+
6041
+	/**
6042
+	 * Gets the "null"-style operators (accept no arguments)
6043
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6044
+	 */
6045
+	public function valid_null_style_operators()
6046
+	{
6047
+		return array_intersect(
6048
+			$this->valid_operators(),
6049
+			$this->_null_style_operators
6050
+		);
6051
+	}
6052
+
6053
+	/**
6054
+	 * Gets an array where keys are the primary keys and values are their 'names'
6055
+	 * (as determined by the model object's name() function, which is often overridden)
6056
+	 *
6057
+	 * @param array $query_params like get_all's
6058
+	 * @return string[]
6059
+	 * @throws EE_Error
6060
+	 */
6061
+	public function get_all_names($query_params = array())
6062
+	{
6063
+		$objs = $this->get_all($query_params);
6064
+		$names = array();
6065
+		foreach ($objs as $obj) {
6066
+			$names[ $obj->ID() ] = $obj->name();
6067
+		}
6068
+		return $names;
6069
+	}
6070
+
6071
+
6072
+
6073
+	/**
6074
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6075
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6076
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6077
+	 * array_keys() on $model_objects.
6078
+	 *
6079
+	 * @param \EE_Base_Class[] $model_objects
6080
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6081
+	 *                                               in the returned array
6082
+	 * @return array
6083
+	 * @throws EE_Error
6084
+	 */
6085
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6086
+	{
6087
+		if (! $this->has_primary_key_field()) {
6088
+			if (WP_DEBUG) {
6089
+				EE_Error::add_error(
6090
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6091
+					__FILE__,
6092
+					__FUNCTION__,
6093
+					__LINE__
6094
+				);
6095
+			}
6096
+		}
6097
+		$IDs = array();
6098
+		foreach ($model_objects as $model_object) {
6099
+			$id = $model_object->ID();
6100
+			if (! $id) {
6101
+				if ($filter_out_empty_ids) {
6102
+					continue;
6103
+				}
6104
+				if (WP_DEBUG) {
6105
+					EE_Error::add_error(
6106
+						esc_html__(
6107
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6108
+							'event_espresso'
6109
+						),
6110
+						__FILE__,
6111
+						__FUNCTION__,
6112
+						__LINE__
6113
+					);
6114
+				}
6115
+			}
6116
+			$IDs[] = $id;
6117
+		}
6118
+		return $IDs;
6119
+	}
6120
+
6121
+
6122
+
6123
+	/**
6124
+	 * Returns the string used in capabilities relating to this model. If there
6125
+	 * are no capabilities that relate to this model returns false
6126
+	 *
6127
+	 * @return string|false
6128
+	 */
6129
+	public function cap_slug()
6130
+	{
6131
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6132
+	}
6133
+
6134
+
6135
+
6136
+	/**
6137
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6138
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6139
+	 * only returns the cap restrictions array in that context (ie, the array
6140
+	 * at that key)
6141
+	 *
6142
+	 * @param string $context
6143
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6144
+	 * @throws EE_Error
6145
+	 */
6146
+	public function cap_restrictions($context = EEM_Base::caps_read)
6147
+	{
6148
+		EEM_Base::verify_is_valid_cap_context($context);
6149
+		// check if we ought to run the restriction generator first
6150
+		if (
6151
+			isset($this->_cap_restriction_generators[ $context ])
6152
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6153
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6154
+		) {
6155
+			$this->_cap_restrictions[ $context ] = array_merge(
6156
+				$this->_cap_restrictions[ $context ],
6157
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6158
+			);
6159
+		}
6160
+		// and make sure we've finalized the construction of each restriction
6161
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6162
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6163
+				$where_conditions_obj->_finalize_construct($this);
6164
+			}
6165
+		}
6166
+		return $this->_cap_restrictions[ $context ];
6167
+	}
6168
+
6169
+
6170
+
6171
+	/**
6172
+	 * Indicating whether or not this model thinks its a wp core model
6173
+	 *
6174
+	 * @return boolean
6175
+	 */
6176
+	public function is_wp_core_model()
6177
+	{
6178
+		return $this->_wp_core_model;
6179
+	}
6180
+
6181
+
6182
+
6183
+	/**
6184
+	 * Gets all the caps that are missing which impose a restriction on
6185
+	 * queries made in this context
6186
+	 *
6187
+	 * @param string $context one of EEM_Base::caps_ constants
6188
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6189
+	 * @throws EE_Error
6190
+	 */
6191
+	public function caps_missing($context = EEM_Base::caps_read)
6192
+	{
6193
+		$missing_caps = array();
6194
+		$cap_restrictions = $this->cap_restrictions($context);
6195
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6196
+			if (
6197
+				! EE_Capabilities::instance()
6198
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6199
+			) {
6200
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6201
+			}
6202
+		}
6203
+		return $missing_caps;
6204
+	}
6205
+
6206
+
6207
+
6208
+	/**
6209
+	 * Gets the mapping from capability contexts to action strings used in capability names
6210
+	 *
6211
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6212
+	 * one of 'read', 'edit', or 'delete'
6213
+	 */
6214
+	public function cap_contexts_to_cap_action_map()
6215
+	{
6216
+		return apply_filters(
6217
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6218
+			$this->_cap_contexts_to_cap_action_map,
6219
+			$this
6220
+		);
6221
+	}
6222
+
6223
+
6224
+
6225
+	/**
6226
+	 * Gets the action string for the specified capability context
6227
+	 *
6228
+	 * @param string $context
6229
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6230
+	 * @throws EE_Error
6231
+	 */
6232
+	public function cap_action_for_context($context)
6233
+	{
6234
+		$mapping = $this->cap_contexts_to_cap_action_map();
6235
+		if (isset($mapping[ $context ])) {
6236
+			return $mapping[ $context ];
6237
+		}
6238
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6239
+			return $action;
6240
+		}
6241
+		throw new EE_Error(
6242
+			sprintf(
6243
+				esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6244
+				$context,
6245
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6246
+			)
6247
+		);
6248
+	}
6249
+
6250
+
6251
+
6252
+	/**
6253
+	 * Returns all the capability contexts which are valid when querying models
6254
+	 *
6255
+	 * @return array
6256
+	 */
6257
+	public static function valid_cap_contexts()
6258
+	{
6259
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6260
+			self::caps_read,
6261
+			self::caps_read_admin,
6262
+			self::caps_edit,
6263
+			self::caps_delete,
6264
+		));
6265
+	}
6266
+
6267
+
6268
+
6269
+	/**
6270
+	 * Returns all valid options for 'default_where_conditions'
6271
+	 *
6272
+	 * @return array
6273
+	 */
6274
+	public static function valid_default_where_conditions()
6275
+	{
6276
+		return array(
6277
+			EEM_Base::default_where_conditions_all,
6278
+			EEM_Base::default_where_conditions_this_only,
6279
+			EEM_Base::default_where_conditions_others_only,
6280
+			EEM_Base::default_where_conditions_minimum_all,
6281
+			EEM_Base::default_where_conditions_minimum_others,
6282
+			EEM_Base::default_where_conditions_none
6283
+		);
6284
+	}
6285
+
6286
+	// public static function default_where_conditions_full
6287
+	/**
6288
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6289
+	 *
6290
+	 * @param string $context
6291
+	 * @return bool
6292
+	 * @throws EE_Error
6293
+	 */
6294
+	public static function verify_is_valid_cap_context($context)
6295
+	{
6296
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6297
+		if (in_array($context, $valid_cap_contexts)) {
6298
+			return true;
6299
+		}
6300
+		throw new EE_Error(
6301
+			sprintf(
6302
+				esc_html__(
6303
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6304
+					'event_espresso'
6305
+				),
6306
+				$context,
6307
+				'EEM_Base',
6308
+				implode(',', $valid_cap_contexts)
6309
+			)
6310
+		);
6311
+	}
6312
+
6313
+
6314
+
6315
+	/**
6316
+	 * Clears all the models field caches. This is only useful when a sub-class
6317
+	 * might have added a field or something and these caches might be invalidated
6318
+	 */
6319
+	protected function _invalidate_field_caches()
6320
+	{
6321
+		$this->_cache_foreign_key_to_fields = array();
6322
+		$this->_cached_fields = null;
6323
+		$this->_cached_fields_non_db_only = null;
6324
+	}
6325
+
6326
+
6327
+
6328
+	/**
6329
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6330
+	 * (eg "and", "or", "not").
6331
+	 *
6332
+	 * @return array
6333
+	 */
6334
+	public function logic_query_param_keys()
6335
+	{
6336
+		return $this->_logic_query_param_keys;
6337
+	}
6338
+
6339
+
6340
+
6341
+	/**
6342
+	 * Determines whether or not the where query param array key is for a logic query param.
6343
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6344
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6345
+	 *
6346
+	 * @param $query_param_key
6347
+	 * @return bool
6348
+	 */
6349
+	public function is_logic_query_param_key($query_param_key)
6350
+	{
6351
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6352
+			if (
6353
+				$query_param_key === $logic_query_param_key
6354
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6355
+			) {
6356
+				return true;
6357
+			}
6358
+		}
6359
+		return false;
6360
+	}
6361
+
6362
+	/**
6363
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6364
+	 * @since 4.9.74.p
6365
+	 * @return boolean
6366
+	 */
6367
+	public function hasPassword()
6368
+	{
6369
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6370
+		if ($this->has_password_field === null) {
6371
+			$password_field = $this->getPasswordField();
6372
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6373
+		}
6374
+		return $this->has_password_field;
6375
+	}
6376
+
6377
+	/**
6378
+	 * Returns the password field on this model, if there is one
6379
+	 * @since 4.9.74.p
6380
+	 * @return EE_Password_Field|null
6381
+	 */
6382
+	public function getPasswordField()
6383
+	{
6384
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6385
+		// there's no need to search for it. If we don't know yet, then find out
6386
+		if ($this->has_password_field === null && $this->password_field === null) {
6387
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6388
+		}
6389
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6390
+		return $this->password_field;
6391
+	}
6392
+
6393
+
6394
+	/**
6395
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6396
+	 * @since 4.9.74.p
6397
+	 * @return EE_Model_Field_Base[]
6398
+	 * @throws EE_Error
6399
+	 */
6400
+	public function getPasswordProtectedFields()
6401
+	{
6402
+		$password_field = $this->getPasswordField();
6403
+		$fields = array();
6404
+		if ($password_field instanceof EE_Password_Field) {
6405
+			$field_names = $password_field->protectedFields();
6406
+			foreach ($field_names as $field_name) {
6407
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6408
+			}
6409
+		}
6410
+		return $fields;
6411
+	}
6412
+
6413
+
6414
+	/**
6415
+	 * Checks if the current user can perform the requested action on this model
6416
+	 * @since 4.9.74.p
6417
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6418
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6419
+	 * @return bool
6420
+	 * @throws EE_Error
6421
+	 * @throws InvalidArgumentException
6422
+	 * @throws InvalidDataTypeException
6423
+	 * @throws InvalidInterfaceException
6424
+	 * @throws ReflectionException
6425
+	 * @throws UnexpectedEntityException
6426
+	 */
6427
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6428
+	{
6429
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6430
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6431
+		}
6432
+		if (!is_array($model_obj_or_fields_n_values)) {
6433
+			throw new UnexpectedEntityException(
6434
+				$model_obj_or_fields_n_values,
6435
+				'EE_Base_Class',
6436
+				sprintf(
6437
+					esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6438
+					__FUNCTION__
6439
+				)
6440
+			);
6441
+		}
6442
+		return $this->exists(
6443
+			$this->alter_query_params_to_restrict_by_ID(
6444
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6445
+				array(
6446
+					'default_where_conditions' => 'none',
6447
+					'caps'                     => $cap_to_check,
6448
+				)
6449
+			)
6450
+		);
6451
+	}
6452
+
6453
+	/**
6454
+	 * Returns the query param where conditions key to the password affecting this model.
6455
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6456
+	 * @since 4.9.74.p
6457
+	 * @return null|string
6458
+	 * @throws EE_Error
6459
+	 * @throws InvalidArgumentException
6460
+	 * @throws InvalidDataTypeException
6461
+	 * @throws InvalidInterfaceException
6462
+	 * @throws ModelConfigurationException
6463
+	 * @throws ReflectionException
6464
+	 */
6465
+	public function modelChainAndPassword()
6466
+	{
6467
+		if ($this->model_chain_to_password === null) {
6468
+			throw new ModelConfigurationException(
6469
+				$this,
6470
+				esc_html_x(
6471
+				// @codingStandardsIgnoreStart
6472
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6473
+					// @codingStandardsIgnoreEnd
6474
+					'1: model name',
6475
+					'event_espresso'
6476
+				)
6477
+			);
6478
+		}
6479
+		if ($this->model_chain_to_password === '') {
6480
+			$model_with_password = $this;
6481
+		} else {
6482
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6483
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6484
+			} else {
6485
+				$last_model_in_chain = $this->model_chain_to_password;
6486
+			}
6487
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6488
+		}
6489
+
6490
+		$password_field = $model_with_password->getPasswordField();
6491
+		if ($password_field instanceof EE_Password_Field) {
6492
+			$password_field_name = $password_field->get_name();
6493
+		} else {
6494
+			throw new ModelConfigurationException(
6495
+				$this,
6496
+				sprintf(
6497
+					esc_html_x(
6498
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6499
+						'1: model name, 2: special string',
6500
+						'event_espresso'
6501
+					),
6502
+					$model_with_password->get_this_model_name(),
6503
+					$this->model_chain_to_password
6504
+				)
6505
+			);
6506
+		}
6507
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6508
+	}
6509
+
6510
+	/**
6511
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6512
+	 * or if this model itself has a password affecting access to some of its other fields.
6513
+	 * @since 4.9.74.p
6514
+	 * @return boolean
6515
+	 */
6516
+	public function restrictedByRelatedModelPassword()
6517
+	{
6518
+		return $this->model_chain_to_password !== null;
6519
+	}
6520 6520
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Transaction.model.php 2 patches
Indentation   +457 added lines, -457 removed lines patch added patch discarded remove patch
@@ -20,231 +20,231 @@  discard block
 block discarded – undo
20 20
 class EEM_Transaction extends EEM_Base
21 21
 {
22 22
 
23
-    // private instance of the Transaction object
24
-    protected static $_instance;
25
-
26
-    /**
27
-     * Status ID(STS_ID on esp_status table) to indicate the transaction is complete,
28
-     * but payment is pending. This is the state for transactions where payment is promised
29
-     * from an offline gateway.
30
-     */
31
-    //  const open_status_code = 'TPN';
32
-
33
-    /**
34
-     * Status ID(STS_ID on esp_status table) to indicate the transaction failed,
35
-     * either due to a technical reason (server or computer crash during registration),
36
-     *  or some other reason that prevent the collection of any useful contact information from any of the registrants
37
-     */
38
-    const failed_status_code = 'TFL';
39
-
40
-    /**
41
-     * Status ID(STS_ID on esp_status table) to indicate the transaction was abandoned,
42
-     * either due to a technical reason (server or computer crash during registration),
43
-     * or due to an abandoned cart after registrant chose not to complete the registration process
44
-     * HOWEVER...
45
-     * an abandoned TXN differs from a failed TXN in that it was able to capture contact information for at least one
46
-     * registrant
47
-     */
48
-    const abandoned_status_code = 'TAB';
49
-
50
-    /**
51
-     * Status ID(STS_ID on esp_status table) to indicate an incomplete transaction,
52
-     * meaning that monies are still owing: TXN_paid < TXN_total
53
-     */
54
-    const incomplete_status_code = 'TIN';
55
-
56
-    /**
57
-     * Status ID (STS_ID on esp_status table) to indicate a complete transaction.
58
-     * meaning that NO monies are owing: TXN_paid == TXN_total
59
-     */
60
-    const complete_status_code = 'TCM';
61
-
62
-    /**
63
-     *  Status ID(STS_ID on esp_status table) to indicate the transaction is overpaid.
64
-     *  This is the same as complete, but site admins actually owe clients the moneys!  TXN_paid > TXN_total
65
-     */
66
-    const overpaid_status_code = 'TOP';
67
-
68
-
69
-    /**
70
-     *    private constructor to prevent direct creation
71
-     *
72
-     * @Constructor
73
-     * @access protected
74
-     *
75
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
76
-     *                         incoming timezone data that gets saved). Note this just sends the timezone info to the
77
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
78
-     *                         timezone in the 'timezone_string' wp option)
79
-     *
80
-     * @throws EE_Error
81
-     */
82
-    protected function __construct($timezone)
83
-    {
84
-        $this->singular_item = esc_html__('Transaction', 'event_espresso');
85
-        $this->plural_item   = esc_html__('Transactions', 'event_espresso');
86
-
87
-        $this->_tables                 = [
88
-            'TransactionTable' => new EE_Primary_Table('esp_transaction', 'TXN_ID'),
89
-        ];
90
-        $this->_fields                 = [
91
-            'TransactionTable' => [
92
-                'TXN_ID'           => new EE_Primary_Key_Int_Field('TXN_ID', esc_html__('Transaction ID', 'event_espresso')),
93
-                'TXN_timestamp'    => new EE_Datetime_Field(
94
-                    'TXN_timestamp',
95
-                    esc_html__('date when transaction was created', 'event_espresso'),
96
-                    false,
97
-                    EE_Datetime_Field::now,
98
-                    $timezone
99
-                ),
100
-                'TXN_total'        => new EE_Money_Field(
101
-                    'TXN_total',
102
-                    esc_html__('Total value of Transaction', 'event_espresso'),
103
-                    false,
104
-                    0
105
-                ),
106
-                'TXN_paid'         => new EE_Money_Field(
107
-                    'TXN_paid',
108
-                    esc_html__('Amount paid towards transaction to date', 'event_espresso'),
109
-                    false,
110
-                    0
111
-                ),
112
-                'STS_ID'           => new EE_Foreign_Key_String_Field(
113
-                    'STS_ID',
114
-                    esc_html__('Status ID', 'event_espresso'),
115
-                    false,
116
-                    EEM_Transaction::failed_status_code,
117
-                    'Status'
118
-                ),
119
-                'TXN_session_data' => new EE_Serialized_Text_Field(
120
-                    'TXN_session_data',
121
-                    esc_html__('Serialized session data', 'event_espresso'),
122
-                    true,
123
-                    ''
124
-                ),
125
-                'TXN_hash_salt'    => new EE_Plain_Text_Field(
126
-                    'TXN_hash_salt',
127
-                    esc_html__('Transaction Hash Salt', 'event_espresso'),
128
-                    true,
129
-                    ''
130
-                ),
131
-                'PMD_ID'           => new EE_Foreign_Key_Int_Field(
132
-                    'PMD_ID',
133
-                    esc_html__("Last Used Payment Method", 'event_espresso'),
134
-                    true,
135
-                    null,
136
-                    'Payment_Method'
137
-                ),
138
-                'TXN_reg_steps'    => new EE_Serialized_Text_Field(
139
-                    'TXN_reg_steps',
140
-                    esc_html__('Registration Steps', 'event_espresso'),
141
-                    false,
142
-                    []
143
-                ),
144
-            ],
145
-        ];
146
-        $this->_model_relations        = [
147
-            'Registration'   => new EE_Has_Many_Relation(),
148
-            'Payment'        => new EE_Has_Many_Relation(),
149
-            'Status'         => new EE_Belongs_To_Relation(),
150
-            'Line_Item'      => new EE_Has_Many_Relation(false),
151
-            // you can delete a transaction without needing to delete its line items
152
-            'Payment_Method' => new EE_Belongs_To_Relation(),
153
-            'Message'        => new EE_Has_Many_Relation(),
154
-        ];
155
-        $this->_model_chain_to_wp_user = 'Registration.Event';
156
-        parent::__construct($timezone);
157
-    }
158
-
159
-
160
-    /**
161
-     *    txn_status_array
162
-     * get list of transaction statuses
163
-     *
164
-     * @access public
165
-     * @return array
166
-     */
167
-    public static function txn_status_array()
168
-    {
169
-        return apply_filters(
170
-            'FHEE__EEM_Transaction__txn_status_array',
171
-            [
172
-                EEM_Transaction::overpaid_status_code,
173
-                EEM_Transaction::complete_status_code,
174
-                EEM_Transaction::incomplete_status_code,
175
-                EEM_Transaction::abandoned_status_code,
176
-                EEM_Transaction::failed_status_code,
177
-            ]
178
-        );
179
-    }
180
-
181
-
182
-    /**
183
-     *        get the revenue per day  for the Transaction Admin page Reports Tab
184
-     *
185
-     * @access        public
186
-     *
187
-     * @param string $period
188
-     *
189
-     * @return stdClass[]
190
-     * @throws EE_Error
191
-     * @throws EE_Error
192
-     */
193
-    public function get_revenue_per_day_report($period = '-1 month')
194
-    {
195
-        $sql_date = $this->convert_datetime_for_query(
196
-            'TXN_timestamp',
197
-            date('Y-m-d H:i:s', strtotime($period)),
198
-            'Y-m-d H:i:s',
199
-            'UTC'
200
-        );
201
-
202
-        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'TXN_timestamp');
203
-
204
-        return $this->_get_all_wpdb_results(
205
-            [
206
-                [
207
-                    'TXN_timestamp' => ['>=', $sql_date],
208
-                ],
209
-                'group_by' => 'txnDate',
210
-                'order_by' => ['TXN_timestamp' => 'ASC'],
211
-            ],
212
-            OBJECT,
213
-            [
214
-                'txnDate' => ['DATE(' . $query_interval . ')', '%s'],
215
-                'revenue' => ['SUM(TransactionTable.TXN_paid)', '%d'],
216
-            ]
217
-        );
218
-    }
219
-
220
-
221
-    /**
222
-     *        get the revenue per event  for the Transaction Admin page Reports Tab
223
-     *
224
-     * @access        public
225
-     *
226
-     * @param string $period
227
-     *
228
-     * @return EE_Transaction[]
229
-     */
230
-    public function get_revenue_per_event_report($period = '-1 month')
231
-    {
232
-        global $wpdb;
233
-        $transaction_table          = $wpdb->prefix . 'esp_transaction';
234
-        $registration_table         = $wpdb->prefix . 'esp_registration';
235
-        $registration_payment_table = $wpdb->prefix . 'esp_registration_payment';
236
-        $event_table                = $wpdb->posts;
237
-        $payment_table              = $wpdb->prefix . 'esp_payment';
238
-        $sql_date                   = date('Y-m-d H:i:s', strtotime($period));
239
-        $approved_payment_status    = EEM_Payment::status_id_approved;
240
-        $extra_event_on_join        = '';
241
-        // exclude events not authored by user if permissions in effect
242
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
243
-            $extra_event_on_join = ' AND Event.post_author = ' . get_current_user_id();
244
-        }
245
-
246
-        return $wpdb->get_results(
247
-            "SELECT
23
+	// private instance of the Transaction object
24
+	protected static $_instance;
25
+
26
+	/**
27
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction is complete,
28
+	 * but payment is pending. This is the state for transactions where payment is promised
29
+	 * from an offline gateway.
30
+	 */
31
+	//  const open_status_code = 'TPN';
32
+
33
+	/**
34
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction failed,
35
+	 * either due to a technical reason (server or computer crash during registration),
36
+	 *  or some other reason that prevent the collection of any useful contact information from any of the registrants
37
+	 */
38
+	const failed_status_code = 'TFL';
39
+
40
+	/**
41
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction was abandoned,
42
+	 * either due to a technical reason (server or computer crash during registration),
43
+	 * or due to an abandoned cart after registrant chose not to complete the registration process
44
+	 * HOWEVER...
45
+	 * an abandoned TXN differs from a failed TXN in that it was able to capture contact information for at least one
46
+	 * registrant
47
+	 */
48
+	const abandoned_status_code = 'TAB';
49
+
50
+	/**
51
+	 * Status ID(STS_ID on esp_status table) to indicate an incomplete transaction,
52
+	 * meaning that monies are still owing: TXN_paid < TXN_total
53
+	 */
54
+	const incomplete_status_code = 'TIN';
55
+
56
+	/**
57
+	 * Status ID (STS_ID on esp_status table) to indicate a complete transaction.
58
+	 * meaning that NO monies are owing: TXN_paid == TXN_total
59
+	 */
60
+	const complete_status_code = 'TCM';
61
+
62
+	/**
63
+	 *  Status ID(STS_ID on esp_status table) to indicate the transaction is overpaid.
64
+	 *  This is the same as complete, but site admins actually owe clients the moneys!  TXN_paid > TXN_total
65
+	 */
66
+	const overpaid_status_code = 'TOP';
67
+
68
+
69
+	/**
70
+	 *    private constructor to prevent direct creation
71
+	 *
72
+	 * @Constructor
73
+	 * @access protected
74
+	 *
75
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
76
+	 *                         incoming timezone data that gets saved). Note this just sends the timezone info to the
77
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
78
+	 *                         timezone in the 'timezone_string' wp option)
79
+	 *
80
+	 * @throws EE_Error
81
+	 */
82
+	protected function __construct($timezone)
83
+	{
84
+		$this->singular_item = esc_html__('Transaction', 'event_espresso');
85
+		$this->plural_item   = esc_html__('Transactions', 'event_espresso');
86
+
87
+		$this->_tables                 = [
88
+			'TransactionTable' => new EE_Primary_Table('esp_transaction', 'TXN_ID'),
89
+		];
90
+		$this->_fields                 = [
91
+			'TransactionTable' => [
92
+				'TXN_ID'           => new EE_Primary_Key_Int_Field('TXN_ID', esc_html__('Transaction ID', 'event_espresso')),
93
+				'TXN_timestamp'    => new EE_Datetime_Field(
94
+					'TXN_timestamp',
95
+					esc_html__('date when transaction was created', 'event_espresso'),
96
+					false,
97
+					EE_Datetime_Field::now,
98
+					$timezone
99
+				),
100
+				'TXN_total'        => new EE_Money_Field(
101
+					'TXN_total',
102
+					esc_html__('Total value of Transaction', 'event_espresso'),
103
+					false,
104
+					0
105
+				),
106
+				'TXN_paid'         => new EE_Money_Field(
107
+					'TXN_paid',
108
+					esc_html__('Amount paid towards transaction to date', 'event_espresso'),
109
+					false,
110
+					0
111
+				),
112
+				'STS_ID'           => new EE_Foreign_Key_String_Field(
113
+					'STS_ID',
114
+					esc_html__('Status ID', 'event_espresso'),
115
+					false,
116
+					EEM_Transaction::failed_status_code,
117
+					'Status'
118
+				),
119
+				'TXN_session_data' => new EE_Serialized_Text_Field(
120
+					'TXN_session_data',
121
+					esc_html__('Serialized session data', 'event_espresso'),
122
+					true,
123
+					''
124
+				),
125
+				'TXN_hash_salt'    => new EE_Plain_Text_Field(
126
+					'TXN_hash_salt',
127
+					esc_html__('Transaction Hash Salt', 'event_espresso'),
128
+					true,
129
+					''
130
+				),
131
+				'PMD_ID'           => new EE_Foreign_Key_Int_Field(
132
+					'PMD_ID',
133
+					esc_html__("Last Used Payment Method", 'event_espresso'),
134
+					true,
135
+					null,
136
+					'Payment_Method'
137
+				),
138
+				'TXN_reg_steps'    => new EE_Serialized_Text_Field(
139
+					'TXN_reg_steps',
140
+					esc_html__('Registration Steps', 'event_espresso'),
141
+					false,
142
+					[]
143
+				),
144
+			],
145
+		];
146
+		$this->_model_relations        = [
147
+			'Registration'   => new EE_Has_Many_Relation(),
148
+			'Payment'        => new EE_Has_Many_Relation(),
149
+			'Status'         => new EE_Belongs_To_Relation(),
150
+			'Line_Item'      => new EE_Has_Many_Relation(false),
151
+			// you can delete a transaction without needing to delete its line items
152
+			'Payment_Method' => new EE_Belongs_To_Relation(),
153
+			'Message'        => new EE_Has_Many_Relation(),
154
+		];
155
+		$this->_model_chain_to_wp_user = 'Registration.Event';
156
+		parent::__construct($timezone);
157
+	}
158
+
159
+
160
+	/**
161
+	 *    txn_status_array
162
+	 * get list of transaction statuses
163
+	 *
164
+	 * @access public
165
+	 * @return array
166
+	 */
167
+	public static function txn_status_array()
168
+	{
169
+		return apply_filters(
170
+			'FHEE__EEM_Transaction__txn_status_array',
171
+			[
172
+				EEM_Transaction::overpaid_status_code,
173
+				EEM_Transaction::complete_status_code,
174
+				EEM_Transaction::incomplete_status_code,
175
+				EEM_Transaction::abandoned_status_code,
176
+				EEM_Transaction::failed_status_code,
177
+			]
178
+		);
179
+	}
180
+
181
+
182
+	/**
183
+	 *        get the revenue per day  for the Transaction Admin page Reports Tab
184
+	 *
185
+	 * @access        public
186
+	 *
187
+	 * @param string $period
188
+	 *
189
+	 * @return stdClass[]
190
+	 * @throws EE_Error
191
+	 * @throws EE_Error
192
+	 */
193
+	public function get_revenue_per_day_report($period = '-1 month')
194
+	{
195
+		$sql_date = $this->convert_datetime_for_query(
196
+			'TXN_timestamp',
197
+			date('Y-m-d H:i:s', strtotime($period)),
198
+			'Y-m-d H:i:s',
199
+			'UTC'
200
+		);
201
+
202
+		$query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'TXN_timestamp');
203
+
204
+		return $this->_get_all_wpdb_results(
205
+			[
206
+				[
207
+					'TXN_timestamp' => ['>=', $sql_date],
208
+				],
209
+				'group_by' => 'txnDate',
210
+				'order_by' => ['TXN_timestamp' => 'ASC'],
211
+			],
212
+			OBJECT,
213
+			[
214
+				'txnDate' => ['DATE(' . $query_interval . ')', '%s'],
215
+				'revenue' => ['SUM(TransactionTable.TXN_paid)', '%d'],
216
+			]
217
+		);
218
+	}
219
+
220
+
221
+	/**
222
+	 *        get the revenue per event  for the Transaction Admin page Reports Tab
223
+	 *
224
+	 * @access        public
225
+	 *
226
+	 * @param string $period
227
+	 *
228
+	 * @return EE_Transaction[]
229
+	 */
230
+	public function get_revenue_per_event_report($period = '-1 month')
231
+	{
232
+		global $wpdb;
233
+		$transaction_table          = $wpdb->prefix . 'esp_transaction';
234
+		$registration_table         = $wpdb->prefix . 'esp_registration';
235
+		$registration_payment_table = $wpdb->prefix . 'esp_registration_payment';
236
+		$event_table                = $wpdb->posts;
237
+		$payment_table              = $wpdb->prefix . 'esp_payment';
238
+		$sql_date                   = date('Y-m-d H:i:s', strtotime($period));
239
+		$approved_payment_status    = EEM_Payment::status_id_approved;
240
+		$extra_event_on_join        = '';
241
+		// exclude events not authored by user if permissions in effect
242
+		if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
243
+			$extra_event_on_join = ' AND Event.post_author = ' . get_current_user_id();
244
+		}
245
+
246
+		return $wpdb->get_results(
247
+			"SELECT
248 248
 			Transaction_Event.event_name AS event_name,
249 249
 			SUM(Transaction_Event.paid) AS revenue
250 250
 			FROM
@@ -272,236 +272,236 @@  discard block
 block discarded – undo
272 272
 					$extra_event_on_join
273 273
 				) AS Transaction_Event
274 274
 			GROUP BY event_name"
275
-        );
276
-    }
277
-
278
-
279
-    /**
280
-     * Gets the current transaction given the reg_url_link, or assumes the reg_url_link is in the
281
-     * request global variable. Either way, tries to find the current transaction (through
282
-     * the registration pointed to by reg_url_link), if not returns null
283
-     *
284
-     * @param string $reg_url_link
285
-     *
286
-     * @return EE_Transaction
287
-     * @throws EE_Error
288
-     */
289
-    public function get_transaction_from_reg_url_link($reg_url_link = '')
290
-    {
291
-        if (empty($reg_url_link)) {
292
-            $request      = LoaderFactory::getLoader()->getShared(RequestInterface::class);
293
-            $reg_url_link = $request->getRequestParam('e_reg_url_link');
294
-        }
295
-        return $this->get_one(
296
-            [
297
-                [
298
-                    'Registration.REG_url_link' => $reg_url_link,
299
-                ],
300
-            ]
301
-        );
302
-    }
303
-
304
-
305
-    /**
306
-     * Updates the provided EE_Transaction with all the applicable payments
307
-     * (or fetch the EE_Transaction from its ID)
308
-     *
309
-     * @param EE_Transaction|int $transaction_obj_or_id
310
-     * @param boolean            $save_txn whether or not to save the transaction during this function call
311
-     *
312
-     * @return array
313
-     * @throws EE_Error
314
-     * @throws ReflectionException
315
-     * @deprecated
316
-     *
317
-     */
318
-    public function update_based_on_payments($transaction_obj_or_id, $save_txn = true)
319
-    {
320
-        EE_Error::doing_it_wrong(
321
-            __CLASS__ . '::' . __FUNCTION__,
322
-            sprintf(
323
-                esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
324
-                'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
325
-            ),
326
-            '4.6.0'
327
-        );
328
-        /** @type EE_Transaction_Processor $transaction_processor */
329
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
330
-
331
-        return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
332
-            $this->ensure_is_obj($transaction_obj_or_id)
333
-        );
334
-    }
335
-
336
-
337
-    /**
338
-     * Deletes "junk" transactions that were probably added by bots. There might be TONS
339
-     * of these, so we are very careful to NOT select (which the models do even when deleting),
340
-     * and so we only use wpdb directly and only do minimal joins.
341
-     * Transactions are considered "junk" if they're failed for longer than a week.
342
-     * Also, there is an extra check for payments related to the transaction, because if a transaction has a payment on
343
-     * it, it's probably not junk (regardless of what status it has).
344
-     * The downside to this approach is that is addons are listening for object deletions
345
-     * on EEM_Base::delete() they won't be notified of this.  However, there is an action that plugins can hook into
346
-     * to catch these types of deletions.
347
-     *
348
-     * @return int
349
-     * @throws EE_Error
350
-     * @throws EE_Error
351
-     * @global WPDB $wpdb
352
-     */
353
-    public function delete_junk_transactions()
354
-    {
355
-        global $wpdb;
356
-        $deleted             = false;
357
-        $time_to_leave_alone = (int) apply_filters(
358
-            'FHEE__EEM_Transaction__delete_junk_transactions__time_to_leave_alone',
359
-            WEEK_IN_SECONDS
360
-        );
361
-
362
-
363
-        /**
364
-         * This allows code to filter the query arguments used for retrieving the transaction IDs to delete.
365
-         * Useful for plugins that want to exclude transactions matching certain query parameters.
366
-         * The query parameters should be in the format accepted by the EEM_Base model queries.
367
-         */
368
-        $ids_query = apply_filters(
369
-            'FHEE__EEM_Transaction__delete_junk_transactions__initial_query_args',
370
-            [
371
-                0          => [
372
-                    'STS_ID'         => EEM_Transaction::failed_status_code,
373
-                    'Payment.PAY_ID' => ['IS NULL'],
374
-                    'TXN_timestamp'  => ['<', time() - $time_to_leave_alone],
375
-                ],
376
-                'order_by' => ['TXN_timestamp' => 'ASC'],
377
-                'limit'    => 1000,
378
-            ],
379
-            $time_to_leave_alone
380
-        );
381
-
382
-
383
-        /**
384
-         * This filter is for when code needs to filter the list of transaction ids that represent transactions
385
-         * about to be deleted based on some other criteria that isn't easily done via the query args filter.
386
-         */
387
-        $txn_ids = apply_filters(
388
-            'FHEE__EEM_Transaction__delete_junk_transactions__transaction_ids_to_delete',
389
-            EEM_Transaction::instance()->get_col($ids_query, 'TXN_ID'),
390
-            $time_to_leave_alone
391
-        );
392
-        // now that we have the ids to delete
393
-        if (! empty($txn_ids) && is_array($txn_ids)) {
394
-            // first, make sure these TXN's are removed the "ee_locked_transactions" array
395
-            EEM_Transaction::unset_locked_transactions($txn_ids);
396
-
397
-            // Create IDs placeholder.
398
-            $placeholders = array_fill(0, count($txn_ids), '%d');
399
-
400
-            // Glue it together to use inside $wpdb->prepare.
401
-            $format = implode(', ', $placeholders);
402
-
403
-            // let's get deleting...
404
-            // We got the ids from the original query to get them FROM
405
-            // the db (which is sanitized) so no need to prepare them again.
406
-            $query   = $wpdb->prepare("DELETE FROM " . $this->table() . " WHERE TXN_ID IN ( $format )", $txn_ids);
407
-            $deleted = $wpdb->query($query);
408
-        }
409
-        if ($deleted) {
410
-            /**
411
-             * Allows code to do something after the transactions have been deleted.
412
-             */
413
-            do_action('AHEE__EEM_Transaction__delete_junk_transactions__successful_deletion', $txn_ids);
414
-        }
415
-
416
-        return $deleted;
417
-    }
418
-
419
-
420
-    /**
421
-     * @param array $transaction_IDs
422
-     *
423
-     * @return bool
424
-     */
425
-    public static function unset_locked_transactions(array $transaction_IDs)
426
-    {
427
-        $locked_transactions = get_option('ee_locked_transactions', []);
428
-        $update              = false;
429
-        foreach ($transaction_IDs as $TXN_ID) {
430
-            if (isset($locked_transactions[ $TXN_ID ])) {
431
-                unset($locked_transactions[ $TXN_ID ]);
432
-                $update = true;
433
-            }
434
-        }
435
-        if ($update) {
436
-            update_option('ee_locked_transactions', $locked_transactions);
437
-        }
438
-
439
-        return $update;
440
-    }
441
-
442
-
443
-    /**
444
-     * returns an array of EE_Transaction objects whose timestamp is greater than
445
-     * the current time minus the session lifespan, which defaults to 60 minutes
446
-     *
447
-     * @return EE_Base_Class[]|EE_Transaction[]
448
-     * @throws EE_Error
449
-     * @throws InvalidArgumentException
450
-     * @throws InvalidDataTypeException
451
-     * @throws InvalidInterfaceException
452
-     */
453
-    public function get_transactions_in_progress()
454
-    {
455
-        return $this->_get_transactions_in_progress();
456
-    }
457
-
458
-
459
-    /**
460
-     * returns an array of EE_Transaction objects whose timestamp is less than
461
-     * the current time minus the session lifespan, which defaults to 60 minutes
462
-     *
463
-     * @return EE_Base_Class[]|EE_Transaction[]
464
-     * @throws EE_Error
465
-     * @throws InvalidArgumentException
466
-     * @throws InvalidDataTypeException
467
-     * @throws InvalidInterfaceException
468
-     */
469
-    public function get_transactions_not_in_progress()
470
-    {
471
-        return $this->_get_transactions_in_progress('<=');
472
-    }
473
-
474
-
475
-    /**
476
-     * @param string $comparison
477
-     * @return EE_Transaction[]
478
-     * @throws EE_Error
479
-     * @throws InvalidArgumentException
480
-     * @throws InvalidDataTypeException
481
-     * @throws InvalidInterfaceException
482
-     */
483
-    private function _get_transactions_in_progress($comparison = '>=')
484
-    {
485
-        $comparison = $comparison === '>=' || $comparison === '<='
486
-            ? $comparison
487
-            : '>=';
488
-        /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
489
-        $session_lifespan = LoaderFactory::getLoader()->getShared(
490
-            'EventEspresso\core\domain\values\session\SessionLifespan'
491
-        );
492
-        return $this->get_all(
493
-            [
494
-                [
495
-                    'TXN_timestamp' => [
496
-                        $comparison,
497
-                        $session_lifespan->expiration(),
498
-                    ],
499
-                    'STS_ID'        => [
500
-                        '!=',
501
-                        EEM_Transaction::complete_status_code,
502
-                    ],
503
-                ],
504
-            ]
505
-        );
506
-    }
275
+		);
276
+	}
277
+
278
+
279
+	/**
280
+	 * Gets the current transaction given the reg_url_link, or assumes the reg_url_link is in the
281
+	 * request global variable. Either way, tries to find the current transaction (through
282
+	 * the registration pointed to by reg_url_link), if not returns null
283
+	 *
284
+	 * @param string $reg_url_link
285
+	 *
286
+	 * @return EE_Transaction
287
+	 * @throws EE_Error
288
+	 */
289
+	public function get_transaction_from_reg_url_link($reg_url_link = '')
290
+	{
291
+		if (empty($reg_url_link)) {
292
+			$request      = LoaderFactory::getLoader()->getShared(RequestInterface::class);
293
+			$reg_url_link = $request->getRequestParam('e_reg_url_link');
294
+		}
295
+		return $this->get_one(
296
+			[
297
+				[
298
+					'Registration.REG_url_link' => $reg_url_link,
299
+				],
300
+			]
301
+		);
302
+	}
303
+
304
+
305
+	/**
306
+	 * Updates the provided EE_Transaction with all the applicable payments
307
+	 * (or fetch the EE_Transaction from its ID)
308
+	 *
309
+	 * @param EE_Transaction|int $transaction_obj_or_id
310
+	 * @param boolean            $save_txn whether or not to save the transaction during this function call
311
+	 *
312
+	 * @return array
313
+	 * @throws EE_Error
314
+	 * @throws ReflectionException
315
+	 * @deprecated
316
+	 *
317
+	 */
318
+	public function update_based_on_payments($transaction_obj_or_id, $save_txn = true)
319
+	{
320
+		EE_Error::doing_it_wrong(
321
+			__CLASS__ . '::' . __FUNCTION__,
322
+			sprintf(
323
+				esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
324
+				'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
325
+			),
326
+			'4.6.0'
327
+		);
328
+		/** @type EE_Transaction_Processor $transaction_processor */
329
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
330
+
331
+		return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
332
+			$this->ensure_is_obj($transaction_obj_or_id)
333
+		);
334
+	}
335
+
336
+
337
+	/**
338
+	 * Deletes "junk" transactions that were probably added by bots. There might be TONS
339
+	 * of these, so we are very careful to NOT select (which the models do even when deleting),
340
+	 * and so we only use wpdb directly and only do minimal joins.
341
+	 * Transactions are considered "junk" if they're failed for longer than a week.
342
+	 * Also, there is an extra check for payments related to the transaction, because if a transaction has a payment on
343
+	 * it, it's probably not junk (regardless of what status it has).
344
+	 * The downside to this approach is that is addons are listening for object deletions
345
+	 * on EEM_Base::delete() they won't be notified of this.  However, there is an action that plugins can hook into
346
+	 * to catch these types of deletions.
347
+	 *
348
+	 * @return int
349
+	 * @throws EE_Error
350
+	 * @throws EE_Error
351
+	 * @global WPDB $wpdb
352
+	 */
353
+	public function delete_junk_transactions()
354
+	{
355
+		global $wpdb;
356
+		$deleted             = false;
357
+		$time_to_leave_alone = (int) apply_filters(
358
+			'FHEE__EEM_Transaction__delete_junk_transactions__time_to_leave_alone',
359
+			WEEK_IN_SECONDS
360
+		);
361
+
362
+
363
+		/**
364
+		 * This allows code to filter the query arguments used for retrieving the transaction IDs to delete.
365
+		 * Useful for plugins that want to exclude transactions matching certain query parameters.
366
+		 * The query parameters should be in the format accepted by the EEM_Base model queries.
367
+		 */
368
+		$ids_query = apply_filters(
369
+			'FHEE__EEM_Transaction__delete_junk_transactions__initial_query_args',
370
+			[
371
+				0          => [
372
+					'STS_ID'         => EEM_Transaction::failed_status_code,
373
+					'Payment.PAY_ID' => ['IS NULL'],
374
+					'TXN_timestamp'  => ['<', time() - $time_to_leave_alone],
375
+				],
376
+				'order_by' => ['TXN_timestamp' => 'ASC'],
377
+				'limit'    => 1000,
378
+			],
379
+			$time_to_leave_alone
380
+		);
381
+
382
+
383
+		/**
384
+		 * This filter is for when code needs to filter the list of transaction ids that represent transactions
385
+		 * about to be deleted based on some other criteria that isn't easily done via the query args filter.
386
+		 */
387
+		$txn_ids = apply_filters(
388
+			'FHEE__EEM_Transaction__delete_junk_transactions__transaction_ids_to_delete',
389
+			EEM_Transaction::instance()->get_col($ids_query, 'TXN_ID'),
390
+			$time_to_leave_alone
391
+		);
392
+		// now that we have the ids to delete
393
+		if (! empty($txn_ids) && is_array($txn_ids)) {
394
+			// first, make sure these TXN's are removed the "ee_locked_transactions" array
395
+			EEM_Transaction::unset_locked_transactions($txn_ids);
396
+
397
+			// Create IDs placeholder.
398
+			$placeholders = array_fill(0, count($txn_ids), '%d');
399
+
400
+			// Glue it together to use inside $wpdb->prepare.
401
+			$format = implode(', ', $placeholders);
402
+
403
+			// let's get deleting...
404
+			// We got the ids from the original query to get them FROM
405
+			// the db (which is sanitized) so no need to prepare them again.
406
+			$query   = $wpdb->prepare("DELETE FROM " . $this->table() . " WHERE TXN_ID IN ( $format )", $txn_ids);
407
+			$deleted = $wpdb->query($query);
408
+		}
409
+		if ($deleted) {
410
+			/**
411
+			 * Allows code to do something after the transactions have been deleted.
412
+			 */
413
+			do_action('AHEE__EEM_Transaction__delete_junk_transactions__successful_deletion', $txn_ids);
414
+		}
415
+
416
+		return $deleted;
417
+	}
418
+
419
+
420
+	/**
421
+	 * @param array $transaction_IDs
422
+	 *
423
+	 * @return bool
424
+	 */
425
+	public static function unset_locked_transactions(array $transaction_IDs)
426
+	{
427
+		$locked_transactions = get_option('ee_locked_transactions', []);
428
+		$update              = false;
429
+		foreach ($transaction_IDs as $TXN_ID) {
430
+			if (isset($locked_transactions[ $TXN_ID ])) {
431
+				unset($locked_transactions[ $TXN_ID ]);
432
+				$update = true;
433
+			}
434
+		}
435
+		if ($update) {
436
+			update_option('ee_locked_transactions', $locked_transactions);
437
+		}
438
+
439
+		return $update;
440
+	}
441
+
442
+
443
+	/**
444
+	 * returns an array of EE_Transaction objects whose timestamp is greater than
445
+	 * the current time minus the session lifespan, which defaults to 60 minutes
446
+	 *
447
+	 * @return EE_Base_Class[]|EE_Transaction[]
448
+	 * @throws EE_Error
449
+	 * @throws InvalidArgumentException
450
+	 * @throws InvalidDataTypeException
451
+	 * @throws InvalidInterfaceException
452
+	 */
453
+	public function get_transactions_in_progress()
454
+	{
455
+		return $this->_get_transactions_in_progress();
456
+	}
457
+
458
+
459
+	/**
460
+	 * returns an array of EE_Transaction objects whose timestamp is less than
461
+	 * the current time minus the session lifespan, which defaults to 60 minutes
462
+	 *
463
+	 * @return EE_Base_Class[]|EE_Transaction[]
464
+	 * @throws EE_Error
465
+	 * @throws InvalidArgumentException
466
+	 * @throws InvalidDataTypeException
467
+	 * @throws InvalidInterfaceException
468
+	 */
469
+	public function get_transactions_not_in_progress()
470
+	{
471
+		return $this->_get_transactions_in_progress('<=');
472
+	}
473
+
474
+
475
+	/**
476
+	 * @param string $comparison
477
+	 * @return EE_Transaction[]
478
+	 * @throws EE_Error
479
+	 * @throws InvalidArgumentException
480
+	 * @throws InvalidDataTypeException
481
+	 * @throws InvalidInterfaceException
482
+	 */
483
+	private function _get_transactions_in_progress($comparison = '>=')
484
+	{
485
+		$comparison = $comparison === '>=' || $comparison === '<='
486
+			? $comparison
487
+			: '>=';
488
+		/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
489
+		$session_lifespan = LoaderFactory::getLoader()->getShared(
490
+			'EventEspresso\core\domain\values\session\SessionLifespan'
491
+		);
492
+		return $this->get_all(
493
+			[
494
+				[
495
+					'TXN_timestamp' => [
496
+						$comparison,
497
+						$session_lifespan->expiration(),
498
+					],
499
+					'STS_ID'        => [
500
+						'!=',
501
+						EEM_Transaction::complete_status_code,
502
+					],
503
+				],
504
+			]
505
+		);
506
+	}
507 507
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
                 ),
144 144
             ],
145 145
         ];
146
-        $this->_model_relations        = [
146
+        $this->_model_relations = [
147 147
             'Registration'   => new EE_Has_Many_Relation(),
148 148
             'Payment'        => new EE_Has_Many_Relation(),
149 149
             'Status'         => new EE_Belongs_To_Relation(),
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
             ],
212 212
             OBJECT,
213 213
             [
214
-                'txnDate' => ['DATE(' . $query_interval . ')', '%s'],
214
+                'txnDate' => ['DATE('.$query_interval.')', '%s'],
215 215
                 'revenue' => ['SUM(TransactionTable.TXN_paid)', '%d'],
216 216
             ]
217 217
         );
@@ -230,17 +230,17 @@  discard block
 block discarded – undo
230 230
     public function get_revenue_per_event_report($period = '-1 month')
231 231
     {
232 232
         global $wpdb;
233
-        $transaction_table          = $wpdb->prefix . 'esp_transaction';
234
-        $registration_table         = $wpdb->prefix . 'esp_registration';
235
-        $registration_payment_table = $wpdb->prefix . 'esp_registration_payment';
233
+        $transaction_table          = $wpdb->prefix.'esp_transaction';
234
+        $registration_table         = $wpdb->prefix.'esp_registration';
235
+        $registration_payment_table = $wpdb->prefix.'esp_registration_payment';
236 236
         $event_table                = $wpdb->posts;
237
-        $payment_table              = $wpdb->prefix . 'esp_payment';
237
+        $payment_table              = $wpdb->prefix.'esp_payment';
238 238
         $sql_date                   = date('Y-m-d H:i:s', strtotime($period));
239 239
         $approved_payment_status    = EEM_Payment::status_id_approved;
240 240
         $extra_event_on_join        = '';
241 241
         // exclude events not authored by user if permissions in effect
242
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
243
-            $extra_event_on_join = ' AND Event.post_author = ' . get_current_user_id();
242
+        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
243
+            $extra_event_on_join = ' AND Event.post_author = '.get_current_user_id();
244 244
         }
245 245
 
246 246
         return $wpdb->get_results(
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
     public function update_based_on_payments($transaction_obj_or_id, $save_txn = true)
319 319
     {
320 320
         EE_Error::doing_it_wrong(
321
-            __CLASS__ . '::' . __FUNCTION__,
321
+            __CLASS__.'::'.__FUNCTION__,
322 322
             sprintf(
323 323
                 esc_html__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
324 324
                 'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
             $time_to_leave_alone
391 391
         );
392 392
         // now that we have the ids to delete
393
-        if (! empty($txn_ids) && is_array($txn_ids)) {
393
+        if ( ! empty($txn_ids) && is_array($txn_ids)) {
394 394
             // first, make sure these TXN's are removed the "ee_locked_transactions" array
395 395
             EEM_Transaction::unset_locked_transactions($txn_ids);
396 396
 
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
             // let's get deleting...
404 404
             // We got the ids from the original query to get them FROM
405 405
             // the db (which is sanitized) so no need to prepare them again.
406
-            $query   = $wpdb->prepare("DELETE FROM " . $this->table() . " WHERE TXN_ID IN ( $format )", $txn_ids);
406
+            $query   = $wpdb->prepare("DELETE FROM ".$this->table()." WHERE TXN_ID IN ( $format )", $txn_ids);
407 407
             $deleted = $wpdb->query($query);
408 408
         }
409 409
         if ($deleted) {
@@ -427,8 +427,8 @@  discard block
 block discarded – undo
427 427
         $locked_transactions = get_option('ee_locked_transactions', []);
428 428
         $update              = false;
429 429
         foreach ($transaction_IDs as $TXN_ID) {
430
-            if (isset($locked_transactions[ $TXN_ID ])) {
431
-                unset($locked_transactions[ $TXN_ID ]);
430
+            if (isset($locked_transactions[$TXN_ID])) {
431
+                unset($locked_transactions[$TXN_ID]);
432 432
                 $update = true;
433 433
             }
434 434
         }
Please login to merge, or discard this patch.
core/db_models/EEM_Extra_Join.model.php 1 patch
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -23,32 +23,32 @@
 block discarded – undo
23 23
  */
24 24
 class EEM_Extra_Join extends EEM_Base
25 25
 {
26
-    // private instance of the Extra Join object
27
-    protected static $_instance = null;
26
+	// private instance of the Extra Join object
27
+	protected static $_instance = null;
28 28
 
29
-    public function __construct($timezone = null)
30
-    {
31
-        $models_this_can_join = array_keys(EE_Registry::instance()->non_abstract_db_models);
32
-        $this->_tables = array(
33
-            'Extra_Join' => new EE_Primary_Table('esp_extra_join', 'EXJ_ID'),
34
-        );
35
-        $this->_fields = array(
36
-            'Extra_Join' => array(
37
-                'EXJ_ID' => new EE_Primary_Key_Int_Field('EXJ_ID', esc_html__('Extra Join ID', 'event_espresso')),
38
-                'EXJ_first_model_ID' => new EE_Foreign_Key_String_Field('EXJ_first_model_ID', esc_html__('First Model ID', 'event_espresso'), true, 0, $models_this_can_join),
39
-                'EXJ_first_model_name' => new EE_Any_Foreign_Model_Name_Field('EXJ_first_model_name', esc_html__('First Model Name', 'event_espresso'), true, '', $models_this_can_join),
40
-                'EXJ_second_model_ID' => new EE_Foreign_Key_String_Field('EXJ_second_model_ID', esc_html__('Second Model ID', 'event_espresso'), true, 0, $models_this_can_join),
41
-                'EXJ_second_model_name' => new EE_Any_Foreign_Model_Name_Field('EXJ_second_model_name', esc_html__('Second Model Name', 'event_espresso'), true, '', $models_this_can_join),
29
+	public function __construct($timezone = null)
30
+	{
31
+		$models_this_can_join = array_keys(EE_Registry::instance()->non_abstract_db_models);
32
+		$this->_tables = array(
33
+			'Extra_Join' => new EE_Primary_Table('esp_extra_join', 'EXJ_ID'),
34
+		);
35
+		$this->_fields = array(
36
+			'Extra_Join' => array(
37
+				'EXJ_ID' => new EE_Primary_Key_Int_Field('EXJ_ID', esc_html__('Extra Join ID', 'event_espresso')),
38
+				'EXJ_first_model_ID' => new EE_Foreign_Key_String_Field('EXJ_first_model_ID', esc_html__('First Model ID', 'event_espresso'), true, 0, $models_this_can_join),
39
+				'EXJ_first_model_name' => new EE_Any_Foreign_Model_Name_Field('EXJ_first_model_name', esc_html__('First Model Name', 'event_espresso'), true, '', $models_this_can_join),
40
+				'EXJ_second_model_ID' => new EE_Foreign_Key_String_Field('EXJ_second_model_ID', esc_html__('Second Model ID', 'event_espresso'), true, 0, $models_this_can_join),
41
+				'EXJ_second_model_name' => new EE_Any_Foreign_Model_Name_Field('EXJ_second_model_name', esc_html__('Second Model Name', 'event_espresso'), true, '', $models_this_can_join),
42 42
 
43
-            )
44
-        );
45
-        // this model is weird in that it has two foreign key columns which can point to any model/table.
46
-        // eg a foreign key to event will be in "EXJ_first_model_ID", provided the other
47
-        // model linked to is alphabetically greater than event (eg venue).
48
-        // but if the model linked to is alphabetically lower (eg attendee),
49
-        // the foreign key to the event will be in "EXJ_second_model_ID"
50
-        // so normal usage of foreign keys is weird. So don't define any
51
-        // relations to other models because they won't work properly with this model
52
-        parent::__construct($timezone);
53
-    }
43
+			)
44
+		);
45
+		// this model is weird in that it has two foreign key columns which can point to any model/table.
46
+		// eg a foreign key to event will be in "EXJ_first_model_ID", provided the other
47
+		// model linked to is alphabetically greater than event (eg venue).
48
+		// but if the model linked to is alphabetically lower (eg attendee),
49
+		// the foreign key to the event will be in "EXJ_second_model_ID"
50
+		// so normal usage of foreign keys is weird. So don't define any
51
+		// relations to other models because they won't work properly with this model
52
+		parent::__construct($timezone);
53
+	}
54 54
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Registration_Payment.model.php 2 patches
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -13,34 +13,34 @@
 block discarded – undo
13 13
 class EEM_Registration_Payment extends EEM_Base
14 14
 {
15 15
 
16
-    // private instance
17
-    protected static $_instance = null;
16
+	// private instance
17
+	protected static $_instance = null;
18 18
 
19 19
 
20
-    protected function __construct($timezone = null)
21
-    {
20
+	protected function __construct($timezone = null)
21
+	{
22 22
 
23
-        $this->singular_item = esc_html__('Registration Payment', 'event_espresso');
24
-        $this->plural_item  = esc_html__('Registration Payments', 'event_espresso');
23
+		$this->singular_item = esc_html__('Registration Payment', 'event_espresso');
24
+		$this->plural_item  = esc_html__('Registration Payments', 'event_espresso');
25 25
 
26
-        $this->_tables = array(
27
-            'Registration_Payment' => new EE_Primary_Table('esp_registration_payment', 'RPY_ID')
28
-        );
26
+		$this->_tables = array(
27
+			'Registration_Payment' => new EE_Primary_Table('esp_registration_payment', 'RPY_ID')
28
+		);
29 29
 
30
-        $this->_fields = array(
31
-            'Registration_Payment' => array(
32
-                'RPY_ID'                => new EE_Primary_Key_Int_Field('RPY_ID', esc_html__('Registration Payment ID', 'event_espresso')),
33
-                'REG_ID'                => new EE_Foreign_Key_Int_Field('REG_ID', esc_html__('Registration ID', 'event_espresso'), false, 0, 'Registration'),
34
-                'PAY_ID'                => new EE_Foreign_Key_Int_Field('PAY_ID', esc_html__('Payment ID', 'event_espresso'), true, null, 'Payment'),
35
-                'RPY_amount'    => new EE_Money_Field('RPY_amount', esc_html__('Amount attributed to the registration', 'event_espresso'), false, 0),
36
-            )
37
-        );
30
+		$this->_fields = array(
31
+			'Registration_Payment' => array(
32
+				'RPY_ID'                => new EE_Primary_Key_Int_Field('RPY_ID', esc_html__('Registration Payment ID', 'event_espresso')),
33
+				'REG_ID'                => new EE_Foreign_Key_Int_Field('REG_ID', esc_html__('Registration ID', 'event_espresso'), false, 0, 'Registration'),
34
+				'PAY_ID'                => new EE_Foreign_Key_Int_Field('PAY_ID', esc_html__('Payment ID', 'event_espresso'), true, null, 'Payment'),
35
+				'RPY_amount'    => new EE_Money_Field('RPY_amount', esc_html__('Amount attributed to the registration', 'event_espresso'), false, 0),
36
+			)
37
+		);
38 38
 
39
-        $this->_model_relations = array(
40
-            'Registration'  => new EE_Belongs_To_Relation(),
41
-            'Payment'       => new EE_Belongs_To_Relation(),
42
-        );
39
+		$this->_model_relations = array(
40
+			'Registration'  => new EE_Belongs_To_Relation(),
41
+			'Payment'       => new EE_Belongs_To_Relation(),
42
+		);
43 43
 
44
-        parent::__construct($timezone);
45
-    }
44
+		parent::__construct($timezone);
45
+	}
46 46
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@
 block discarded – undo
21 21
     {
22 22
 
23 23
         $this->singular_item = esc_html__('Registration Payment', 'event_espresso');
24
-        $this->plural_item  = esc_html__('Registration Payments', 'event_espresso');
24
+        $this->plural_item = esc_html__('Registration Payments', 'event_espresso');
25 25
 
26 26
         $this->_tables = array(
27 27
             'Registration_Payment' => new EE_Primary_Table('esp_registration_payment', 'RPY_ID')
Please login to merge, or discard this patch.
core/db_models/EEM_CPT_Base.model.php 2 patches
Indentation   +561 added lines, -561 removed lines patch added patch discarded remove patch
@@ -15,565 +15,565 @@
 block discarded – undo
15 15
 abstract class EEM_CPT_Base extends EEM_Soft_Delete_Base
16 16
 {
17 17
 
18
-    const EVENT_CATEGORY_TAXONOMY = 'espresso_event_categories';
19
-
20
-    /**
21
-     * @var string post_status_publish - the wp post status for published cpts
22
-     */
23
-    const post_status_publish = 'publish';
24
-
25
-    /**
26
-     * @var string post_status_future - the wp post status for scheduled cpts
27
-     */
28
-    const post_status_future = 'future';
29
-
30
-    /**
31
-     * @var string post_status_draft - the wp post status for draft cpts
32
-     */
33
-    const post_status_draft = 'draft';
34
-
35
-    /**
36
-     * @var string post_status_pending - the wp post status for pending cpts
37
-     */
38
-    const post_status_pending = 'pending';
39
-
40
-    /**
41
-     * @var string post_status_private - the wp post status for private cpts
42
-     */
43
-    const post_status_private = 'private';
44
-
45
-    /**
46
-     * @var string post_status_trashed - the wp post status for trashed cpts
47
-     */
48
-    const post_status_trashed = 'trash';
49
-
50
-    /**
51
-     * This is an array of custom statuses for the given CPT model (modified by children)
52
-     * format:
53
-     * array(
54
-     *        'status_name' => array(
55
-     *            'label' => esc_html__('Status Name', 'event_espresso'),
56
-     *            'public' => TRUE //whether a public status or not.
57
-     *        )
58
-     * )
59
-     *
60
-     * @var array
61
-     */
62
-    protected $_custom_stati = array();
63
-
64
-
65
-    /**
66
-     * Adds a relationship to Term_Taxonomy for each CPT_Base
67
-     *
68
-     * @param string $timezone
69
-     * @throws \EE_Error
70
-     */
71
-    protected function __construct($timezone = null)
72
-    {
73
-        // adds a relationship to Term_Taxonomy for all these models. For this to work
74
-        // Term_Relationship must have a relation to each model subclassing EE_CPT_Base explicitly
75
-        // eg, in EEM_Term_Relationship, inside the _model_relations array, there must be an entry
76
-        // with key equalling the subclassing model's model name (eg 'Event' or 'Venue'), and the value
77
-        // must also be new EE_HABTM_Relation('Term_Relationship');
78
-        $this->_model_relations['Term_Taxonomy'] = new EE_HABTM_Relation('Term_Relationship');
79
-        $primary_table_name = null;
80
-        // add  the common _status field to all CPT primary tables.
81
-        foreach ($this->_tables as $alias => $table_obj) {
82
-            if ($table_obj instanceof EE_Primary_Table) {
83
-                $primary_table_name = $alias;
84
-            }
85
-        }
86
-        // set default wp post statuses if child has not already set.
87
-        if (! isset($this->_fields[ $primary_table_name ]['status'])) {
88
-            $this->_fields[ $primary_table_name ]['status'] = new EE_WP_Post_Status_Field(
89
-                'post_status',
90
-                esc_html__("Event Status", "event_espresso"),
91
-                false,
92
-                'draft'
93
-            );
94
-        }
95
-        if (! isset($this->_fields[ $primary_table_name ]['to_ping'])) {
96
-            $this->_fields[ $primary_table_name ]['to_ping'] = new EE_DB_Only_Text_Field(
97
-                'to_ping',
98
-                esc_html__('To Ping', 'event_espresso'),
99
-                false,
100
-                ''
101
-            );
102
-        }
103
-        if (! isset($this->_fields[ $primary_table_name ]['pinged'])) {
104
-            $this->_fields[ $primary_table_name ]['pinged'] = new EE_DB_Only_Text_Field(
105
-                'pinged',
106
-                esc_html__('Pinged', 'event_espresso'),
107
-                false,
108
-                ''
109
-            );
110
-        }
111
-        if (! isset($this->_fields[ $primary_table_name ]['comment_status'])) {
112
-            $this->_fields[ $primary_table_name ]['comment_status'] = new EE_Plain_Text_Field(
113
-                'comment_status',
114
-                esc_html__('Comment Status', 'event_espresso'),
115
-                false,
116
-                'open'
117
-            );
118
-        }
119
-        if (! isset($this->_fields[ $primary_table_name ]['ping_status'])) {
120
-            $this->_fields[ $primary_table_name ]['ping_status'] = new EE_Plain_Text_Field(
121
-                'ping_status',
122
-                esc_html__('Ping Status', 'event_espresso'),
123
-                false,
124
-                'open'
125
-            );
126
-        }
127
-        if (! isset($this->_fields[ $primary_table_name ]['post_content_filtered'])) {
128
-            $this->_fields[ $primary_table_name ]['post_content_filtered'] = new EE_DB_Only_Text_Field(
129
-                'post_content_filtered',
130
-                esc_html__('Post Content Filtered', 'event_espresso'),
131
-                false,
132
-                ''
133
-            );
134
-        }
135
-        if (! isset($this->_model_relations['Post_Meta'])) {
136
-            // don't block deletes though because we want to maintain the current behaviour
137
-            $this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
138
-        }
139
-        if (! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
140
-            // nothing was set during child constructor, so set default
141
-            $this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
142
-        }
143
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
144
-            // nothing was set during child constructor, so set default
145
-            // it's ok for child classes to specify this, but generally this is more DRY
146
-            $this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
147
-        }
148
-        parent::__construct($timezone);
149
-    }
150
-
151
-
152
-    /**
153
-     * @return array
154
-     */
155
-    public function public_event_stati()
156
-    {
157
-        // @see wp-includes/post.php
158
-        return get_post_stati(array('public' => true));
159
-    }
160
-
161
-
162
-    /**
163
-     * Searches for field on this model of type 'deleted_flag'. if it is found,
164
-     * returns it's name. BUT That doesn't apply to CPTs. We should instead use post_status_field_name
165
-     *
166
-     * @return string
167
-     * @throws EE_Error
168
-     */
169
-    public function deleted_field_name()
170
-    {
171
-        throw new EE_Error(
172
-            sprintf(
173
-                esc_html__(
174
-                    "EEM_CPT_Base should nto call deleted_field_name! It should instead use post_status_field_name",
175
-                    "event_espresso"
176
-                )
177
-            )
178
-        );
179
-    }
180
-
181
-
182
-    /**
183
-     * Gets the field's name that sets the post status
184
-     *
185
-     * @return string
186
-     * @throws EE_Error
187
-     */
188
-    public function post_status_field_name()
189
-    {
190
-        $field = $this->get_a_field_of_type('EE_WP_Post_Status_Field');
191
-        if ($field) {
192
-            return $field->get_name();
193
-        } else {
194
-            throw new EE_Error(
195
-                sprintf(
196
-                    esc_html__(
197
-                        'We are trying to find the post status flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
198
-                        'event_espresso'
199
-                    ),
200
-                    get_class($this),
201
-                    get_class($this)
202
-                )
203
-            );
204
-        }
205
-    }
206
-
207
-
208
-    /**
209
-     * Alters the query params so that only trashed/soft-deleted items are considered
210
-     *
211
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
212
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
213
-     */
214
-    protected function _alter_query_params_so_only_trashed_items_included($query_params)
215
-    {
216
-        $post_status_field_name = $this->post_status_field_name();
217
-        $query_params[0][ $post_status_field_name ] = self::post_status_trashed;
218
-        return $query_params;
219
-    }
220
-
221
-
222
-    /**
223
-     * Alters the query params so each item's deleted status is ignored.
224
-     *
225
-     * @param array $query_params
226
-     * @return array
227
-     */
228
-    protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
229
-    {
230
-        $query_params['default_where_conditions'] = 'minimum';
231
-        return $query_params;
232
-    }
233
-
234
-
235
-    /**
236
-     * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
237
-     *
238
-     * @param boolean $delete       true to indicate deletion, false to indicate restoration
239
-     * @param array   $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
240
-     * @return boolean success
241
-     */
242
-    public function delete_or_restore($delete = true, $query_params = array())
243
-    {
244
-        $post_status_field_name = $this->post_status_field_name();
245
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
246
-        $new_status = $delete ? self::post_status_trashed : 'draft';
247
-        if ($this->update(array($post_status_field_name => $new_status), $query_params)) {
248
-            return true;
249
-        } else {
250
-            return false;
251
-        }
252
-    }
253
-
254
-
255
-    /**
256
-     * meta_table
257
-     * returns first EE_Secondary_Table table name
258
-     *
259
-     * @access public
260
-     * @return string
261
-     */
262
-    public function meta_table()
263
-    {
264
-        $meta_table = $this->_get_other_tables();
265
-        $meta_table = reset($meta_table);
266
-        return $meta_table instanceof EE_Secondary_Table ? $meta_table->get_table_name() : null;
267
-    }
268
-
269
-
270
-    /**
271
-     * This simply returns an array of the meta table fields (useful for when we just need to update those fields)
272
-     *
273
-     * @param  bool $all triggers whether we include DB_Only fields or JUST non DB_Only fields.  Defaults to false (no
274
-     *                   db only fields)
275
-     * @return array
276
-     */
277
-    public function get_meta_table_fields($all = false)
278
-    {
279
-        $all_fields = $fields_to_return = array();
280
-        foreach ($this->_tables as $alias => $table_obj) {
281
-            if ($table_obj instanceof EE_Secondary_Table) {
282
-                $all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
283
-            }
284
-        }
285
-        if (! $all) {
286
-            foreach ($all_fields as $name => $obj) {
287
-                if ($obj instanceof EE_DB_Only_Field_Base) {
288
-                    continue;
289
-                }
290
-                $fields_to_return[] = $name;
291
-            }
292
-        } else {
293
-            $fields_to_return = array_keys($all_fields);
294
-        }
295
-        return $fields_to_return;
296
-    }
297
-
298
-
299
-    /**
300
-     * Adds an event category with the specified name and description to the specified
301
-     * $cpt_model_object. Intelligently adds a term if necessary, and adds a term_taxonomy if necessary,
302
-     * and adds an entry in the term_relationship if necessary.
303
-     *
304
-     * @param EE_CPT_Base $cpt_model_object
305
-     * @param string      $category_name (used to derive the term slug too)
306
-     * @param string      $category_description
307
-     * @param int         $parent_term_taxonomy_id
308
-     * @return EE_Term_Taxonomy
309
-     */
310
-    public function add_event_category(
311
-        EE_CPT_Base $cpt_model_object,
312
-        $category_name,
313
-        $category_description = '',
314
-        $parent_term_taxonomy_id = null
315
-    ) {
316
-        // create term
317
-        require_once(EE_MODELS . 'EEM_Term.model.php');
318
-        // first, check for a term by the same name or slug
319
-        $category_slug = sanitize_title($category_name);
320
-        $term = EEM_Term::instance()->get_one(
321
-            array(
322
-                array(
323
-                    'OR' => array(
324
-                        'name' => $category_name,
325
-                        'slug' => $category_slug,
326
-                    ),
327
-                    'Term_Taxonomy.taxonomy' => self::EVENT_CATEGORY_TAXONOMY
328
-                ),
329
-            )
330
-        );
331
-        if (! $term) {
332
-            $term = EE_Term::new_instance(
333
-                array(
334
-                    'name' => $category_name,
335
-                    'slug' => $category_slug,
336
-                )
337
-            );
338
-            $term->save();
339
-        }
340
-        // make sure there's a term-taxonomy entry too
341
-        require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
342
-        $term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(
343
-            array(
344
-                array(
345
-                    'term_id'  => $term->ID(),
346
-                    'taxonomy' => self::EVENT_CATEGORY_TAXONOMY,
347
-                ),
348
-            )
349
-        );
350
-        /** @var $term_taxonomy EE_Term_Taxonomy */
351
-        if (! $term_taxonomy) {
352
-            $term_taxonomy = EE_Term_Taxonomy::new_instance(
353
-                array(
354
-                    'term_id'     => $term->ID(),
355
-                    'taxonomy'    => self::EVENT_CATEGORY_TAXONOMY,
356
-                    'description' => $category_description,
357
-                    'term_count'       => 1,
358
-                    'parent'      => $parent_term_taxonomy_id,
359
-                )
360
-            );
361
-            $term_taxonomy->save();
362
-        } else {
363
-            $term_taxonomy->set_count($term_taxonomy->count() + 1);
364
-            $term_taxonomy->save();
365
-        }
366
-        return $this->add_relationship_to($cpt_model_object, $term_taxonomy, 'Term_Taxonomy');
367
-    }
368
-
369
-
370
-    /**
371
-     * Removed the category specified by name as having a relation to this event.
372
-     * Does not remove the term or term_taxonomy.
373
-     *
374
-     * @param EE_CPT_Base $cpt_model_object_event
375
-     * @param string      $category_name name of the event category (term)
376
-     * @return bool
377
-     */
378
-    public function remove_event_category(EE_CPT_Base $cpt_model_object_event, $category_name)
379
-    {
380
-        // find the term_taxonomy by that name
381
-        $term_taxonomy = $this->get_first_related(
382
-            $cpt_model_object_event,
383
-            'Term_Taxonomy',
384
-            array(array('Term.name' => $category_name, 'taxonomy' => self::EVENT_CATEGORY_TAXONOMY))
385
-        );
386
-        /** @var $term_taxonomy EE_Term_Taxonomy */
387
-        if ($term_taxonomy) {
388
-            $term_taxonomy->set_count($term_taxonomy->count() - 1);
389
-            $term_taxonomy->save();
390
-        }
391
-        return $this->remove_relationship_to($cpt_model_object_event, $term_taxonomy, 'Term_Taxonomy');
392
-    }
393
-
394
-
395
-    /**
396
-     * This is a wrapper for the WordPress get_the_post_thumbnail() function that returns the feature image for the
397
-     * given CPT ID.  It accepts the same params as what get_the_post_thumbnail() accepts.
398
-     *
399
-     * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
400
-     * @access public
401
-     * @param int          $id   the ID for the cpt we want the feature image for
402
-     * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
403
-     *                           representing width and height in pixels (i.e. array(32,32) ).
404
-     * @param string|array $attr Optional. Query string or array of attributes.
405
-     * @return string HTML image element
406
-     */
407
-    public function get_feature_image($id, $size = 'thumbnail', $attr = '')
408
-    {
409
-        return get_the_post_thumbnail($id, $size, $attr);
410
-    }
411
-
412
-
413
-    /**
414
-     * Just a handy way to get the list of post statuses currently registered with WP.
415
-     *
416
-     * @global array $wp_post_statuses set in wp core for storing all the post stati
417
-     * @return array
418
-     */
419
-    public function get_post_statuses()
420
-    {
421
-        global $wp_post_statuses;
422
-        $statuses = array();
423
-        foreach ($wp_post_statuses as $post_status => $args_object) {
424
-            $statuses[ $post_status ] = $args_object->label;
425
-        }
426
-        return $statuses;
427
-    }
428
-
429
-
430
-    /**
431
-     * public method that can be used to retrieve the protected status array on the instantiated cpt model
432
-     *
433
-     * @return array array of statuses.
434
-     */
435
-    public function get_status_array()
436
-    {
437
-        $statuses = $this->get_post_statuses();
438
-        // first the global filter
439
-        $statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
440
-        // now the class specific filter
441
-        $statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
442
-        return $statuses;
443
-    }
444
-
445
-
446
-    /**
447
-     * this returns the post statuses that are NOT the default wordpress status
448
-     *
449
-     * @return array
450
-     */
451
-    public function get_custom_post_statuses()
452
-    {
453
-        $new_stati = array();
454
-        foreach ($this->_custom_stati as $status => $props) {
455
-            $new_stati[ $status ] = $props['label'];
456
-        }
457
-        return $new_stati;
458
-    }
459
-
460
-
461
-    /**
462
-     * Creates a child of EE_CPT_Base given a WP_Post or array of wpdb results which
463
-     * are a row from the posts table. If we're missing any fields required for the model,
464
-     * we just fetch the entire entry from the DB (ie, if you want to use this to save DB queries,
465
-     * make sure you are attaching all the model's fields onto the post)
466
-     *
467
-     * @param WP_Post|array $post
468
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class
469
-     */
470
-    public function instantiate_class_from_post_object_orig($post)
471
-    {
472
-        $post = (array) $post;
473
-        $has_all_necessary_fields_for_table = true;
474
-        // check if the post has fields on the meta table already
475
-        foreach ($this->_get_other_tables() as $table_obj) {
476
-            $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
477
-            foreach ($fields_for_that_table as $field_obj) {
478
-                if (
479
-                    ! isset($post[ $field_obj->get_table_column() ])
480
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
481
-                ) {
482
-                    $has_all_necessary_fields_for_table = false;
483
-                }
484
-            }
485
-        }
486
-        // if we don't have all the fields we need, then just fetch the proper model from the DB
487
-        if (! $has_all_necessary_fields_for_table) {
488
-            return $this->get_one_by_ID($post['ID']);
489
-        } else {
490
-            return $this->instantiate_class_from_array_or_object($post);
491
-        }
492
-    }
493
-
494
-
495
-    /**
496
-     * @param null $post
497
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class
498
-     */
499
-    public function instantiate_class_from_post_object($post = null)
500
-    {
501
-        if (empty($post)) {
502
-            global $post;
503
-        }
504
-        $post = (array) $post;
505
-        $tables_needing_to_be_queried = array();
506
-        // check if the post has fields on the meta table already
507
-        foreach ($this->get_tables() as $table_obj) {
508
-            $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
509
-            foreach ($fields_for_that_table as $field_obj) {
510
-                if (
511
-                    ! isset($post[ $field_obj->get_table_column() ])
512
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
513
-                ) {
514
-                    $tables_needing_to_be_queried[ $table_obj->get_table_alias() ] = $table_obj;
515
-                }
516
-            }
517
-        }
518
-        // if we don't have all the fields we need, then just fetch the proper model from the DB
519
-        if ($tables_needing_to_be_queried) {
520
-            if (
521
-                count($tables_needing_to_be_queried) == 1
522
-                && reset($tables_needing_to_be_queried)
523
-                   instanceof
524
-                   EE_Secondary_Table
525
-            ) {
526
-                // so we're only missing data from a secondary table. Well that's not too hard to query for
527
-                $table_to_query = reset($tables_needing_to_be_queried);
528
-                $missing_data = $this->_do_wpdb_query(
529
-                    'get_row',
530
-                    array(
531
-                        'SELECT * FROM '
532
-                        . $table_to_query->get_table_name()
533
-                        . ' WHERE '
534
-                        . $table_to_query->get_fk_on_table()
535
-                        . ' = '
536
-                        . $post['ID'],
537
-                        ARRAY_A,
538
-                    )
539
-                );
540
-                if (! empty($missing_data)) {
541
-                    $post = array_merge($post, $missing_data);
542
-                }
543
-            } else {
544
-                return $this->get_one_by_ID($post['ID']);
545
-            }
546
-        }
547
-        return $this->instantiate_class_from_array_or_object($post);
548
-    }
549
-
550
-
551
-    /**
552
-     * Gets the post type associated with this
553
-     *
554
-     * @throws EE_Error
555
-     * @return string
556
-     */
557
-    public function post_type()
558
-    {
559
-        $post_type_field = null;
560
-        foreach ($this->field_settings(true) as $field_obj) {
561
-            if ($field_obj instanceof EE_WP_Post_Type_Field) {
562
-                $post_type_field = $field_obj;
563
-                break;
564
-            }
565
-        }
566
-        if ($post_type_field == null) {
567
-            throw new EE_Error(
568
-                sprintf(
569
-                    esc_html__(
570
-                        "CPT Model %s should have a field of type EE_WP_Post_Type, but doesnt",
571
-                        "event_espresso"
572
-                    ),
573
-                    get_class($this)
574
-                )
575
-            );
576
-        }
577
-        return $post_type_field->get_default_value();
578
-    }
18
+	const EVENT_CATEGORY_TAXONOMY = 'espresso_event_categories';
19
+
20
+	/**
21
+	 * @var string post_status_publish - the wp post status for published cpts
22
+	 */
23
+	const post_status_publish = 'publish';
24
+
25
+	/**
26
+	 * @var string post_status_future - the wp post status for scheduled cpts
27
+	 */
28
+	const post_status_future = 'future';
29
+
30
+	/**
31
+	 * @var string post_status_draft - the wp post status for draft cpts
32
+	 */
33
+	const post_status_draft = 'draft';
34
+
35
+	/**
36
+	 * @var string post_status_pending - the wp post status for pending cpts
37
+	 */
38
+	const post_status_pending = 'pending';
39
+
40
+	/**
41
+	 * @var string post_status_private - the wp post status for private cpts
42
+	 */
43
+	const post_status_private = 'private';
44
+
45
+	/**
46
+	 * @var string post_status_trashed - the wp post status for trashed cpts
47
+	 */
48
+	const post_status_trashed = 'trash';
49
+
50
+	/**
51
+	 * This is an array of custom statuses for the given CPT model (modified by children)
52
+	 * format:
53
+	 * array(
54
+	 *        'status_name' => array(
55
+	 *            'label' => esc_html__('Status Name', 'event_espresso'),
56
+	 *            'public' => TRUE //whether a public status or not.
57
+	 *        )
58
+	 * )
59
+	 *
60
+	 * @var array
61
+	 */
62
+	protected $_custom_stati = array();
63
+
64
+
65
+	/**
66
+	 * Adds a relationship to Term_Taxonomy for each CPT_Base
67
+	 *
68
+	 * @param string $timezone
69
+	 * @throws \EE_Error
70
+	 */
71
+	protected function __construct($timezone = null)
72
+	{
73
+		// adds a relationship to Term_Taxonomy for all these models. For this to work
74
+		// Term_Relationship must have a relation to each model subclassing EE_CPT_Base explicitly
75
+		// eg, in EEM_Term_Relationship, inside the _model_relations array, there must be an entry
76
+		// with key equalling the subclassing model's model name (eg 'Event' or 'Venue'), and the value
77
+		// must also be new EE_HABTM_Relation('Term_Relationship');
78
+		$this->_model_relations['Term_Taxonomy'] = new EE_HABTM_Relation('Term_Relationship');
79
+		$primary_table_name = null;
80
+		// add  the common _status field to all CPT primary tables.
81
+		foreach ($this->_tables as $alias => $table_obj) {
82
+			if ($table_obj instanceof EE_Primary_Table) {
83
+				$primary_table_name = $alias;
84
+			}
85
+		}
86
+		// set default wp post statuses if child has not already set.
87
+		if (! isset($this->_fields[ $primary_table_name ]['status'])) {
88
+			$this->_fields[ $primary_table_name ]['status'] = new EE_WP_Post_Status_Field(
89
+				'post_status',
90
+				esc_html__("Event Status", "event_espresso"),
91
+				false,
92
+				'draft'
93
+			);
94
+		}
95
+		if (! isset($this->_fields[ $primary_table_name ]['to_ping'])) {
96
+			$this->_fields[ $primary_table_name ]['to_ping'] = new EE_DB_Only_Text_Field(
97
+				'to_ping',
98
+				esc_html__('To Ping', 'event_espresso'),
99
+				false,
100
+				''
101
+			);
102
+		}
103
+		if (! isset($this->_fields[ $primary_table_name ]['pinged'])) {
104
+			$this->_fields[ $primary_table_name ]['pinged'] = new EE_DB_Only_Text_Field(
105
+				'pinged',
106
+				esc_html__('Pinged', 'event_espresso'),
107
+				false,
108
+				''
109
+			);
110
+		}
111
+		if (! isset($this->_fields[ $primary_table_name ]['comment_status'])) {
112
+			$this->_fields[ $primary_table_name ]['comment_status'] = new EE_Plain_Text_Field(
113
+				'comment_status',
114
+				esc_html__('Comment Status', 'event_espresso'),
115
+				false,
116
+				'open'
117
+			);
118
+		}
119
+		if (! isset($this->_fields[ $primary_table_name ]['ping_status'])) {
120
+			$this->_fields[ $primary_table_name ]['ping_status'] = new EE_Plain_Text_Field(
121
+				'ping_status',
122
+				esc_html__('Ping Status', 'event_espresso'),
123
+				false,
124
+				'open'
125
+			);
126
+		}
127
+		if (! isset($this->_fields[ $primary_table_name ]['post_content_filtered'])) {
128
+			$this->_fields[ $primary_table_name ]['post_content_filtered'] = new EE_DB_Only_Text_Field(
129
+				'post_content_filtered',
130
+				esc_html__('Post Content Filtered', 'event_espresso'),
131
+				false,
132
+				''
133
+			);
134
+		}
135
+		if (! isset($this->_model_relations['Post_Meta'])) {
136
+			// don't block deletes though because we want to maintain the current behaviour
137
+			$this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
138
+		}
139
+		if (! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
140
+			// nothing was set during child constructor, so set default
141
+			$this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
142
+		}
143
+		if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
144
+			// nothing was set during child constructor, so set default
145
+			// it's ok for child classes to specify this, but generally this is more DRY
146
+			$this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
147
+		}
148
+		parent::__construct($timezone);
149
+	}
150
+
151
+
152
+	/**
153
+	 * @return array
154
+	 */
155
+	public function public_event_stati()
156
+	{
157
+		// @see wp-includes/post.php
158
+		return get_post_stati(array('public' => true));
159
+	}
160
+
161
+
162
+	/**
163
+	 * Searches for field on this model of type 'deleted_flag'. if it is found,
164
+	 * returns it's name. BUT That doesn't apply to CPTs. We should instead use post_status_field_name
165
+	 *
166
+	 * @return string
167
+	 * @throws EE_Error
168
+	 */
169
+	public function deleted_field_name()
170
+	{
171
+		throw new EE_Error(
172
+			sprintf(
173
+				esc_html__(
174
+					"EEM_CPT_Base should nto call deleted_field_name! It should instead use post_status_field_name",
175
+					"event_espresso"
176
+				)
177
+			)
178
+		);
179
+	}
180
+
181
+
182
+	/**
183
+	 * Gets the field's name that sets the post status
184
+	 *
185
+	 * @return string
186
+	 * @throws EE_Error
187
+	 */
188
+	public function post_status_field_name()
189
+	{
190
+		$field = $this->get_a_field_of_type('EE_WP_Post_Status_Field');
191
+		if ($field) {
192
+			return $field->get_name();
193
+		} else {
194
+			throw new EE_Error(
195
+				sprintf(
196
+					esc_html__(
197
+						'We are trying to find the post status flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
198
+						'event_espresso'
199
+					),
200
+					get_class($this),
201
+					get_class($this)
202
+				)
203
+			);
204
+		}
205
+	}
206
+
207
+
208
+	/**
209
+	 * Alters the query params so that only trashed/soft-deleted items are considered
210
+	 *
211
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
212
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
213
+	 */
214
+	protected function _alter_query_params_so_only_trashed_items_included($query_params)
215
+	{
216
+		$post_status_field_name = $this->post_status_field_name();
217
+		$query_params[0][ $post_status_field_name ] = self::post_status_trashed;
218
+		return $query_params;
219
+	}
220
+
221
+
222
+	/**
223
+	 * Alters the query params so each item's deleted status is ignored.
224
+	 *
225
+	 * @param array $query_params
226
+	 * @return array
227
+	 */
228
+	protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
229
+	{
230
+		$query_params['default_where_conditions'] = 'minimum';
231
+		return $query_params;
232
+	}
233
+
234
+
235
+	/**
236
+	 * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
237
+	 *
238
+	 * @param boolean $delete       true to indicate deletion, false to indicate restoration
239
+	 * @param array   $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
240
+	 * @return boolean success
241
+	 */
242
+	public function delete_or_restore($delete = true, $query_params = array())
243
+	{
244
+		$post_status_field_name = $this->post_status_field_name();
245
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
246
+		$new_status = $delete ? self::post_status_trashed : 'draft';
247
+		if ($this->update(array($post_status_field_name => $new_status), $query_params)) {
248
+			return true;
249
+		} else {
250
+			return false;
251
+		}
252
+	}
253
+
254
+
255
+	/**
256
+	 * meta_table
257
+	 * returns first EE_Secondary_Table table name
258
+	 *
259
+	 * @access public
260
+	 * @return string
261
+	 */
262
+	public function meta_table()
263
+	{
264
+		$meta_table = $this->_get_other_tables();
265
+		$meta_table = reset($meta_table);
266
+		return $meta_table instanceof EE_Secondary_Table ? $meta_table->get_table_name() : null;
267
+	}
268
+
269
+
270
+	/**
271
+	 * This simply returns an array of the meta table fields (useful for when we just need to update those fields)
272
+	 *
273
+	 * @param  bool $all triggers whether we include DB_Only fields or JUST non DB_Only fields.  Defaults to false (no
274
+	 *                   db only fields)
275
+	 * @return array
276
+	 */
277
+	public function get_meta_table_fields($all = false)
278
+	{
279
+		$all_fields = $fields_to_return = array();
280
+		foreach ($this->_tables as $alias => $table_obj) {
281
+			if ($table_obj instanceof EE_Secondary_Table) {
282
+				$all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
283
+			}
284
+		}
285
+		if (! $all) {
286
+			foreach ($all_fields as $name => $obj) {
287
+				if ($obj instanceof EE_DB_Only_Field_Base) {
288
+					continue;
289
+				}
290
+				$fields_to_return[] = $name;
291
+			}
292
+		} else {
293
+			$fields_to_return = array_keys($all_fields);
294
+		}
295
+		return $fields_to_return;
296
+	}
297
+
298
+
299
+	/**
300
+	 * Adds an event category with the specified name and description to the specified
301
+	 * $cpt_model_object. Intelligently adds a term if necessary, and adds a term_taxonomy if necessary,
302
+	 * and adds an entry in the term_relationship if necessary.
303
+	 *
304
+	 * @param EE_CPT_Base $cpt_model_object
305
+	 * @param string      $category_name (used to derive the term slug too)
306
+	 * @param string      $category_description
307
+	 * @param int         $parent_term_taxonomy_id
308
+	 * @return EE_Term_Taxonomy
309
+	 */
310
+	public function add_event_category(
311
+		EE_CPT_Base $cpt_model_object,
312
+		$category_name,
313
+		$category_description = '',
314
+		$parent_term_taxonomy_id = null
315
+	) {
316
+		// create term
317
+		require_once(EE_MODELS . 'EEM_Term.model.php');
318
+		// first, check for a term by the same name or slug
319
+		$category_slug = sanitize_title($category_name);
320
+		$term = EEM_Term::instance()->get_one(
321
+			array(
322
+				array(
323
+					'OR' => array(
324
+						'name' => $category_name,
325
+						'slug' => $category_slug,
326
+					),
327
+					'Term_Taxonomy.taxonomy' => self::EVENT_CATEGORY_TAXONOMY
328
+				),
329
+			)
330
+		);
331
+		if (! $term) {
332
+			$term = EE_Term::new_instance(
333
+				array(
334
+					'name' => $category_name,
335
+					'slug' => $category_slug,
336
+				)
337
+			);
338
+			$term->save();
339
+		}
340
+		// make sure there's a term-taxonomy entry too
341
+		require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
342
+		$term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(
343
+			array(
344
+				array(
345
+					'term_id'  => $term->ID(),
346
+					'taxonomy' => self::EVENT_CATEGORY_TAXONOMY,
347
+				),
348
+			)
349
+		);
350
+		/** @var $term_taxonomy EE_Term_Taxonomy */
351
+		if (! $term_taxonomy) {
352
+			$term_taxonomy = EE_Term_Taxonomy::new_instance(
353
+				array(
354
+					'term_id'     => $term->ID(),
355
+					'taxonomy'    => self::EVENT_CATEGORY_TAXONOMY,
356
+					'description' => $category_description,
357
+					'term_count'       => 1,
358
+					'parent'      => $parent_term_taxonomy_id,
359
+				)
360
+			);
361
+			$term_taxonomy->save();
362
+		} else {
363
+			$term_taxonomy->set_count($term_taxonomy->count() + 1);
364
+			$term_taxonomy->save();
365
+		}
366
+		return $this->add_relationship_to($cpt_model_object, $term_taxonomy, 'Term_Taxonomy');
367
+	}
368
+
369
+
370
+	/**
371
+	 * Removed the category specified by name as having a relation to this event.
372
+	 * Does not remove the term or term_taxonomy.
373
+	 *
374
+	 * @param EE_CPT_Base $cpt_model_object_event
375
+	 * @param string      $category_name name of the event category (term)
376
+	 * @return bool
377
+	 */
378
+	public function remove_event_category(EE_CPT_Base $cpt_model_object_event, $category_name)
379
+	{
380
+		// find the term_taxonomy by that name
381
+		$term_taxonomy = $this->get_first_related(
382
+			$cpt_model_object_event,
383
+			'Term_Taxonomy',
384
+			array(array('Term.name' => $category_name, 'taxonomy' => self::EVENT_CATEGORY_TAXONOMY))
385
+		);
386
+		/** @var $term_taxonomy EE_Term_Taxonomy */
387
+		if ($term_taxonomy) {
388
+			$term_taxonomy->set_count($term_taxonomy->count() - 1);
389
+			$term_taxonomy->save();
390
+		}
391
+		return $this->remove_relationship_to($cpt_model_object_event, $term_taxonomy, 'Term_Taxonomy');
392
+	}
393
+
394
+
395
+	/**
396
+	 * This is a wrapper for the WordPress get_the_post_thumbnail() function that returns the feature image for the
397
+	 * given CPT ID.  It accepts the same params as what get_the_post_thumbnail() accepts.
398
+	 *
399
+	 * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
400
+	 * @access public
401
+	 * @param int          $id   the ID for the cpt we want the feature image for
402
+	 * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
403
+	 *                           representing width and height in pixels (i.e. array(32,32) ).
404
+	 * @param string|array $attr Optional. Query string or array of attributes.
405
+	 * @return string HTML image element
406
+	 */
407
+	public function get_feature_image($id, $size = 'thumbnail', $attr = '')
408
+	{
409
+		return get_the_post_thumbnail($id, $size, $attr);
410
+	}
411
+
412
+
413
+	/**
414
+	 * Just a handy way to get the list of post statuses currently registered with WP.
415
+	 *
416
+	 * @global array $wp_post_statuses set in wp core for storing all the post stati
417
+	 * @return array
418
+	 */
419
+	public function get_post_statuses()
420
+	{
421
+		global $wp_post_statuses;
422
+		$statuses = array();
423
+		foreach ($wp_post_statuses as $post_status => $args_object) {
424
+			$statuses[ $post_status ] = $args_object->label;
425
+		}
426
+		return $statuses;
427
+	}
428
+
429
+
430
+	/**
431
+	 * public method that can be used to retrieve the protected status array on the instantiated cpt model
432
+	 *
433
+	 * @return array array of statuses.
434
+	 */
435
+	public function get_status_array()
436
+	{
437
+		$statuses = $this->get_post_statuses();
438
+		// first the global filter
439
+		$statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
440
+		// now the class specific filter
441
+		$statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
442
+		return $statuses;
443
+	}
444
+
445
+
446
+	/**
447
+	 * this returns the post statuses that are NOT the default wordpress status
448
+	 *
449
+	 * @return array
450
+	 */
451
+	public function get_custom_post_statuses()
452
+	{
453
+		$new_stati = array();
454
+		foreach ($this->_custom_stati as $status => $props) {
455
+			$new_stati[ $status ] = $props['label'];
456
+		}
457
+		return $new_stati;
458
+	}
459
+
460
+
461
+	/**
462
+	 * Creates a child of EE_CPT_Base given a WP_Post or array of wpdb results which
463
+	 * are a row from the posts table. If we're missing any fields required for the model,
464
+	 * we just fetch the entire entry from the DB (ie, if you want to use this to save DB queries,
465
+	 * make sure you are attaching all the model's fields onto the post)
466
+	 *
467
+	 * @param WP_Post|array $post
468
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class
469
+	 */
470
+	public function instantiate_class_from_post_object_orig($post)
471
+	{
472
+		$post = (array) $post;
473
+		$has_all_necessary_fields_for_table = true;
474
+		// check if the post has fields on the meta table already
475
+		foreach ($this->_get_other_tables() as $table_obj) {
476
+			$fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
477
+			foreach ($fields_for_that_table as $field_obj) {
478
+				if (
479
+					! isset($post[ $field_obj->get_table_column() ])
480
+					&& ! isset($post[ $field_obj->get_qualified_column() ])
481
+				) {
482
+					$has_all_necessary_fields_for_table = false;
483
+				}
484
+			}
485
+		}
486
+		// if we don't have all the fields we need, then just fetch the proper model from the DB
487
+		if (! $has_all_necessary_fields_for_table) {
488
+			return $this->get_one_by_ID($post['ID']);
489
+		} else {
490
+			return $this->instantiate_class_from_array_or_object($post);
491
+		}
492
+	}
493
+
494
+
495
+	/**
496
+	 * @param null $post
497
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class
498
+	 */
499
+	public function instantiate_class_from_post_object($post = null)
500
+	{
501
+		if (empty($post)) {
502
+			global $post;
503
+		}
504
+		$post = (array) $post;
505
+		$tables_needing_to_be_queried = array();
506
+		// check if the post has fields on the meta table already
507
+		foreach ($this->get_tables() as $table_obj) {
508
+			$fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
509
+			foreach ($fields_for_that_table as $field_obj) {
510
+				if (
511
+					! isset($post[ $field_obj->get_table_column() ])
512
+					&& ! isset($post[ $field_obj->get_qualified_column() ])
513
+				) {
514
+					$tables_needing_to_be_queried[ $table_obj->get_table_alias() ] = $table_obj;
515
+				}
516
+			}
517
+		}
518
+		// if we don't have all the fields we need, then just fetch the proper model from the DB
519
+		if ($tables_needing_to_be_queried) {
520
+			if (
521
+				count($tables_needing_to_be_queried) == 1
522
+				&& reset($tables_needing_to_be_queried)
523
+				   instanceof
524
+				   EE_Secondary_Table
525
+			) {
526
+				// so we're only missing data from a secondary table. Well that's not too hard to query for
527
+				$table_to_query = reset($tables_needing_to_be_queried);
528
+				$missing_data = $this->_do_wpdb_query(
529
+					'get_row',
530
+					array(
531
+						'SELECT * FROM '
532
+						. $table_to_query->get_table_name()
533
+						. ' WHERE '
534
+						. $table_to_query->get_fk_on_table()
535
+						. ' = '
536
+						. $post['ID'],
537
+						ARRAY_A,
538
+					)
539
+				);
540
+				if (! empty($missing_data)) {
541
+					$post = array_merge($post, $missing_data);
542
+				}
543
+			} else {
544
+				return $this->get_one_by_ID($post['ID']);
545
+			}
546
+		}
547
+		return $this->instantiate_class_from_array_or_object($post);
548
+	}
549
+
550
+
551
+	/**
552
+	 * Gets the post type associated with this
553
+	 *
554
+	 * @throws EE_Error
555
+	 * @return string
556
+	 */
557
+	public function post_type()
558
+	{
559
+		$post_type_field = null;
560
+		foreach ($this->field_settings(true) as $field_obj) {
561
+			if ($field_obj instanceof EE_WP_Post_Type_Field) {
562
+				$post_type_field = $field_obj;
563
+				break;
564
+			}
565
+		}
566
+		if ($post_type_field == null) {
567
+			throw new EE_Error(
568
+				sprintf(
569
+					esc_html__(
570
+						"CPT Model %s should have a field of type EE_WP_Post_Type, but doesnt",
571
+						"event_espresso"
572
+					),
573
+					get_class($this)
574
+				)
575
+			);
576
+		}
577
+		return $post_type_field->get_default_value();
578
+	}
579 579
 }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -84,63 +84,63 @@  discard block
 block discarded – undo
84 84
             }
85 85
         }
86 86
         // set default wp post statuses if child has not already set.
87
-        if (! isset($this->_fields[ $primary_table_name ]['status'])) {
88
-            $this->_fields[ $primary_table_name ]['status'] = new EE_WP_Post_Status_Field(
87
+        if ( ! isset($this->_fields[$primary_table_name]['status'])) {
88
+            $this->_fields[$primary_table_name]['status'] = new EE_WP_Post_Status_Field(
89 89
                 'post_status',
90 90
                 esc_html__("Event Status", "event_espresso"),
91 91
                 false,
92 92
                 'draft'
93 93
             );
94 94
         }
95
-        if (! isset($this->_fields[ $primary_table_name ]['to_ping'])) {
96
-            $this->_fields[ $primary_table_name ]['to_ping'] = new EE_DB_Only_Text_Field(
95
+        if ( ! isset($this->_fields[$primary_table_name]['to_ping'])) {
96
+            $this->_fields[$primary_table_name]['to_ping'] = new EE_DB_Only_Text_Field(
97 97
                 'to_ping',
98 98
                 esc_html__('To Ping', 'event_espresso'),
99 99
                 false,
100 100
                 ''
101 101
             );
102 102
         }
103
-        if (! isset($this->_fields[ $primary_table_name ]['pinged'])) {
104
-            $this->_fields[ $primary_table_name ]['pinged'] = new EE_DB_Only_Text_Field(
103
+        if ( ! isset($this->_fields[$primary_table_name]['pinged'])) {
104
+            $this->_fields[$primary_table_name]['pinged'] = new EE_DB_Only_Text_Field(
105 105
                 'pinged',
106 106
                 esc_html__('Pinged', 'event_espresso'),
107 107
                 false,
108 108
                 ''
109 109
             );
110 110
         }
111
-        if (! isset($this->_fields[ $primary_table_name ]['comment_status'])) {
112
-            $this->_fields[ $primary_table_name ]['comment_status'] = new EE_Plain_Text_Field(
111
+        if ( ! isset($this->_fields[$primary_table_name]['comment_status'])) {
112
+            $this->_fields[$primary_table_name]['comment_status'] = new EE_Plain_Text_Field(
113 113
                 'comment_status',
114 114
                 esc_html__('Comment Status', 'event_espresso'),
115 115
                 false,
116 116
                 'open'
117 117
             );
118 118
         }
119
-        if (! isset($this->_fields[ $primary_table_name ]['ping_status'])) {
120
-            $this->_fields[ $primary_table_name ]['ping_status'] = new EE_Plain_Text_Field(
119
+        if ( ! isset($this->_fields[$primary_table_name]['ping_status'])) {
120
+            $this->_fields[$primary_table_name]['ping_status'] = new EE_Plain_Text_Field(
121 121
                 'ping_status',
122 122
                 esc_html__('Ping Status', 'event_espresso'),
123 123
                 false,
124 124
                 'open'
125 125
             );
126 126
         }
127
-        if (! isset($this->_fields[ $primary_table_name ]['post_content_filtered'])) {
128
-            $this->_fields[ $primary_table_name ]['post_content_filtered'] = new EE_DB_Only_Text_Field(
127
+        if ( ! isset($this->_fields[$primary_table_name]['post_content_filtered'])) {
128
+            $this->_fields[$primary_table_name]['post_content_filtered'] = new EE_DB_Only_Text_Field(
129 129
                 'post_content_filtered',
130 130
                 esc_html__('Post Content Filtered', 'event_espresso'),
131 131
                 false,
132 132
                 ''
133 133
             );
134 134
         }
135
-        if (! isset($this->_model_relations['Post_Meta'])) {
135
+        if ( ! isset($this->_model_relations['Post_Meta'])) {
136 136
             // don't block deletes though because we want to maintain the current behaviour
137 137
             $this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
138 138
         }
139
-        if (! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
139
+        if ( ! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
140 140
             // nothing was set during child constructor, so set default
141 141
             $this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
142 142
         }
143
-        if (! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
143
+        if ( ! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
144 144
             // nothing was set during child constructor, so set default
145 145
             // it's ok for child classes to specify this, but generally this is more DRY
146 146
             $this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
     protected function _alter_query_params_so_only_trashed_items_included($query_params)
215 215
     {
216 216
         $post_status_field_name = $this->post_status_field_name();
217
-        $query_params[0][ $post_status_field_name ] = self::post_status_trashed;
217
+        $query_params[0][$post_status_field_name] = self::post_status_trashed;
218 218
         return $query_params;
219 219
     }
220 220
 
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
                 $all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
283 283
             }
284 284
         }
285
-        if (! $all) {
285
+        if ( ! $all) {
286 286
             foreach ($all_fields as $name => $obj) {
287 287
                 if ($obj instanceof EE_DB_Only_Field_Base) {
288 288
                     continue;
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
         $parent_term_taxonomy_id = null
315 315
     ) {
316 316
         // create term
317
-        require_once(EE_MODELS . 'EEM_Term.model.php');
317
+        require_once(EE_MODELS.'EEM_Term.model.php');
318 318
         // first, check for a term by the same name or slug
319 319
         $category_slug = sanitize_title($category_name);
320 320
         $term = EEM_Term::instance()->get_one(
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
                 ),
329 329
             )
330 330
         );
331
-        if (! $term) {
331
+        if ( ! $term) {
332 332
             $term = EE_Term::new_instance(
333 333
                 array(
334 334
                     'name' => $category_name,
@@ -338,7 +338,7 @@  discard block
 block discarded – undo
338 338
             $term->save();
339 339
         }
340 340
         // make sure there's a term-taxonomy entry too
341
-        require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
341
+        require_once(EE_MODELS.'EEM_Term_Taxonomy.model.php');
342 342
         $term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(
343 343
             array(
344 344
                 array(
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
             )
349 349
         );
350 350
         /** @var $term_taxonomy EE_Term_Taxonomy */
351
-        if (! $term_taxonomy) {
351
+        if ( ! $term_taxonomy) {
352 352
             $term_taxonomy = EE_Term_Taxonomy::new_instance(
353 353
                 array(
354 354
                     'term_id'     => $term->ID(),
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
         global $wp_post_statuses;
422 422
         $statuses = array();
423 423
         foreach ($wp_post_statuses as $post_status => $args_object) {
424
-            $statuses[ $post_status ] = $args_object->label;
424
+            $statuses[$post_status] = $args_object->label;
425 425
         }
426 426
         return $statuses;
427 427
     }
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
         // first the global filter
439 439
         $statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
440 440
         // now the class specific filter
441
-        $statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
441
+        $statuses = apply_filters('FHEE_EEM_'.get_class($this).'__get_status_array', $statuses);
442 442
         return $statuses;
443 443
     }
444 444
 
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
     {
453 453
         $new_stati = array();
454 454
         foreach ($this->_custom_stati as $status => $props) {
455
-            $new_stati[ $status ] = $props['label'];
455
+            $new_stati[$status] = $props['label'];
456 456
         }
457 457
         return $new_stati;
458 458
     }
@@ -476,15 +476,15 @@  discard block
 block discarded – undo
476 476
             $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
477 477
             foreach ($fields_for_that_table as $field_obj) {
478 478
                 if (
479
-                    ! isset($post[ $field_obj->get_table_column() ])
480
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
479
+                    ! isset($post[$field_obj->get_table_column()])
480
+                    && ! isset($post[$field_obj->get_qualified_column()])
481 481
                 ) {
482 482
                     $has_all_necessary_fields_for_table = false;
483 483
                 }
484 484
             }
485 485
         }
486 486
         // if we don't have all the fields we need, then just fetch the proper model from the DB
487
-        if (! $has_all_necessary_fields_for_table) {
487
+        if ( ! $has_all_necessary_fields_for_table) {
488 488
             return $this->get_one_by_ID($post['ID']);
489 489
         } else {
490 490
             return $this->instantiate_class_from_array_or_object($post);
@@ -508,10 +508,10 @@  discard block
 block discarded – undo
508 508
             $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
509 509
             foreach ($fields_for_that_table as $field_obj) {
510 510
                 if (
511
-                    ! isset($post[ $field_obj->get_table_column() ])
512
-                    && ! isset($post[ $field_obj->get_qualified_column() ])
511
+                    ! isset($post[$field_obj->get_table_column()])
512
+                    && ! isset($post[$field_obj->get_qualified_column()])
513 513
                 ) {
514
-                    $tables_needing_to_be_queried[ $table_obj->get_table_alias() ] = $table_obj;
514
+                    $tables_needing_to_be_queried[$table_obj->get_table_alias()] = $table_obj;
515 515
                 }
516 516
             }
517 517
         }
@@ -537,7 +537,7 @@  discard block
 block discarded – undo
537 537
                         ARRAY_A,
538 538
                     )
539 539
                 );
540
-                if (! empty($missing_data)) {
540
+                if ( ! empty($missing_data)) {
541 541
                     $post = array_merge($post, $missing_data);
542 542
                 }
543 543
             } else {
Please login to merge, or discard this patch.
core/db_models/relations/EE_Model_Relation_Base.php 2 patches
Indentation   +497 added lines, -497 removed lines patch added patch discarded remove patch
@@ -16,502 +16,502 @@
 block discarded – undo
16 16
  */
17 17
 abstract class EE_Model_Relation_Base implements HasSchemaInterface
18 18
 {
19
-    /**
20
-     * The model name of which this relation is a component (ie, the model that called new EE_Model_Relation_Base)
21
-     *
22
-     * @var string eg Event, Question_Group, Registration
23
-     */
24
-    private $_this_model_name;
25
-    /**
26
-     * The model name pointed to by this relation (ie, the model we want to establish a relationship to)
27
-     *
28
-     * @var string eg Event, Question_Group, Registration
29
-     */
30
-    private $_other_model_name;
31
-
32
-    /**
33
-     * this is typically used when calling the relation models to make sure they inherit any set timezone from the
34
-     * initiating model.
35
-     *
36
-     * @var string
37
-     */
38
-    protected $_timezone;
39
-
40
-    /**
41
-     * If you try to delete "this_model", and there are related "other_models",
42
-     * and this isn't null, then abandon the deletion and add this warning.
43
-     * This effectively makes it impossible to delete "this_model" while there are
44
-     * related "other_models" along this relation.
45
-     *
46
-     * @var string (internationalized)
47
-     */
48
-    protected $_blocking_delete_error_message;
49
-
50
-    protected $_blocking_delete = false;
51
-
52
-    /**
53
-     * Object representing the relationship between two models. This knows how to join the models,
54
-     * get related models across the relation, and add-and-remove the relationships.
55
-     *
56
-     * @param boolean $block_deletes                 if there are related models across this relation, block (prevent
57
-     *                                               and add an error) the deletion of this model
58
-     * @param string  $blocking_delete_error_message a customized error message on blocking deletes instead of the
59
-     *                                               default
60
-     */
61
-    public function __construct($block_deletes, $blocking_delete_error_message)
62
-    {
63
-        $this->_blocking_delete               = $block_deletes;
64
-        $this->_blocking_delete_error_message = $blocking_delete_error_message;
65
-    }
66
-
67
-
68
-    /**
69
-     * @param $this_model_name
70
-     * @param $other_model_name
71
-     * @throws EE_Error
72
-     */
73
-    public function _construct_finalize_set_models($this_model_name, $other_model_name)
74
-    {
75
-        $this->_this_model_name  = $this_model_name;
76
-        $this->_other_model_name = $other_model_name;
77
-        if (is_string($this->_blocking_delete)) {
78
-            throw new EE_Error(sprintf(
79
-                esc_html__(
80
-                    "When instantiating the relation of type %s from %s to %s, the \$block_deletes argument should be a boolean, not a string (%s)",
81
-                    "event_espresso"
82
-                ),
83
-                get_class($this),
84
-                $this_model_name,
85
-                $other_model_name,
86
-                $this->_blocking_delete
87
-            ));
88
-        }
89
-    }
90
-
91
-
92
-    /**
93
-     * Gets the model where this relation is defined.
94
-     *
95
-     * @return EEM_Base
96
-     */
97
-    public function get_this_model()
98
-    {
99
-        return $this->_get_model($this->_this_model_name);
100
-    }
101
-
102
-
103
-    /**
104
-     * Gets the model which this relation establishes the relation TO (ie,
105
-     * this relation object was defined on get_this_model(), get_other_model() is the other one)
106
-     *
107
-     * @return EEM_Base
108
-     */
109
-    public function get_other_model()
110
-    {
111
-        return $this->_get_model($this->_other_model_name);
112
-    }
113
-
114
-
115
-    /**
116
-     * Internally used by get_this_model() and get_other_model()
117
-     *
118
-     * @param string $model_name like Event, Question_Group, etc. omit the EEM_
119
-     * @return EEM_Base
120
-     */
121
-    protected function _get_model($model_name)
122
-    {
123
-        $modelInstance = EE_Registry::instance()->load_model($model_name);
124
-        $modelInstance->set_timezone($this->_timezone);
125
-        return $modelInstance;
126
-    }
127
-
128
-
129
-    /**
130
-     * entirely possible that relations may be called from a model and we need to make sure those relations have their
131
-     * timezone set correctly.
132
-     *
133
-     * @param string $timezone timezone to set.
134
-     */
135
-    public function set_timezone($timezone)
136
-    {
137
-        if ($timezone !== null) {
138
-            $this->_timezone = $timezone;
139
-        }
140
-    }
141
-
142
-
143
-    /**
144
-     * @param        $other_table
145
-     * @param        $other_table_alias
146
-     * @param        $other_table_column
147
-     * @param        $this_table_alias
148
-     * @param        $this_table_join_column
149
-     * @param string $extra_join_sql
150
-     * @return string
151
-     */
152
-    protected function _left_join(
153
-        $other_table,
154
-        $other_table_alias,
155
-        $other_table_column,
156
-        $this_table_alias,
157
-        $this_table_join_column,
158
-        $extra_join_sql = ''
159
-    ) {
160
-        return " LEFT JOIN " . $other_table . " AS " . $other_table_alias . " ON " . $other_table_alias . "." . $other_table_column . "=" . $this_table_alias . "." . $this_table_join_column . ($extra_join_sql ? " AND $extra_join_sql" : '');
161
-    }
162
-
163
-
164
-    /**
165
-     * Gets all the model objects of type of other model related to $model_object,
166
-     * according to this relation. This is the same code for EE_HABTM_Relation and EE_Has_Many_Relation.
167
-     * For both of those child classes, $model_object must be saved so that it has an ID before querying,
168
-     * otherwise an error will be thrown. Note: by default we disable default_where_conditions
169
-     * EE_Belongs_To_Relation doesn't need to be saved before querying.
170
-     *
171
-     * @param EE_Base_Class|int $model_object_or_id                      or the primary key of this model
172
-     * @param array             $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
173
-     * @param boolean           $values_already_prepared_by_model_object @deprecated since 4.8.1
174
-     * @return EE_Base_Class[]
175
-     * @throws \EE_Error
176
-     */
177
-    public function get_all_related(
178
-        $model_object_or_id,
179
-        $query_params = array(),
180
-        $values_already_prepared_by_model_object = false
181
-    ) {
182
-        if ($values_already_prepared_by_model_object !== false) {
183
-            EE_Error::doing_it_wrong(
184
-                'EE_Model_Relation_Base::get_all_related',
185
-                esc_html__('The argument $values_already_prepared_by_model_object is no longer used.', 'event_espresso'),
186
-                '4.8.1'
187
-            );
188
-        }
189
-        $query_params                                      = $this->_disable_default_where_conditions_on_query_param($query_params);
190
-        $query_param_where_this_model_pk                   = $this->get_this_model()->get_this_model_name()
191
-                                                             . "."
192
-                                                             . $this->get_this_model()->get_primary_key_field()->get_name();
193
-        $model_object_id                                   = $this->_get_model_object_id($model_object_or_id);
194
-        $query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
195
-        return $this->get_other_model()->get_all($query_params);
196
-    }
197
-
198
-
199
-    /**
200
-     * Alters the $query_params to disable default where conditions, unless otherwise specified
201
-     *
202
-     * @param string $query_params
203
-     * @return array
204
-     */
205
-    protected function _disable_default_where_conditions_on_query_param($query_params)
206
-    {
207
-        if (! isset($query_params['default_where_conditions'])) {
208
-            $query_params['default_where_conditions'] = 'none';
209
-        }
210
-        return $query_params;
211
-    }
212
-
213
-
214
-    /**
215
-     * Deletes the related model objects which meet the query parameters. If no
216
-     * parameters are specified, then all related model objects will be deleted.
217
-     * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
218
-     * model objects will only be soft-deleted.
219
-     *
220
-     * @param EE_Base_Class|int|string $model_object_or_id
221
-     * @param array                    $query_params
222
-     * @return int of how many related models got deleted
223
-     * @throws \EE_Error
224
-     */
225
-    public function delete_all_related($model_object_or_id, $query_params = array())
226
-    {
227
-        // for each thing we would delete,
228
-        $related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
229
-        // determine if it's blocked by anything else before it can be deleted
230
-        $deleted_count = 0;
231
-        foreach ($related_model_objects as $related_model_object) {
232
-            $delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
233
-                $related_model_object,
234
-                $model_object_or_id
235
-            );
236
-            /* @var $model_object_or_id EE_Base_Class */
237
-            if (! $delete_is_blocked) {
238
-                $this->remove_relation_to($model_object_or_id, $related_model_object);
239
-                $related_model_object->delete();
240
-                $deleted_count++;
241
-            }
242
-        }
243
-        return $deleted_count;
244
-    }
245
-
246
-
247
-    /**
248
-     * Deletes the related model objects which meet the query parameters. If no
249
-     * parameters are specified, then all related model objects will be deleted.
250
-     * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
251
-     * model objects will only be soft-deleted.
252
-     *
253
-     * @param EE_Base_Class|int|string $model_object_or_id
254
-     * @param array                    $query_params
255
-     * @return int of how many related models got deleted
256
-     * @throws \EE_Error
257
-     */
258
-    public function delete_related_permanently($model_object_or_id, $query_params = array())
259
-    {
260
-        // for each thing we would delete,
261
-        $related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
262
-        // determine if it's blocked by anything else before it can be deleted
263
-        $deleted_count = 0;
264
-        foreach ($related_model_objects as $related_model_object) {
265
-            $delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
266
-                $related_model_object,
267
-                $model_object_or_id
268
-            );
269
-            /* @var $model_object_or_id EE_Base_Class */
270
-            if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
271
-                $this->remove_relation_to($model_object_or_id, $related_model_object);
272
-                $deleted_count++;
273
-                if (! $delete_is_blocked) {
274
-                    $related_model_object->delete_permanently();
275
-                } else {
276
-                    // delete is blocked
277
-                    // brent and darren, in this case, wanted to just soft delete it then
278
-                    $related_model_object->delete();
279
-                }
280
-            } else {
281
-                // its not a soft-deletable thing anyways. do the normal logic.
282
-                if (! $delete_is_blocked) {
283
-                    $this->remove_relation_to($model_object_or_id, $related_model_object);
284
-                    $related_model_object->delete();
285
-                    $deleted_count++;
286
-                }
287
-            }
288
-        }
289
-        return $deleted_count;
290
-    }
291
-
292
-
293
-    /**
294
-     * this just returns a model_object_id for incoming item that could be an object or id.
295
-     *
296
-     * @param  EE_Base_Class|int $model_object_or_id model object or the primary key of this model
297
-     * @throws EE_Error
298
-     * @return int
299
-     */
300
-    protected function _get_model_object_id($model_object_or_id)
301
-    {
302
-        $model_object_id = $model_object_or_id;
303
-        if ($model_object_or_id instanceof EE_Base_Class) {
304
-            $model_object_id = $model_object_or_id->ID();
305
-        }
306
-        if (! $model_object_id) {
307
-            throw new EE_Error(sprintf(
308
-                esc_html__(
309
-                    "Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
310
-                    "event_espresso"
311
-                ),
312
-                $this->get_other_model()->get_this_model_name(),
313
-                $this->get_this_model()->get_this_model_name()
314
-            ));
315
-        }
316
-        return $model_object_id;
317
-    }
318
-
319
-
320
-    /**
321
-     * Gets the SQL string for performing the join between this model and the other model.
322
-     *
323
-     * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
324
-     * @return string of SQL, eg "LEFT JOIN table_name AS table_alias ON this_model_primary_table.pk =
325
-     *                other_model_primary_table.fk" etc
326
-     */
327
-    abstract public function get_join_statement($model_relation_chain);
328
-
329
-
330
-    /**
331
-     * Adds a relationships between the two model objects provided. Each type of relationship handles this differently
332
-     * (EE_Belongs_To is a slight exception, it should more accurately be called set_relation_to(...), as this
333
-     * relationship only allows this model to be related to a single other model of this type)
334
-     *
335
-     * @param       $this_obj_or_id
336
-     * @param       $other_obj_or_id
337
-     * @param array $extra_join_model_fields_n_values
338
-     * @return \EE_Base_Class the EE_Base_Class which was added as a relation. (Convenient if you only pass an ID for
339
-     *                        $other_obj_or_id)
340
-     */
341
-    abstract public function add_relation_to(
342
-        $this_obj_or_id,
343
-        $other_obj_or_id,
344
-        $extra_join_model_fields_n_values = array()
345
-    );
346
-
347
-
348
-    /**
349
-     * Similar to 'add_relation_to(...)', performs the opposite action of removing the relationship between the two
350
-     * model objects
351
-     *
352
-     * @param       $this_obj_or_id
353
-     * @param       $other_obj_or_id
354
-     * @param array $where_query
355
-     * @return bool
356
-     */
357
-    abstract public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array());
358
-
359
-
360
-    /**
361
-     * Removes ALL relation instances for this relation obj
362
-     *
363
-     * @param EE_Base_Class|int $this_obj_or_id
364
-     * @param array             $where_query_param @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
365
-     * @return EE_Base_Class[]
366
-     * @throws \EE_Error
367
-     */
368
-    public function remove_relations($this_obj_or_id, $where_query_param = array())
369
-    {
370
-        $related_things = $this->get_all_related($this_obj_or_id, array($where_query_param));
371
-        $objs_removed   = array();
372
-        foreach ($related_things as $related_thing) {
373
-            $objs_removed[] = $this->remove_relation_to($this_obj_or_id, $related_thing);
374
-        }
375
-        return $objs_removed;
376
-    }
377
-
378
-
379
-    /**
380
-     * If you aren't allowed to delete this model when there are related models across this
381
-     * relation object, return true. Otherwise, if you can delete this model even though
382
-     * related objects exist, returns false.
383
-     *
384
-     * @return boolean
385
-     */
386
-    public function block_delete_if_related_models_exist()
387
-    {
388
-        return $this->_blocking_delete;
389
-    }
390
-
391
-
392
-    /**
393
-     * Gets the error message to show
394
-     *
395
-     * @return string
396
-     */
397
-    public function get_deletion_error_message()
398
-    {
399
-        if ($this->_blocking_delete_error_message) {
400
-            return $this->_blocking_delete_error_message;
401
-        } else {
19
+	/**
20
+	 * The model name of which this relation is a component (ie, the model that called new EE_Model_Relation_Base)
21
+	 *
22
+	 * @var string eg Event, Question_Group, Registration
23
+	 */
24
+	private $_this_model_name;
25
+	/**
26
+	 * The model name pointed to by this relation (ie, the model we want to establish a relationship to)
27
+	 *
28
+	 * @var string eg Event, Question_Group, Registration
29
+	 */
30
+	private $_other_model_name;
31
+
32
+	/**
33
+	 * this is typically used when calling the relation models to make sure they inherit any set timezone from the
34
+	 * initiating model.
35
+	 *
36
+	 * @var string
37
+	 */
38
+	protected $_timezone;
39
+
40
+	/**
41
+	 * If you try to delete "this_model", and there are related "other_models",
42
+	 * and this isn't null, then abandon the deletion and add this warning.
43
+	 * This effectively makes it impossible to delete "this_model" while there are
44
+	 * related "other_models" along this relation.
45
+	 *
46
+	 * @var string (internationalized)
47
+	 */
48
+	protected $_blocking_delete_error_message;
49
+
50
+	protected $_blocking_delete = false;
51
+
52
+	/**
53
+	 * Object representing the relationship between two models. This knows how to join the models,
54
+	 * get related models across the relation, and add-and-remove the relationships.
55
+	 *
56
+	 * @param boolean $block_deletes                 if there are related models across this relation, block (prevent
57
+	 *                                               and add an error) the deletion of this model
58
+	 * @param string  $blocking_delete_error_message a customized error message on blocking deletes instead of the
59
+	 *                                               default
60
+	 */
61
+	public function __construct($block_deletes, $blocking_delete_error_message)
62
+	{
63
+		$this->_blocking_delete               = $block_deletes;
64
+		$this->_blocking_delete_error_message = $blocking_delete_error_message;
65
+	}
66
+
67
+
68
+	/**
69
+	 * @param $this_model_name
70
+	 * @param $other_model_name
71
+	 * @throws EE_Error
72
+	 */
73
+	public function _construct_finalize_set_models($this_model_name, $other_model_name)
74
+	{
75
+		$this->_this_model_name  = $this_model_name;
76
+		$this->_other_model_name = $other_model_name;
77
+		if (is_string($this->_blocking_delete)) {
78
+			throw new EE_Error(sprintf(
79
+				esc_html__(
80
+					"When instantiating the relation of type %s from %s to %s, the \$block_deletes argument should be a boolean, not a string (%s)",
81
+					"event_espresso"
82
+				),
83
+				get_class($this),
84
+				$this_model_name,
85
+				$other_model_name,
86
+				$this->_blocking_delete
87
+			));
88
+		}
89
+	}
90
+
91
+
92
+	/**
93
+	 * Gets the model where this relation is defined.
94
+	 *
95
+	 * @return EEM_Base
96
+	 */
97
+	public function get_this_model()
98
+	{
99
+		return $this->_get_model($this->_this_model_name);
100
+	}
101
+
102
+
103
+	/**
104
+	 * Gets the model which this relation establishes the relation TO (ie,
105
+	 * this relation object was defined on get_this_model(), get_other_model() is the other one)
106
+	 *
107
+	 * @return EEM_Base
108
+	 */
109
+	public function get_other_model()
110
+	{
111
+		return $this->_get_model($this->_other_model_name);
112
+	}
113
+
114
+
115
+	/**
116
+	 * Internally used by get_this_model() and get_other_model()
117
+	 *
118
+	 * @param string $model_name like Event, Question_Group, etc. omit the EEM_
119
+	 * @return EEM_Base
120
+	 */
121
+	protected function _get_model($model_name)
122
+	{
123
+		$modelInstance = EE_Registry::instance()->load_model($model_name);
124
+		$modelInstance->set_timezone($this->_timezone);
125
+		return $modelInstance;
126
+	}
127
+
128
+
129
+	/**
130
+	 * entirely possible that relations may be called from a model and we need to make sure those relations have their
131
+	 * timezone set correctly.
132
+	 *
133
+	 * @param string $timezone timezone to set.
134
+	 */
135
+	public function set_timezone($timezone)
136
+	{
137
+		if ($timezone !== null) {
138
+			$this->_timezone = $timezone;
139
+		}
140
+	}
141
+
142
+
143
+	/**
144
+	 * @param        $other_table
145
+	 * @param        $other_table_alias
146
+	 * @param        $other_table_column
147
+	 * @param        $this_table_alias
148
+	 * @param        $this_table_join_column
149
+	 * @param string $extra_join_sql
150
+	 * @return string
151
+	 */
152
+	protected function _left_join(
153
+		$other_table,
154
+		$other_table_alias,
155
+		$other_table_column,
156
+		$this_table_alias,
157
+		$this_table_join_column,
158
+		$extra_join_sql = ''
159
+	) {
160
+		return " LEFT JOIN " . $other_table . " AS " . $other_table_alias . " ON " . $other_table_alias . "." . $other_table_column . "=" . $this_table_alias . "." . $this_table_join_column . ($extra_join_sql ? " AND $extra_join_sql" : '');
161
+	}
162
+
163
+
164
+	/**
165
+	 * Gets all the model objects of type of other model related to $model_object,
166
+	 * according to this relation. This is the same code for EE_HABTM_Relation and EE_Has_Many_Relation.
167
+	 * For both of those child classes, $model_object must be saved so that it has an ID before querying,
168
+	 * otherwise an error will be thrown. Note: by default we disable default_where_conditions
169
+	 * EE_Belongs_To_Relation doesn't need to be saved before querying.
170
+	 *
171
+	 * @param EE_Base_Class|int $model_object_or_id                      or the primary key of this model
172
+	 * @param array             $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
173
+	 * @param boolean           $values_already_prepared_by_model_object @deprecated since 4.8.1
174
+	 * @return EE_Base_Class[]
175
+	 * @throws \EE_Error
176
+	 */
177
+	public function get_all_related(
178
+		$model_object_or_id,
179
+		$query_params = array(),
180
+		$values_already_prepared_by_model_object = false
181
+	) {
182
+		if ($values_already_prepared_by_model_object !== false) {
183
+			EE_Error::doing_it_wrong(
184
+				'EE_Model_Relation_Base::get_all_related',
185
+				esc_html__('The argument $values_already_prepared_by_model_object is no longer used.', 'event_espresso'),
186
+				'4.8.1'
187
+			);
188
+		}
189
+		$query_params                                      = $this->_disable_default_where_conditions_on_query_param($query_params);
190
+		$query_param_where_this_model_pk                   = $this->get_this_model()->get_this_model_name()
191
+															 . "."
192
+															 . $this->get_this_model()->get_primary_key_field()->get_name();
193
+		$model_object_id                                   = $this->_get_model_object_id($model_object_or_id);
194
+		$query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
195
+		return $this->get_other_model()->get_all($query_params);
196
+	}
197
+
198
+
199
+	/**
200
+	 * Alters the $query_params to disable default where conditions, unless otherwise specified
201
+	 *
202
+	 * @param string $query_params
203
+	 * @return array
204
+	 */
205
+	protected function _disable_default_where_conditions_on_query_param($query_params)
206
+	{
207
+		if (! isset($query_params['default_where_conditions'])) {
208
+			$query_params['default_where_conditions'] = 'none';
209
+		}
210
+		return $query_params;
211
+	}
212
+
213
+
214
+	/**
215
+	 * Deletes the related model objects which meet the query parameters. If no
216
+	 * parameters are specified, then all related model objects will be deleted.
217
+	 * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
218
+	 * model objects will only be soft-deleted.
219
+	 *
220
+	 * @param EE_Base_Class|int|string $model_object_or_id
221
+	 * @param array                    $query_params
222
+	 * @return int of how many related models got deleted
223
+	 * @throws \EE_Error
224
+	 */
225
+	public function delete_all_related($model_object_or_id, $query_params = array())
226
+	{
227
+		// for each thing we would delete,
228
+		$related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
229
+		// determine if it's blocked by anything else before it can be deleted
230
+		$deleted_count = 0;
231
+		foreach ($related_model_objects as $related_model_object) {
232
+			$delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
233
+				$related_model_object,
234
+				$model_object_or_id
235
+			);
236
+			/* @var $model_object_or_id EE_Base_Class */
237
+			if (! $delete_is_blocked) {
238
+				$this->remove_relation_to($model_object_or_id, $related_model_object);
239
+				$related_model_object->delete();
240
+				$deleted_count++;
241
+			}
242
+		}
243
+		return $deleted_count;
244
+	}
245
+
246
+
247
+	/**
248
+	 * Deletes the related model objects which meet the query parameters. If no
249
+	 * parameters are specified, then all related model objects will be deleted.
250
+	 * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
251
+	 * model objects will only be soft-deleted.
252
+	 *
253
+	 * @param EE_Base_Class|int|string $model_object_or_id
254
+	 * @param array                    $query_params
255
+	 * @return int of how many related models got deleted
256
+	 * @throws \EE_Error
257
+	 */
258
+	public function delete_related_permanently($model_object_or_id, $query_params = array())
259
+	{
260
+		// for each thing we would delete,
261
+		$related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
262
+		// determine if it's blocked by anything else before it can be deleted
263
+		$deleted_count = 0;
264
+		foreach ($related_model_objects as $related_model_object) {
265
+			$delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
266
+				$related_model_object,
267
+				$model_object_or_id
268
+			);
269
+			/* @var $model_object_or_id EE_Base_Class */
270
+			if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
271
+				$this->remove_relation_to($model_object_or_id, $related_model_object);
272
+				$deleted_count++;
273
+				if (! $delete_is_blocked) {
274
+					$related_model_object->delete_permanently();
275
+				} else {
276
+					// delete is blocked
277
+					// brent and darren, in this case, wanted to just soft delete it then
278
+					$related_model_object->delete();
279
+				}
280
+			} else {
281
+				// its not a soft-deletable thing anyways. do the normal logic.
282
+				if (! $delete_is_blocked) {
283
+					$this->remove_relation_to($model_object_or_id, $related_model_object);
284
+					$related_model_object->delete();
285
+					$deleted_count++;
286
+				}
287
+			}
288
+		}
289
+		return $deleted_count;
290
+	}
291
+
292
+
293
+	/**
294
+	 * this just returns a model_object_id for incoming item that could be an object or id.
295
+	 *
296
+	 * @param  EE_Base_Class|int $model_object_or_id model object or the primary key of this model
297
+	 * @throws EE_Error
298
+	 * @return int
299
+	 */
300
+	protected function _get_model_object_id($model_object_or_id)
301
+	{
302
+		$model_object_id = $model_object_or_id;
303
+		if ($model_object_or_id instanceof EE_Base_Class) {
304
+			$model_object_id = $model_object_or_id->ID();
305
+		}
306
+		if (! $model_object_id) {
307
+			throw new EE_Error(sprintf(
308
+				esc_html__(
309
+					"Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
310
+					"event_espresso"
311
+				),
312
+				$this->get_other_model()->get_this_model_name(),
313
+				$this->get_this_model()->get_this_model_name()
314
+			));
315
+		}
316
+		return $model_object_id;
317
+	}
318
+
319
+
320
+	/**
321
+	 * Gets the SQL string for performing the join between this model and the other model.
322
+	 *
323
+	 * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
324
+	 * @return string of SQL, eg "LEFT JOIN table_name AS table_alias ON this_model_primary_table.pk =
325
+	 *                other_model_primary_table.fk" etc
326
+	 */
327
+	abstract public function get_join_statement($model_relation_chain);
328
+
329
+
330
+	/**
331
+	 * Adds a relationships between the two model objects provided. Each type of relationship handles this differently
332
+	 * (EE_Belongs_To is a slight exception, it should more accurately be called set_relation_to(...), as this
333
+	 * relationship only allows this model to be related to a single other model of this type)
334
+	 *
335
+	 * @param       $this_obj_or_id
336
+	 * @param       $other_obj_or_id
337
+	 * @param array $extra_join_model_fields_n_values
338
+	 * @return \EE_Base_Class the EE_Base_Class which was added as a relation. (Convenient if you only pass an ID for
339
+	 *                        $other_obj_or_id)
340
+	 */
341
+	abstract public function add_relation_to(
342
+		$this_obj_or_id,
343
+		$other_obj_or_id,
344
+		$extra_join_model_fields_n_values = array()
345
+	);
346
+
347
+
348
+	/**
349
+	 * Similar to 'add_relation_to(...)', performs the opposite action of removing the relationship between the two
350
+	 * model objects
351
+	 *
352
+	 * @param       $this_obj_or_id
353
+	 * @param       $other_obj_or_id
354
+	 * @param array $where_query
355
+	 * @return bool
356
+	 */
357
+	abstract public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array());
358
+
359
+
360
+	/**
361
+	 * Removes ALL relation instances for this relation obj
362
+	 *
363
+	 * @param EE_Base_Class|int $this_obj_or_id
364
+	 * @param array             $where_query_param @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
365
+	 * @return EE_Base_Class[]
366
+	 * @throws \EE_Error
367
+	 */
368
+	public function remove_relations($this_obj_or_id, $where_query_param = array())
369
+	{
370
+		$related_things = $this->get_all_related($this_obj_or_id, array($where_query_param));
371
+		$objs_removed   = array();
372
+		foreach ($related_things as $related_thing) {
373
+			$objs_removed[] = $this->remove_relation_to($this_obj_or_id, $related_thing);
374
+		}
375
+		return $objs_removed;
376
+	}
377
+
378
+
379
+	/**
380
+	 * If you aren't allowed to delete this model when there are related models across this
381
+	 * relation object, return true. Otherwise, if you can delete this model even though
382
+	 * related objects exist, returns false.
383
+	 *
384
+	 * @return boolean
385
+	 */
386
+	public function block_delete_if_related_models_exist()
387
+	{
388
+		return $this->_blocking_delete;
389
+	}
390
+
391
+
392
+	/**
393
+	 * Gets the error message to show
394
+	 *
395
+	 * @return string
396
+	 */
397
+	public function get_deletion_error_message()
398
+	{
399
+		if ($this->_blocking_delete_error_message) {
400
+			return $this->_blocking_delete_error_message;
401
+		} else {
402 402
 //          return sprintf(esc_html__('Cannot delete %1$s when there are related %2$s', "event_espresso"),$this->get_this_model()->item_name(2),$this->get_other_model()->item_name(2));
403
-            return sprintf(
404
-                esc_html__(
405
-                    'This %1$s is currently linked to one or more %2$s records. If this %1$s is incorrect, then please remove it from all %3$s before attempting to delete it.',
406
-                    "event_espresso"
407
-                ),
408
-                $this->get_this_model()->item_name(1),
409
-                $this->get_other_model()->item_name(1),
410
-                $this->get_other_model()->item_name(2)
411
-            );
412
-        }
413
-    }
414
-
415
-    /**
416
-     * Returns whatever is set as the nicename for the object.
417
-     *
418
-     * @return string
419
-     */
420
-    public function getSchemaDescription()
421
-    {
422
-        $description = $this instanceof EE_Belongs_To_Relation
423
-            ? esc_html__('The related %1$s entity to the %2$s.', 'event_espresso')
424
-            : esc_html__('The related %1$s entities to the %2$s.', 'event_espresso');
425
-        return sprintf(
426
-            $description,
427
-            $this->get_other_model()->get_this_model_name(),
428
-            $this->get_this_model()->get_this_model_name()
429
-        );
430
-    }
431
-
432
-    /**
433
-     * Returns whatever is set as the $_schema_type property for the object.
434
-     * Note: this will automatically add 'null' to the schema if the object is_nullable()
435
-     *
436
-     * @return string|array
437
-     */
438
-    public function getSchemaType()
439
-    {
440
-        return $this instanceof EE_Belongs_To_Relation ? 'object' : 'array';
441
-    }
442
-
443
-    /**
444
-     * This is usually present when the $_schema_type property is 'object'.  Any child classes will need to override
445
-     * this method and return the properties for the schema.
446
-     * The reason this is not a property on the class is because there may be filters set on the values for the property
447
-     * that won't be exposed on construct.  For example enum type schemas may have the enum values filtered.
448
-     *
449
-     * @return array
450
-     */
451
-    public function getSchemaProperties()
452
-    {
453
-        return array();
454
-    }
455
-
456
-    /**
457
-     * If a child class has enum values, they should override this method and provide a simple array
458
-     * of the enum values.
459
-     * The reason this is not a property on the class is because there may be filterable enum values that
460
-     * are set on the instantiated object that could be filtered after construct.
461
-     *
462
-     * @return array
463
-     */
464
-    public function getSchemaEnum()
465
-    {
466
-        return array();
467
-    }
468
-
469
-    /**
470
-     * This returns the value of the $_schema_format property on the object.
471
-     *
472
-     * @return string
473
-     */
474
-    public function getSchemaFormat()
475
-    {
476
-        return array();
477
-    }
478
-
479
-    /**
480
-     * This returns the value of the $_schema_readonly property on the object.
481
-     *
482
-     * @return bool
483
-     */
484
-    public function getSchemaReadonly()
485
-    {
486
-        return true;
487
-    }
488
-
489
-    /**
490
-     * This returns elements used to represent this field in the json schema.
491
-     *
492
-     * @link http://json-schema.org/
493
-     * @return array
494
-     */
495
-    public function getSchema()
496
-    {
497
-        $schema = array(
498
-            'description' => $this->getSchemaDescription(),
499
-            'type' => $this->getSchemaType(),
500
-            'relation' => true,
501
-            'relation_type' => get_class($this),
502
-            'readonly' => $this->getSchemaReadonly()
503
-        );
504
-
505
-        if ($this instanceof EE_HABTM_Relation) {
506
-            $schema['joining_model_name'] = $this->get_join_model()->get_this_model_name();
507
-        }
508
-
509
-        if ($this->getSchemaType() === 'array') {
510
-            $schema['items'] = array(
511
-                'type' => 'object'
512
-            );
513
-        }
514
-
515
-        return $schema;
516
-    }
403
+			return sprintf(
404
+				esc_html__(
405
+					'This %1$s is currently linked to one or more %2$s records. If this %1$s is incorrect, then please remove it from all %3$s before attempting to delete it.',
406
+					"event_espresso"
407
+				),
408
+				$this->get_this_model()->item_name(1),
409
+				$this->get_other_model()->item_name(1),
410
+				$this->get_other_model()->item_name(2)
411
+			);
412
+		}
413
+	}
414
+
415
+	/**
416
+	 * Returns whatever is set as the nicename for the object.
417
+	 *
418
+	 * @return string
419
+	 */
420
+	public function getSchemaDescription()
421
+	{
422
+		$description = $this instanceof EE_Belongs_To_Relation
423
+			? esc_html__('The related %1$s entity to the %2$s.', 'event_espresso')
424
+			: esc_html__('The related %1$s entities to the %2$s.', 'event_espresso');
425
+		return sprintf(
426
+			$description,
427
+			$this->get_other_model()->get_this_model_name(),
428
+			$this->get_this_model()->get_this_model_name()
429
+		);
430
+	}
431
+
432
+	/**
433
+	 * Returns whatever is set as the $_schema_type property for the object.
434
+	 * Note: this will automatically add 'null' to the schema if the object is_nullable()
435
+	 *
436
+	 * @return string|array
437
+	 */
438
+	public function getSchemaType()
439
+	{
440
+		return $this instanceof EE_Belongs_To_Relation ? 'object' : 'array';
441
+	}
442
+
443
+	/**
444
+	 * This is usually present when the $_schema_type property is 'object'.  Any child classes will need to override
445
+	 * this method and return the properties for the schema.
446
+	 * The reason this is not a property on the class is because there may be filters set on the values for the property
447
+	 * that won't be exposed on construct.  For example enum type schemas may have the enum values filtered.
448
+	 *
449
+	 * @return array
450
+	 */
451
+	public function getSchemaProperties()
452
+	{
453
+		return array();
454
+	}
455
+
456
+	/**
457
+	 * If a child class has enum values, they should override this method and provide a simple array
458
+	 * of the enum values.
459
+	 * The reason this is not a property on the class is because there may be filterable enum values that
460
+	 * are set on the instantiated object that could be filtered after construct.
461
+	 *
462
+	 * @return array
463
+	 */
464
+	public function getSchemaEnum()
465
+	{
466
+		return array();
467
+	}
468
+
469
+	/**
470
+	 * This returns the value of the $_schema_format property on the object.
471
+	 *
472
+	 * @return string
473
+	 */
474
+	public function getSchemaFormat()
475
+	{
476
+		return array();
477
+	}
478
+
479
+	/**
480
+	 * This returns the value of the $_schema_readonly property on the object.
481
+	 *
482
+	 * @return bool
483
+	 */
484
+	public function getSchemaReadonly()
485
+	{
486
+		return true;
487
+	}
488
+
489
+	/**
490
+	 * This returns elements used to represent this field in the json schema.
491
+	 *
492
+	 * @link http://json-schema.org/
493
+	 * @return array
494
+	 */
495
+	public function getSchema()
496
+	{
497
+		$schema = array(
498
+			'description' => $this->getSchemaDescription(),
499
+			'type' => $this->getSchemaType(),
500
+			'relation' => true,
501
+			'relation_type' => get_class($this),
502
+			'readonly' => $this->getSchemaReadonly()
503
+		);
504
+
505
+		if ($this instanceof EE_HABTM_Relation) {
506
+			$schema['joining_model_name'] = $this->get_join_model()->get_this_model_name();
507
+		}
508
+
509
+		if ($this->getSchemaType() === 'array') {
510
+			$schema['items'] = array(
511
+				'type' => 'object'
512
+			);
513
+		}
514
+
515
+		return $schema;
516
+	}
517 517
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
         $this_table_join_column,
158 158
         $extra_join_sql = ''
159 159
     ) {
160
-        return " LEFT JOIN " . $other_table . " AS " . $other_table_alias . " ON " . $other_table_alias . "." . $other_table_column . "=" . $this_table_alias . "." . $this_table_join_column . ($extra_join_sql ? " AND $extra_join_sql" : '');
160
+        return " LEFT JOIN ".$other_table." AS ".$other_table_alias." ON ".$other_table_alias.".".$other_table_column."=".$this_table_alias.".".$this_table_join_column.($extra_join_sql ? " AND $extra_join_sql" : '');
161 161
     }
162 162
 
163 163
 
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
                                                              . "."
192 192
                                                              . $this->get_this_model()->get_primary_key_field()->get_name();
193 193
         $model_object_id                                   = $this->_get_model_object_id($model_object_or_id);
194
-        $query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
194
+        $query_params[0][$query_param_where_this_model_pk] = $model_object_id;
195 195
         return $this->get_other_model()->get_all($query_params);
196 196
     }
197 197
 
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
      */
205 205
     protected function _disable_default_where_conditions_on_query_param($query_params)
206 206
     {
207
-        if (! isset($query_params['default_where_conditions'])) {
207
+        if ( ! isset($query_params['default_where_conditions'])) {
208 208
             $query_params['default_where_conditions'] = 'none';
209 209
         }
210 210
         return $query_params;
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
                 $model_object_or_id
235 235
             );
236 236
             /* @var $model_object_or_id EE_Base_Class */
237
-            if (! $delete_is_blocked) {
237
+            if ( ! $delete_is_blocked) {
238 238
                 $this->remove_relation_to($model_object_or_id, $related_model_object);
239 239
                 $related_model_object->delete();
240 240
                 $deleted_count++;
@@ -270,7 +270,7 @@  discard block
 block discarded – undo
270 270
             if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
271 271
                 $this->remove_relation_to($model_object_or_id, $related_model_object);
272 272
                 $deleted_count++;
273
-                if (! $delete_is_blocked) {
273
+                if ( ! $delete_is_blocked) {
274 274
                     $related_model_object->delete_permanently();
275 275
                 } else {
276 276
                     // delete is blocked
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
                 }
280 280
             } else {
281 281
                 // its not a soft-deletable thing anyways. do the normal logic.
282
-                if (! $delete_is_blocked) {
282
+                if ( ! $delete_is_blocked) {
283 283
                     $this->remove_relation_to($model_object_or_id, $related_model_object);
284 284
                     $related_model_object->delete();
285 285
                     $deleted_count++;
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
         if ($model_object_or_id instanceof EE_Base_Class) {
304 304
             $model_object_id = $model_object_or_id->ID();
305 305
         }
306
-        if (! $model_object_id) {
306
+        if ( ! $model_object_id) {
307 307
             throw new EE_Error(sprintf(
308 308
                 esc_html__(
309 309
                     "Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
Please login to merge, or discard this patch.