Completed
Branch BUG/11407/workaround-php-datet... (a4e379)
by
unknown
77:22 queued 64:17
created
core/libraries/rest_api/controllers/model/Read.php 2 patches
Indentation   +1347 added lines, -1353 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
 use EEM_CPT_Base;
22 22
 
23 23
 if (! defined('EVENT_ESPRESSO_VERSION')) {
24
-    exit('No direct script access allowed');
24
+	exit('No direct script access allowed');
25 25
 }
26 26
 
27 27
 
@@ -39,1370 +39,1364 @@  discard block
 block discarded – undo
39 39
 
40 40
 
41 41
 
42
-    /**
43
-     * @var CalculatedModelFields
44
-     */
45
-    protected $fields_calculator;
42
+	/**
43
+	 * @var CalculatedModelFields
44
+	 */
45
+	protected $fields_calculator;
46 46
 
47 47
 
48 48
 
49
-    /**
50
-     * Read constructor.
51
-     */
52
-    public function __construct()
53
-    {
54
-        parent::__construct();
55
-        $this->fields_calculator = new CalculatedModelFields();
56
-    }
49
+	/**
50
+	 * Read constructor.
51
+	 */
52
+	public function __construct()
53
+	{
54
+		parent::__construct();
55
+		$this->fields_calculator = new CalculatedModelFields();
56
+	}
57 57
 
58 58
 
59 59
 
60
-    /**
61
-     * Handles requests to get all (or a filtered subset) of entities for a particular model
62
-
63
-     *
60
+	/**
61
+	 * Handles requests to get all (or a filtered subset) of entities for a particular model
62
+	 *
64 63
 *@param WP_REST_Request $request
65
-     * @param string           $version
66
-     * @param string           $model_name
67
-     * @return \WP_REST_Response|WP_Error
68
-     */
69
-    public static function handleRequestGetAll(WP_REST_Request $request, $version, $model_name)
70
-    {
71
-        $controller = new Read();
72
-        try {
73
-            $controller->setRequestedVersion($version);
74
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
75
-                return $controller->sendResponse(
76
-                    new WP_Error(
77
-                        'endpoint_parsing_error',
78
-                        sprintf(
79
-                            __(
80
-                                'There is no model for endpoint %s. Please contact event espresso support',
81
-                                'event_espresso'
82
-                            ),
83
-                            $model_name
84
-                        )
85
-                    )
86
-                );
87
-            }
88
-            return $controller->sendResponse(
89
-                $controller->getEntitiesFromModel(
90
-                    $controller->getModelVersionInfo()->loadModel($model_name),
91
-                    $request
92
-                )
93
-            );
94
-        } catch (Exception $e) {
95
-            return $controller->sendResponse($e);
96
-        }
97
-    }
98
-
99
-
100
-
101
-    /**
102
-     * Prepares and returns schema for any OPTIONS request.
103
-     *
104
-     * @param string $version    The API endpoint version being used.
105
-     * @param string $model_name Something like `Event` or `Registration`
106
-     * @return array
107
-     */
108
-    public static function handleSchemaRequest($version, $model_name)
109
-    {
110
-        $controller = new Read();
111
-        try {
112
-            $controller->setRequestedVersion($version);
113
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
114
-                return array();
115
-            }
116
-            //get the model for this version
117
-            $model = $controller->getModelVersionInfo()->loadModel($model_name);
118
-            $model_schema = new JsonModelSchema($model);
119
-            return $model_schema->getModelSchemaForRelations(
120
-                $controller->getModelVersionInfo()->relationSettings($model),
121
-                $controller->customizeSchemaForRestResponse(
122
-                    $model,
123
-                    $model_schema->getModelSchemaForFields(
124
-                        $controller->getModelVersionInfo()->fieldsOnModelInThisVersion($model),
125
-                        $model_schema->getInitialSchemaStructure()
126
-                    )
127
-                )
128
-            );
129
-        } catch (Exception $e) {
130
-            return array();
131
-        }
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     * This loops through each field in the given schema for the model and does the following:
138
-     * - add any extra fields that are REST API specific and related to existing fields.
139
-     * - transform default values into the correct format for a REST API response.
140
-     *
141
-     * @param EEM_Base $model
142
-     * @param array     $schema
143
-     * @return array  The final schema.
144
-     */
145
-    protected function customizeSchemaForRestResponse(EEM_Base $model, array $schema)
146
-    {
147
-        foreach ($this->getModelVersionInfo()->fieldsOnModelInThisVersion($model) as $field_name => $field) {
148
-            $schema = $this->translateDefaultsForRestResponse(
149
-                $field_name,
150
-                $field,
151
-                $this->maybeAddExtraFieldsToSchema($field_name, $field, $schema)
152
-            );
153
-        }
154
-        return $schema;
155
-    }
156
-
157
-
158
-
159
-    /**
160
-     * This is used to ensure that the 'default' value set in the schema response is formatted correctly for the REST
161
-     * response.
162
-     *
163
-     * @param                      $field_name
164
-     * @param EE_Model_Field_Base $field
165
-     * @param array                $schema
166
-     * @return array
167
-     * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we
168
-     * did, let's know about it ASAP, so let the exception bubble up)
169
-     */
170
-    protected function translateDefaultsForRestResponse($field_name, EE_Model_Field_Base $field, array $schema)
171
-    {
172
-        if (isset($schema['properties'][$field_name]['default'])) {
173
-            if (is_array($schema['properties'][$field_name]['default'])) {
174
-                foreach ($schema['properties'][$field_name]['default'] as $default_key => $default_value) {
175
-                    if ($default_key === 'raw') {
176
-                        $schema['properties'][$field_name]['default'][$default_key] =
177
-                            ModelDataTranslator::prepareFieldValueForJson(
178
-                                $field,
179
-                                $default_value,
180
-                                $this->getModelVersionInfo()->requestedVersion()
181
-                            );
182
-                    }
183
-                }
184
-            } else {
185
-                $schema['properties'][$field_name]['default'] = ModelDataTranslator::prepareFieldValueForJson(
186
-                    $field,
187
-                    $schema['properties'][$field_name]['default'],
188
-                    $this->getModelVersionInfo()->requestedVersion()
189
-                );
190
-            }
191
-        }
192
-        return $schema;
193
-    }
194
-
195
-
196
-
197
-    /**
198
-     * Adds additional fields to the schema
199
-     * The REST API returns a GMT value field for each datetime field in the resource.  Thus the description about this
200
-     * needs to be added to the schema.
201
-     *
202
-     * @param                      $field_name
203
-     * @param EE_Model_Field_Base $field
204
-     * @param array                $schema
205
-     * @return array
206
-     */
207
-    protected function maybeAddExtraFieldsToSchema($field_name, EE_Model_Field_Base $field, array $schema)
208
-    {
209
-        if ($field instanceof EE_Datetime_Field) {
210
-            $schema['properties'][$field_name . '_gmt'] = $field->getSchema();
211
-            //modify the description
212
-            $schema['properties'][$field_name . '_gmt']['description'] = sprintf(
213
-                esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
214
-                wp_specialchars_decode($field->get_nicename(), ENT_QUOTES)
215
-            );
216
-        }
217
-        return $schema;
218
-    }
219
-
220
-
221
-
222
-    /**
223
-     * Used to figure out the route from the request when a `WP_REST_Request` object is not available
224
-     *
225
-     * @return string
226
-     */
227
-    protected function getRouteFromRequest()
228
-    {
229
-        if (isset($GLOBALS['wp'])
230
-            && $GLOBALS['wp'] instanceof \WP
231
-            && isset($GLOBALS['wp']->query_vars['rest_route'])
232
-        ) {
233
-            return $GLOBALS['wp']->query_vars['rest_route'];
234
-        } else {
235
-            return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
236
-        }
237
-    }
238
-
239
-
240
-
241
-    /**
242
-     * Gets a single entity related to the model indicated in the path and its id
243
-
244
-     *
64
+	 * @param string           $version
65
+	 * @param string           $model_name
66
+	 * @return \WP_REST_Response|WP_Error
67
+	 */
68
+	public static function handleRequestGetAll(WP_REST_Request $request, $version, $model_name)
69
+	{
70
+		$controller = new Read();
71
+		try {
72
+			$controller->setRequestedVersion($version);
73
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
74
+				return $controller->sendResponse(
75
+					new WP_Error(
76
+						'endpoint_parsing_error',
77
+						sprintf(
78
+							__(
79
+								'There is no model for endpoint %s. Please contact event espresso support',
80
+								'event_espresso'
81
+							),
82
+							$model_name
83
+						)
84
+					)
85
+				);
86
+			}
87
+			return $controller->sendResponse(
88
+				$controller->getEntitiesFromModel(
89
+					$controller->getModelVersionInfo()->loadModel($model_name),
90
+					$request
91
+				)
92
+			);
93
+		} catch (Exception $e) {
94
+			return $controller->sendResponse($e);
95
+		}
96
+	}
97
+
98
+
99
+
100
+	/**
101
+	 * Prepares and returns schema for any OPTIONS request.
102
+	 *
103
+	 * @param string $version    The API endpoint version being used.
104
+	 * @param string $model_name Something like `Event` or `Registration`
105
+	 * @return array
106
+	 */
107
+	public static function handleSchemaRequest($version, $model_name)
108
+	{
109
+		$controller = new Read();
110
+		try {
111
+			$controller->setRequestedVersion($version);
112
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
113
+				return array();
114
+			}
115
+			//get the model for this version
116
+			$model = $controller->getModelVersionInfo()->loadModel($model_name);
117
+			$model_schema = new JsonModelSchema($model);
118
+			return $model_schema->getModelSchemaForRelations(
119
+				$controller->getModelVersionInfo()->relationSettings($model),
120
+				$controller->customizeSchemaForRestResponse(
121
+					$model,
122
+					$model_schema->getModelSchemaForFields(
123
+						$controller->getModelVersionInfo()->fieldsOnModelInThisVersion($model),
124
+						$model_schema->getInitialSchemaStructure()
125
+					)
126
+				)
127
+			);
128
+		} catch (Exception $e) {
129
+			return array();
130
+		}
131
+	}
132
+
133
+
134
+
135
+	/**
136
+	 * This loops through each field in the given schema for the model and does the following:
137
+	 * - add any extra fields that are REST API specific and related to existing fields.
138
+	 * - transform default values into the correct format for a REST API response.
139
+	 *
140
+	 * @param EEM_Base $model
141
+	 * @param array     $schema
142
+	 * @return array  The final schema.
143
+	 */
144
+	protected function customizeSchemaForRestResponse(EEM_Base $model, array $schema)
145
+	{
146
+		foreach ($this->getModelVersionInfo()->fieldsOnModelInThisVersion($model) as $field_name => $field) {
147
+			$schema = $this->translateDefaultsForRestResponse(
148
+				$field_name,
149
+				$field,
150
+				$this->maybeAddExtraFieldsToSchema($field_name, $field, $schema)
151
+			);
152
+		}
153
+		return $schema;
154
+	}
155
+
156
+
157
+
158
+	/**
159
+	 * This is used to ensure that the 'default' value set in the schema response is formatted correctly for the REST
160
+	 * response.
161
+	 *
162
+	 * @param                      $field_name
163
+	 * @param EE_Model_Field_Base $field
164
+	 * @param array                $schema
165
+	 * @return array
166
+	 * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we
167
+	 * did, let's know about it ASAP, so let the exception bubble up)
168
+	 */
169
+	protected function translateDefaultsForRestResponse($field_name, EE_Model_Field_Base $field, array $schema)
170
+	{
171
+		if (isset($schema['properties'][$field_name]['default'])) {
172
+			if (is_array($schema['properties'][$field_name]['default'])) {
173
+				foreach ($schema['properties'][$field_name]['default'] as $default_key => $default_value) {
174
+					if ($default_key === 'raw') {
175
+						$schema['properties'][$field_name]['default'][$default_key] =
176
+							ModelDataTranslator::prepareFieldValueForJson(
177
+								$field,
178
+								$default_value,
179
+								$this->getModelVersionInfo()->requestedVersion()
180
+							);
181
+					}
182
+				}
183
+			} else {
184
+				$schema['properties'][$field_name]['default'] = ModelDataTranslator::prepareFieldValueForJson(
185
+					$field,
186
+					$schema['properties'][$field_name]['default'],
187
+					$this->getModelVersionInfo()->requestedVersion()
188
+				);
189
+			}
190
+		}
191
+		return $schema;
192
+	}
193
+
194
+
195
+
196
+	/**
197
+	 * Adds additional fields to the schema
198
+	 * The REST API returns a GMT value field for each datetime field in the resource.  Thus the description about this
199
+	 * needs to be added to the schema.
200
+	 *
201
+	 * @param                      $field_name
202
+	 * @param EE_Model_Field_Base $field
203
+	 * @param array                $schema
204
+	 * @return array
205
+	 */
206
+	protected function maybeAddExtraFieldsToSchema($field_name, EE_Model_Field_Base $field, array $schema)
207
+	{
208
+		if ($field instanceof EE_Datetime_Field) {
209
+			$schema['properties'][$field_name . '_gmt'] = $field->getSchema();
210
+			//modify the description
211
+			$schema['properties'][$field_name . '_gmt']['description'] = sprintf(
212
+				esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
213
+				wp_specialchars_decode($field->get_nicename(), ENT_QUOTES)
214
+			);
215
+		}
216
+		return $schema;
217
+	}
218
+
219
+
220
+
221
+	/**
222
+	 * Used to figure out the route from the request when a `WP_REST_Request` object is not available
223
+	 *
224
+	 * @return string
225
+	 */
226
+	protected function getRouteFromRequest()
227
+	{
228
+		if (isset($GLOBALS['wp'])
229
+			&& $GLOBALS['wp'] instanceof \WP
230
+			&& isset($GLOBALS['wp']->query_vars['rest_route'])
231
+		) {
232
+			return $GLOBALS['wp']->query_vars['rest_route'];
233
+		} else {
234
+			return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
235
+		}
236
+	}
237
+
238
+
239
+
240
+	/**
241
+	 * Gets a single entity related to the model indicated in the path and its id
242
+	 *
245 243
 *@param WP_REST_Request $request
246
-     * @param string           $version
247
-     * @param string           $model_name
248
-     * @return \WP_REST_Response|WP_Error
249
-     */
250
-    public static function handleRequestGetOne(WP_REST_Request $request, $version, $model_name)
251
-    {
252
-        $controller = new Read();
253
-        try {
254
-            $controller->setRequestedVersion($version);
255
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
256
-                return $controller->sendResponse(
257
-                    new WP_Error(
258
-                        'endpoint_parsing_error',
259
-                        sprintf(
260
-                            __(
261
-                                'There is no model for endpoint %s. Please contact event espresso support',
262
-                                'event_espresso'
263
-                            ),
264
-                            $model_name
265
-                        )
266
-                    )
267
-                );
268
-            }
269
-            return $controller->sendResponse(
270
-                $controller->getEntityFromModel(
271
-                    $controller->getModelVersionInfo()->loadModel($model_name),
272
-                    $request
273
-                )
274
-            );
275
-        } catch (Exception $e) {
276
-            return $controller->sendResponse($e);
277
-        }
278
-    }
279
-
280
-
281
-
282
-    /**
283
-     * Gets all the related entities (or if its a belongs-to relation just the one)
284
-     * to the item with the given id
285
-
286
-     *
244
+	 * @param string           $version
245
+	 * @param string           $model_name
246
+	 * @return \WP_REST_Response|WP_Error
247
+	 */
248
+	public static function handleRequestGetOne(WP_REST_Request $request, $version, $model_name)
249
+	{
250
+		$controller = new Read();
251
+		try {
252
+			$controller->setRequestedVersion($version);
253
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
254
+				return $controller->sendResponse(
255
+					new WP_Error(
256
+						'endpoint_parsing_error',
257
+						sprintf(
258
+							__(
259
+								'There is no model for endpoint %s. Please contact event espresso support',
260
+								'event_espresso'
261
+							),
262
+							$model_name
263
+						)
264
+					)
265
+				);
266
+			}
267
+			return $controller->sendResponse(
268
+				$controller->getEntityFromModel(
269
+					$controller->getModelVersionInfo()->loadModel($model_name),
270
+					$request
271
+				)
272
+			);
273
+		} catch (Exception $e) {
274
+			return $controller->sendResponse($e);
275
+		}
276
+	}
277
+
278
+
279
+
280
+	/**
281
+	 * Gets all the related entities (or if its a belongs-to relation just the one)
282
+	 * to the item with the given id
283
+	 *
287 284
 *@param WP_REST_Request $request
288
-     * @param string           $version
289
-     * @param string           $model_name
290
-     * @param string           $related_model_name
291
-     * @return \WP_REST_Response|WP_Error
292
-     */
293
-    public static function handleRequestGetRelated(
294
-        WP_REST_Request $request,
295
-        $version,
296
-        $model_name,
297
-        $related_model_name
298
-    ) {
299
-        $controller = new Read();
300
-        try {
301
-            $controller->setRequestedVersion($version);
302
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
303
-                return $controller->sendResponse(
304
-                    new WP_Error(
305
-                        'endpoint_parsing_error',
306
-                        sprintf(
307
-                            __(
308
-                                'There is no model for endpoint %s. Please contact event espresso support',
309
-                                'event_espresso'
310
-                            ),
311
-                            $model_name
312
-                        )
313
-                    )
314
-                );
315
-            }
316
-            $main_model = $controller->getModelVersionInfo()->loadModel($model_name);
317
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($related_model_name)) {
318
-                return $controller->sendResponse(
319
-                    new WP_Error(
320
-                        'endpoint_parsing_error',
321
-                        sprintf(
322
-                            __(
323
-                                'There is no model for endpoint %s. Please contact event espresso support',
324
-                                'event_espresso'
325
-                            ),
326
-                            $related_model_name
327
-                        )
328
-                    )
329
-                );
330
-            }
331
-            return $controller->sendResponse(
332
-                $controller->getEntitiesFromRelation(
333
-                    $request->get_param('id'),
334
-                    $main_model->related_settings_for($related_model_name),
335
-                    $request
336
-                )
337
-            );
338
-        } catch (Exception $e) {
339
-            return $controller->sendResponse($e);
340
-        }
341
-    }
342
-
343
-
344
-
345
-    /**
346
-     * Gets a collection for the given model and filters
347
-
348
-     *
285
+	 * @param string           $version
286
+	 * @param string           $model_name
287
+	 * @param string           $related_model_name
288
+	 * @return \WP_REST_Response|WP_Error
289
+	 */
290
+	public static function handleRequestGetRelated(
291
+		WP_REST_Request $request,
292
+		$version,
293
+		$model_name,
294
+		$related_model_name
295
+	) {
296
+		$controller = new Read();
297
+		try {
298
+			$controller->setRequestedVersion($version);
299
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
300
+				return $controller->sendResponse(
301
+					new WP_Error(
302
+						'endpoint_parsing_error',
303
+						sprintf(
304
+							__(
305
+								'There is no model for endpoint %s. Please contact event espresso support',
306
+								'event_espresso'
307
+							),
308
+							$model_name
309
+						)
310
+					)
311
+				);
312
+			}
313
+			$main_model = $controller->getModelVersionInfo()->loadModel($model_name);
314
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($related_model_name)) {
315
+				return $controller->sendResponse(
316
+					new WP_Error(
317
+						'endpoint_parsing_error',
318
+						sprintf(
319
+							__(
320
+								'There is no model for endpoint %s. Please contact event espresso support',
321
+								'event_espresso'
322
+							),
323
+							$related_model_name
324
+						)
325
+					)
326
+				);
327
+			}
328
+			return $controller->sendResponse(
329
+				$controller->getEntitiesFromRelation(
330
+					$request->get_param('id'),
331
+					$main_model->related_settings_for($related_model_name),
332
+					$request
333
+				)
334
+			);
335
+		} catch (Exception $e) {
336
+			return $controller->sendResponse($e);
337
+		}
338
+	}
339
+
340
+
341
+
342
+	/**
343
+	 * Gets a collection for the given model and filters
344
+	 *
349 345
 *@param EEM_Base        $model
350
-     * @param WP_REST_Request $request
351
-     * @return array|WP_Error
352
-     */
353
-    public function getEntitiesFromModel($model, $request)
354
-    {
355
-        $query_params = $this->createModelQueryParams($model, $request->get_params());
356
-        if (! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) {
357
-            $model_name_plural = EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
358
-            return new WP_Error(
359
-                sprintf('rest_%s_cannot_list', $model_name_plural),
360
-                sprintf(
361
-                    __('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
362
-                    $model_name_plural,
363
-                    Capabilities::getMissingPermissionsString($model, $query_params['caps'])
364
-                ),
365
-                array('status' => 403)
366
-            );
367
-        }
368
-        if (! $request->get_header('no_rest_headers')) {
369
-            $this->setHeadersFromQueryParams($model, $query_params);
370
-        }
371
-        /** @type array $results */
372
-        $results = $model->get_all_wpdb_results($query_params);
373
-        $nice_results = array();
374
-        foreach ($results as $result) {
375
-            $nice_results[] = $this->createEntityFromWpdbResult(
376
-                $model,
377
-                $result,
378
-                $request
379
-            );
380
-        }
381
-        return $nice_results;
382
-    }
383
-
384
-
385
-
386
-    /**
387
-     * Gets the collection for given relation object
388
-     * The same as Read::get_entities_from_model(), except if the relation
389
-     * is a HABTM relation, in which case it merges any non-foreign-key fields from
390
-     * the join-model-object into the results
391
-     *
392
-     * @param array                   $primary_model_query_params query params for finding the item from which
393
-     *                                                            relations will be based
394
-     * @param \EE_Model_Relation_Base $relation
395
-     * @param WP_REST_Request        $request
396
-     * @return WP_Error|array
397
-     * @throws RestException
398
-     */
399
-    protected function getEntitiesFromRelationUsingModelQueryParams($primary_model_query_params, $relation, $request)
400
-    {
401
-        $context = $this->validateContext($request->get_param('caps'));
402
-        $model = $relation->get_this_model();
403
-        $related_model = $relation->get_other_model();
404
-        if (! isset($primary_model_query_params[0])) {
405
-            $primary_model_query_params[0] = array();
406
-        }
407
-        //check if they can access the 1st model object
408
-        $primary_model_query_params = array(
409
-            0       => $primary_model_query_params[0],
410
-            'limit' => 1,
411
-        );
412
-        if ($model instanceof \EEM_Soft_Delete_Base) {
413
-            $primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included(
414
-                $primary_model_query_params
415
-            );
416
-        }
417
-        $restricted_query_params = $primary_model_query_params;
418
-        $restricted_query_params['caps'] = $context;
419
-        $this->setDebugInfo('main model query params', $restricted_query_params);
420
-        $this->setDebugInfo('missing caps', Capabilities::getMissingPermissionsString($related_model, $context));
421
-        if (! (
422
-            Capabilities::currentUserHasPartialAccessTo($related_model, $context)
423
-            && $model->exists($restricted_query_params)
424
-        )
425
-        ) {
426
-            if ($relation instanceof EE_Belongs_To_Relation) {
427
-                $related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
428
-            } else {
429
-                $related_model_name_maybe_plural = EEH_Inflector::pluralize_and_lower(
430
-                    $related_model->get_this_model_name()
431
-                );
432
-            }
433
-            return new WP_Error(
434
-                sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
435
-                sprintf(
436
-                    __(
437
-                        'Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
438
-                        'event_espresso'
439
-                    ),
440
-                    $related_model_name_maybe_plural,
441
-                    $relation->get_this_model()->get_this_model_name(),
442
-                    implode(
443
-                        ',',
444
-                        array_keys(
445
-                            Capabilities::getMissingPermissions($related_model, $context)
446
-                        )
447
-                    )
448
-                ),
449
-                array('status' => 403)
450
-            );
451
-        }
452
-        $query_params = $this->createModelQueryParams($relation->get_other_model(), $request->get_params());
453
-        foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
454
-            $query_params[0][$relation->get_this_model()->get_this_model_name()
455
-                             . '.'
456
-                             . $where_condition_key] = $where_condition_value;
457
-        }
458
-        $query_params['default_where_conditions'] = 'none';
459
-        $query_params['caps'] = $context;
460
-        if (! $request->get_header('no_rest_headers')) {
461
-            $this->setHeadersFromQueryParams($relation->get_other_model(), $query_params);
462
-        }
463
-        /** @type array $results */
464
-        $results = $relation->get_other_model()->get_all_wpdb_results($query_params);
465
-        $nice_results = array();
466
-        foreach ($results as $result) {
467
-            $nice_result = $this->createEntityFromWpdbResult(
468
-                $relation->get_other_model(),
469
-                $result,
470
-                $request
471
-            );
472
-            if ($relation instanceof \EE_HABTM_Relation) {
473
-                //put the unusual stuff (properties from the HABTM relation) first, and make sure
474
-                //if there are conflicts we prefer the properties from the main model
475
-                $join_model_result = $this->createEntityFromWpdbResult(
476
-                    $relation->get_join_model(),
477
-                    $result,
478
-                    $request
479
-                );
480
-                $joined_result = array_merge($nice_result, $join_model_result);
481
-                //but keep the meta stuff from the main model
482
-                if (isset($nice_result['meta'])) {
483
-                    $joined_result['meta'] = $nice_result['meta'];
484
-                }
485
-                $nice_result = $joined_result;
486
-            }
487
-            $nice_results[] = $nice_result;
488
-        }
489
-        if ($relation instanceof EE_Belongs_To_Relation) {
490
-            return array_shift($nice_results);
491
-        } else {
492
-            return $nice_results;
493
-        }
494
-    }
495
-
496
-
497
-
498
-    /**
499
-     * Gets the collection for given relation object
500
-     * The same as Read::get_entities_from_model(), except if the relation
501
-     * is a HABTM relation, in which case it merges any non-foreign-key fields from
502
-     * the join-model-object into the results
503
-
504
-     *
346
+	 * @param WP_REST_Request $request
347
+	 * @return array|WP_Error
348
+	 */
349
+	public function getEntitiesFromModel($model, $request)
350
+	{
351
+		$query_params = $this->createModelQueryParams($model, $request->get_params());
352
+		if (! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) {
353
+			$model_name_plural = EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
354
+			return new WP_Error(
355
+				sprintf('rest_%s_cannot_list', $model_name_plural),
356
+				sprintf(
357
+					__('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
358
+					$model_name_plural,
359
+					Capabilities::getMissingPermissionsString($model, $query_params['caps'])
360
+				),
361
+				array('status' => 403)
362
+			);
363
+		}
364
+		if (! $request->get_header('no_rest_headers')) {
365
+			$this->setHeadersFromQueryParams($model, $query_params);
366
+		}
367
+		/** @type array $results */
368
+		$results = $model->get_all_wpdb_results($query_params);
369
+		$nice_results = array();
370
+		foreach ($results as $result) {
371
+			$nice_results[] = $this->createEntityFromWpdbResult(
372
+				$model,
373
+				$result,
374
+				$request
375
+			);
376
+		}
377
+		return $nice_results;
378
+	}
379
+
380
+
381
+
382
+	/**
383
+	 * Gets the collection for given relation object
384
+	 * The same as Read::get_entities_from_model(), except if the relation
385
+	 * is a HABTM relation, in which case it merges any non-foreign-key fields from
386
+	 * the join-model-object into the results
387
+	 *
388
+	 * @param array                   $primary_model_query_params query params for finding the item from which
389
+	 *                                                            relations will be based
390
+	 * @param \EE_Model_Relation_Base $relation
391
+	 * @param WP_REST_Request        $request
392
+	 * @return WP_Error|array
393
+	 * @throws RestException
394
+	 */
395
+	protected function getEntitiesFromRelationUsingModelQueryParams($primary_model_query_params, $relation, $request)
396
+	{
397
+		$context = $this->validateContext($request->get_param('caps'));
398
+		$model = $relation->get_this_model();
399
+		$related_model = $relation->get_other_model();
400
+		if (! isset($primary_model_query_params[0])) {
401
+			$primary_model_query_params[0] = array();
402
+		}
403
+		//check if they can access the 1st model object
404
+		$primary_model_query_params = array(
405
+			0       => $primary_model_query_params[0],
406
+			'limit' => 1,
407
+		);
408
+		if ($model instanceof \EEM_Soft_Delete_Base) {
409
+			$primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included(
410
+				$primary_model_query_params
411
+			);
412
+		}
413
+		$restricted_query_params = $primary_model_query_params;
414
+		$restricted_query_params['caps'] = $context;
415
+		$this->setDebugInfo('main model query params', $restricted_query_params);
416
+		$this->setDebugInfo('missing caps', Capabilities::getMissingPermissionsString($related_model, $context));
417
+		if (! (
418
+			Capabilities::currentUserHasPartialAccessTo($related_model, $context)
419
+			&& $model->exists($restricted_query_params)
420
+		)
421
+		) {
422
+			if ($relation instanceof EE_Belongs_To_Relation) {
423
+				$related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
424
+			} else {
425
+				$related_model_name_maybe_plural = EEH_Inflector::pluralize_and_lower(
426
+					$related_model->get_this_model_name()
427
+				);
428
+			}
429
+			return new WP_Error(
430
+				sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
431
+				sprintf(
432
+					__(
433
+						'Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
434
+						'event_espresso'
435
+					),
436
+					$related_model_name_maybe_plural,
437
+					$relation->get_this_model()->get_this_model_name(),
438
+					implode(
439
+						',',
440
+						array_keys(
441
+							Capabilities::getMissingPermissions($related_model, $context)
442
+						)
443
+					)
444
+				),
445
+				array('status' => 403)
446
+			);
447
+		}
448
+		$query_params = $this->createModelQueryParams($relation->get_other_model(), $request->get_params());
449
+		foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
450
+			$query_params[0][$relation->get_this_model()->get_this_model_name()
451
+							 . '.'
452
+							 . $where_condition_key] = $where_condition_value;
453
+		}
454
+		$query_params['default_where_conditions'] = 'none';
455
+		$query_params['caps'] = $context;
456
+		if (! $request->get_header('no_rest_headers')) {
457
+			$this->setHeadersFromQueryParams($relation->get_other_model(), $query_params);
458
+		}
459
+		/** @type array $results */
460
+		$results = $relation->get_other_model()->get_all_wpdb_results($query_params);
461
+		$nice_results = array();
462
+		foreach ($results as $result) {
463
+			$nice_result = $this->createEntityFromWpdbResult(
464
+				$relation->get_other_model(),
465
+				$result,
466
+				$request
467
+			);
468
+			if ($relation instanceof \EE_HABTM_Relation) {
469
+				//put the unusual stuff (properties from the HABTM relation) first, and make sure
470
+				//if there are conflicts we prefer the properties from the main model
471
+				$join_model_result = $this->createEntityFromWpdbResult(
472
+					$relation->get_join_model(),
473
+					$result,
474
+					$request
475
+				);
476
+				$joined_result = array_merge($nice_result, $join_model_result);
477
+				//but keep the meta stuff from the main model
478
+				if (isset($nice_result['meta'])) {
479
+					$joined_result['meta'] = $nice_result['meta'];
480
+				}
481
+				$nice_result = $joined_result;
482
+			}
483
+			$nice_results[] = $nice_result;
484
+		}
485
+		if ($relation instanceof EE_Belongs_To_Relation) {
486
+			return array_shift($nice_results);
487
+		} else {
488
+			return $nice_results;
489
+		}
490
+	}
491
+
492
+
493
+
494
+	/**
495
+	 * Gets the collection for given relation object
496
+	 * The same as Read::get_entities_from_model(), except if the relation
497
+	 * is a HABTM relation, in which case it merges any non-foreign-key fields from
498
+	 * the join-model-object into the results
499
+	 *
505 500
 *@param string                  $id the ID of the thing we are fetching related stuff from
506
-     * @param \EE_Model_Relation_Base $relation
507
-     * @param WP_REST_Request        $request
508
-     * @return array|WP_Error
509
-     * @throws EE_Error
510
-     */
511
-    public function getEntitiesFromRelation($id, $relation, $request)
512
-    {
513
-        if (! $relation->get_this_model()->has_primary_key_field()) {
514
-            throw new EE_Error(
515
-                sprintf(
516
-                    __(
517
-                        // @codingStandardsIgnoreStart
518
-                        'Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
519
-                        // @codingStandardsIgnoreEnd
520
-                        'event_espresso'
521
-                    ),
522
-                    $relation->get_this_model()->get_this_model_name()
523
-                )
524
-            );
525
-        }
526
-        return $this->getEntitiesFromRelationUsingModelQueryParams(
527
-            array(
528
-                array(
529
-                    $relation->get_this_model()->primary_key_name() => $id,
530
-                ),
531
-            ),
532
-            $relation,
533
-            $request
534
-        );
535
-    }
536
-
537
-
538
-
539
-    /**
540
-     * Sets the headers that are based on the model and query params,
541
-     * like the total records. This should only be called on the original request
542
-     * from the client, not on subsequent internal
543
-     *
544
-     * @param EEM_Base $model
545
-     * @param array     $query_params
546
-     * @return void
547
-     */
548
-    protected function setHeadersFromQueryParams($model, $query_params)
549
-    {
550
-        $this->setDebugInfo('model query params', $query_params);
551
-        $this->setDebugInfo(
552
-            'missing caps',
553
-            Capabilities::getMissingPermissionsString($model, $query_params['caps'])
554
-        );
555
-        //normally the limit to a 2-part array, where the 2nd item is the limit
556
-        if (! isset($query_params['limit'])) {
557
-            $query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
558
-        }
559
-        if (is_array($query_params['limit'])) {
560
-            $limit_parts = $query_params['limit'];
561
-        } else {
562
-            $limit_parts = explode(',', $query_params['limit']);
563
-            if (count($limit_parts) == 1) {
564
-                $limit_parts = array(0, $limit_parts[0]);
565
-            }
566
-        }
567
-        //remove the group by and having parts of the query, as those will
568
-        //make the sql query return an array of values, instead of just a single value
569
-        unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
570
-        $count = $model->count($query_params, null, true);
571
-        $pages = $count / $limit_parts[1];
572
-        $this->setResponseHeader('Total', $count, false);
573
-        $this->setResponseHeader('PageSize', $limit_parts[1], false);
574
-        $this->setResponseHeader('TotalPages', ceil($pages), false);
575
-    }
576
-
577
-
578
-
579
-    /**
580
-     * Changes database results into REST API entities
581
-     *
582
-     * @param EEM_Base        $model
583
-     * @param array            $db_row     like results from $wpdb->get_results()
584
-     * @param WP_REST_Request $rest_request
585
-     * @param string           $deprecated no longer used
586
-     * @return array ready for being converted into json for sending to client
587
-     */
588
-    public function createEntityFromWpdbResult($model, $db_row, $rest_request, $deprecated = null)
589
-    {
590
-        if (! $rest_request instanceof WP_REST_Request) {
591
-            //ok so this was called in the old style, where the 3rd arg was
592
-            //$include, and the 4th arg was $context
593
-            //now setup the request just to avoid fatal errors, although we won't be able
594
-            //to truly make use of it because it's kinda devoid of info
595
-            $rest_request = new WP_REST_Request();
596
-            $rest_request->set_param('include', $rest_request);
597
-            $rest_request->set_param('caps', $deprecated);
598
-        }
599
-        if ($rest_request->get_param('caps') == null) {
600
-            $rest_request->set_param('caps', EEM_Base::caps_read);
601
-        }
602
-        $entity_array = $this->createBareEntityFromWpdbResults($model, $db_row);
603
-        $entity_array = $this->addExtraFields($model, $db_row, $entity_array);
604
-        $entity_array['_links'] = $this->getEntityLinks($model, $db_row, $entity_array);
605
-        $entity_array['_calculated_fields'] = $this->getEntityCalculations($model, $db_row, $rest_request);
606
-        $entity_array = apply_filters(
607
-            'FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models',
608
-            $entity_array,
609
-            $model,
610
-            $rest_request->get_param('caps'),
611
-            $rest_request,
612
-            $this
613
-        );
614
-        $entity_array = $this->includeRequestedModels($model, $rest_request, $entity_array, $db_row);
615
-        $entity_array = apply_filters(
616
-            'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
617
-            $entity_array,
618
-            $model,
619
-            $rest_request->get_param('caps'),
620
-            $rest_request,
621
-            $this
622
-        );
623
-        $result_without_inaccessible_fields = Capabilities::filterOutInaccessibleEntityFields(
624
-            $entity_array,
625
-            $model,
626
-            $rest_request->get_param('caps'),
627
-            $this->getModelVersionInfo(),
628
-            $model->get_index_primary_key_string(
629
-                $model->deduce_fields_n_values_from_cols_n_values($db_row)
630
-            )
631
-        );
632
-        $this->setDebugInfo(
633
-            'inaccessible fields',
634
-            array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
635
-        );
636
-        return apply_filters(
637
-            'FHEE__Read__create_entity_from_wpdb_results__entity_return',
638
-            $result_without_inaccessible_fields,
639
-            $model,
640
-            $rest_request->get_param('caps')
641
-        );
642
-    }
643
-
644
-
645
-
646
-    /**
647
-     * Creates a REST entity array (JSON object we're going to return in the response, but
648
-     * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
649
-     * from $wpdb->get_row( $sql, ARRAY_A)
650
-     *
651
-     * @param EEM_Base $model
652
-     * @param array     $db_row
653
-     * @return array entity mostly ready for converting to JSON and sending in the response
654
-     *
655
-     */
656
-    protected function createBareEntityFromWpdbResults(EEM_Base $model, $db_row)
657
-    {
658
-        $result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
659
-        $result = array_intersect_key(
660
-            $result,
661
-            $this->getModelVersionInfo()->fieldsOnModelInThisVersion($model)
662
-        );
663
-        //if this is a CPT, we need to set the global $post to it,
664
-        //otherwise shortcodes etc won't work properly while rendering it
665
-        if ($model instanceof \EEM_CPT_Base) {
666
-            $do_chevy_shuffle = true;
667
-        } else {
668
-            $do_chevy_shuffle = false;
669
-        }
670
-        if ($do_chevy_shuffle) {
671
-            global $post;
672
-            $old_post = $post;
673
-            $post = get_post($result[$model->primary_key_name()]);
674
-            if (! $post instanceof \WP_Post) {
675
-                //well that's weird, because $result is what we JUST fetched from the database
676
-                throw new RestException(
677
-                    'error_fetching_post_from_database_results',
678
-                    esc_html__(
679
-                        'An item was retrieved from the database but it\'s not a WP_Post like it should be.',
680
-                        'event_espresso'
681
-                    )
682
-                );
683
-            }
684
-            $model_object_classname = 'EE_' . $model->get_this_model_name();
685
-            $post->{$model_object_classname} = \EE_Registry::instance()->load_class(
686
-                $model_object_classname,
687
-                $result,
688
-                false,
689
-                false
690
-            );
691
-        }
692
-        foreach ($result as $field_name => $field_value) {
693
-            $field_obj = $model->field_settings_for($field_name);
694
-            if ($this->isSubclassOfOne($field_obj, $this->getModelVersionInfo()->fieldsIgnored())) {
695
-                unset($result[$field_name]);
696
-            } elseif ($this->isSubclassOfOne(
697
-                $field_obj,
698
-                $this->getModelVersionInfo()->fieldsThatHaveRenderedFormat()
699
-            )
700
-            ) {
701
-                $result[$field_name] = array(
702
-                    'raw'      => $this->prepareFieldObjValueForJson($field_obj, $field_value),
703
-                    'rendered' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
704
-                );
705
-            } elseif ($this->isSubclassOfOne(
706
-                $field_obj,
707
-                $this->getModelVersionInfo()->fieldsThatHavePrettyFormat()
708
-            )
709
-            ) {
710
-                $result[$field_name] = array(
711
-                    'raw'    => $this->prepareFieldObjValueForJson($field_obj, $field_value),
712
-                    'pretty' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
713
-                );
714
-            } elseif ($field_obj instanceof \EE_Datetime_Field) {
715
-                $field_value = $field_obj->prepare_for_set_from_db($field_value);
716
-                $timezone = $field_value->getTimezone();
717
-                $field_value->setTimezone(new \DateTimeZone('UTC'));
718
-                // workaround for php datetime bug
719
-                // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
720
-                $field_value->getTimestamp();
721
-                $result[$field_name . '_gmt'] = ModelDataTranslator::prepareFieldValuesForJson(
722
-                    $field_obj,
723
-                    $field_value,
724
-                    $this->getModelVersionInfo()->requestedVersion()
725
-                );
726
-                $field_value->setTimezone($timezone);
727
-                // workaround for php datetime bug
728
-                // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
729
-                $field_value->getTimestamp();
730
-                $result[$field_name] = ModelDataTranslator::prepareFieldValuesForJson(
731
-                    $field_obj,
732
-                    $field_value,
733
-                    $this->getModelVersionInfo()->requestedVersion()
734
-                );
735
-            } else {
736
-                $result[$field_name] = $this->prepareFieldObjValueForJson($field_obj, $field_value);
737
-            }
738
-        }
739
-        if ($do_chevy_shuffle) {
740
-            $post = $old_post;
741
-        }
742
-        return $result;
743
-    }
744
-
745
-
746
-
747
-    /**
748
-     * Takes a value all the way from the DB representation, to the model object's representation, to the
749
-     * user-facing PHP representation, to the REST API representation. (Assumes you've already taken from the DB
750
-     * representation using $field_obj->prepare_for_set_from_db())
751
-     *
752
-     * @param EE_Model_Field_Base $field_obj
753
-     * @param mixed $value as it's stored on a model object
754
-     * @param string $format valid values are 'normal' (default), 'pretty', 'datetime_obj'
755
-     * @return mixed
756
-     * @throws ObjectDetectedException if $value contains a PHP object
757
-     */
758
-    protected function prepareFieldObjValueForJson(EE_Model_Field_Base $field_obj, $value, $format = 'normal')
759
-    {
760
-        $value = $field_obj->prepare_for_set_from_db($value);
761
-        switch ($format) {
762
-            case 'pretty':
763
-                $value = $field_obj->prepare_for_pretty_echoing($value);
764
-                break;
765
-            case 'normal':
766
-            default:
767
-                $value = $field_obj->prepare_for_get($value);
768
-                break;
769
-        }
770
-        return ModelDataTranslator::prepareFieldValuesForJson(
771
-            $field_obj,
772
-            $value,
773
-            $this->getModelVersionInfo()->requestedVersion()
774
-        );
775
-    }
776
-
777
-
778
-
779
-    /**
780
-     * Adds a few extra fields to the entity response
781
-     *
782
-     * @param EEM_Base $model
783
-     * @param array     $db_row
784
-     * @param array     $entity_array
785
-     * @return array modified entity
786
-     */
787
-    protected function addExtraFields(EEM_Base $model, $db_row, $entity_array)
788
-    {
789
-        if ($model instanceof EEM_CPT_Base) {
790
-            $entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
791
-        }
792
-        return $entity_array;
793
-    }
794
-
795
-
796
-
797
-    /**
798
-     * Gets links we want to add to the response
799
-     *
800
-     * @global \WP_REST_Server $wp_rest_server
801
-     * @param EEM_Base        $model
802
-     * @param array            $db_row
803
-     * @param array            $entity_array
804
-     * @return array the _links item in the entity
805
-     */
806
-    protected function getEntityLinks($model, $db_row, $entity_array)
807
-    {
808
-        //add basic links
809
-        $links = array();
810
-        if ($model->has_primary_key_field()) {
811
-            $links['self'] = array(
812
-                array(
813
-                    'href' => $this->getVersionedLinkTo(
814
-                        EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
815
-                        . '/'
816
-                        . $entity_array[$model->primary_key_name()]
817
-                    ),
818
-                ),
819
-            );
820
-        }
821
-        $links['collection'] = array(
822
-            array(
823
-                'href' => $this->getVersionedLinkTo(
824
-                    EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
825
-                ),
826
-            ),
827
-        );
828
-        //add links to related models
829
-        if ($model->has_primary_key_field()) {
830
-            foreach ($this->getModelVersionInfo()->relationSettings($model) as $relation_name => $relation_obj) {
831
-                $related_model_part = Read::getRelatedEntityName($relation_name, $relation_obj);
832
-                $links[EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
833
-                    array(
834
-                        'href'   => $this->getVersionedLinkTo(
835
-                            EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
836
-                            . '/'
837
-                            . $entity_array[$model->primary_key_name()]
838
-                            . '/'
839
-                            . $related_model_part
840
-                        ),
841
-                        'single' => $relation_obj instanceof EE_Belongs_To_Relation ? true : false,
842
-                    ),
843
-                );
844
-            }
845
-        }
846
-        return $links;
847
-    }
848
-
849
-
850
-
851
-    /**
852
-     * Adds the included models indicated in the request to the entity provided
853
-     *
854
-     * @param EEM_Base        $model
855
-     * @param WP_REST_Request $rest_request
856
-     * @param array            $entity_array
857
-     * @param array            $db_row
858
-     * @return array the modified entity
859
-     */
860
-    protected function includeRequestedModels(
861
-        EEM_Base $model,
862
-        WP_REST_Request $rest_request,
863
-        $entity_array,
864
-        $db_row = array()
865
-    ) {
866
-        //if $db_row not included, hope the entity array has what we need
867
-        if (! $db_row) {
868
-            $db_row = $entity_array;
869
-        }
870
-        $includes_for_this_model = $this->explodeAndGetItemsPrefixedWith($rest_request->get_param('include'), '');
871
-        $includes_for_this_model = $this->removeModelNamesFromArray($includes_for_this_model);
872
-        //if they passed in * or didn't specify any includes, return everything
873
-        if (! in_array('*', $includes_for_this_model)
874
-            && ! empty($includes_for_this_model)
875
-        ) {
876
-            if ($model->has_primary_key_field()) {
877
-                //always include the primary key. ya just gotta know that at least
878
-                $includes_for_this_model[] = $model->primary_key_name();
879
-            }
880
-            if ($this->explodeAndGetItemsPrefixedWith($rest_request->get_param('calculate'), '')) {
881
-                $includes_for_this_model[] = '_calculated_fields';
882
-            }
883
-            $entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
884
-        }
885
-        $relation_settings = $this->getModelVersionInfo()->relationSettings($model);
886
-        foreach ($relation_settings as $relation_name => $relation_obj) {
887
-            $related_fields_to_include = $this->explodeAndGetItemsPrefixedWith(
888
-                $rest_request->get_param('include'),
889
-                $relation_name
890
-            );
891
-            $related_fields_to_calculate = $this->explodeAndGetItemsPrefixedWith(
892
-                $rest_request->get_param('calculate'),
893
-                $relation_name
894
-            );
895
-            //did they specify they wanted to include a related model, or
896
-            //specific fields from a related model?
897
-            //or did they specify to calculate a field from a related model?
898
-            if ($related_fields_to_include || $related_fields_to_calculate) {
899
-                //if so, we should include at least some part of the related model
900
-                $pretend_related_request = new WP_REST_Request();
901
-                $pretend_related_request->set_query_params(
902
-                    array(
903
-                        'caps'      => $rest_request->get_param('caps'),
904
-                        'include'   => $related_fields_to_include,
905
-                        'calculate' => $related_fields_to_calculate,
906
-                    )
907
-                );
908
-                $pretend_related_request->add_header('no_rest_headers', true);
909
-                $primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
910
-                    $model->get_index_primary_key_string(
911
-                        $model->deduce_fields_n_values_from_cols_n_values($db_row)
912
-                    )
913
-                );
914
-                $related_results = $this->getEntitiesFromRelationUsingModelQueryParams(
915
-                    $primary_model_query_params,
916
-                    $relation_obj,
917
-                    $pretend_related_request
918
-                );
919
-                $entity_array[Read::getRelatedEntityName($relation_name, $relation_obj)] = $related_results
920
-                                                                                           instanceof
921
-                                                                                           WP_Error
922
-                    ? null
923
-                    : $related_results;
924
-            }
925
-        }
926
-        return $entity_array;
927
-    }
928
-
929
-
930
-
931
-    /**
932
-     * Returns a new array with all the names of models removed. Eg
933
-     * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
934
-     *
935
-     * @param array $arr
936
-     * @return array
937
-     */
938
-    private function removeModelNamesFromArray($arr)
939
-    {
940
-        return array_diff($arr, array_keys(EE_Registry::instance()->non_abstract_db_models));
941
-    }
942
-
943
-
944
-
945
-    /**
946
-     * Gets the calculated fields for the response
947
-     *
948
-     * @param EEM_Base        $model
949
-     * @param array            $wpdb_row
950
-     * @param WP_REST_Request $rest_request
951
-     * @return \stdClass the _calculations item in the entity
952
-     * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we
953
-     * did, let's know about it ASAP, so let the exception bubble up)
954
-     */
955
-    protected function getEntityCalculations($model, $wpdb_row, $rest_request)
956
-    {
957
-        $calculated_fields = $this->explodeAndGetItemsPrefixedWith(
958
-            $rest_request->get_param('calculate'),
959
-            ''
960
-        );
961
-        //note: setting calculate=* doesn't do anything
962
-        $calculated_fields_to_return = new \stdClass();
963
-        foreach ($calculated_fields as $field_to_calculate) {
964
-            try {
965
-                $calculated_fields_to_return->$field_to_calculate = ModelDataTranslator::prepareFieldValueForJson(
966
-                    null,
967
-                    $this->fields_calculator->retrieveCalculatedFieldValue(
968
-                        $model,
969
-                        $field_to_calculate,
970
-                        $wpdb_row,
971
-                        $rest_request,
972
-                        $this
973
-                    ),
974
-                    $this->getModelVersionInfo()->requestedVersion()
975
-                );
976
-            } catch (RestException $e) {
977
-                //if we don't have permission to read it, just leave it out. but let devs know about the problem
978
-                $this->setResponseHeader(
979
-                    'Notices-Field-Calculation-Errors['
980
-                    . $e->getStringCode()
981
-                    . ']['
982
-                    . $model->get_this_model_name()
983
-                    . ']['
984
-                    . $field_to_calculate
985
-                    . ']',
986
-                    $e->getMessage(),
987
-                    true
988
-                );
989
-            }
990
-        }
991
-        return $calculated_fields_to_return;
992
-    }
993
-
994
-
995
-
996
-    /**
997
-     * Gets the full URL to the resource, taking the requested version into account
998
-     *
999
-     * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
1000
-     * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
1001
-     */
1002
-    public function getVersionedLinkTo($link_part_after_version_and_slash)
1003
-    {
1004
-        return rest_url(
1005
-            EED_Core_Rest_Api::get_versioned_route_to(
1006
-                $link_part_after_version_and_slash,
1007
-                $this->getModelVersionInfo()->requestedVersion()
1008
-            )
1009
-        );
1010
-    }
1011
-
1012
-
1013
-
1014
-    /**
1015
-     * Gets the correct lowercase name for the relation in the API according
1016
-     * to the relation's type
1017
-     *
1018
-     * @param string                  $relation_name
1019
-     * @param \EE_Model_Relation_Base $relation_obj
1020
-     * @return string
1021
-     */
1022
-    public static function getRelatedEntityName($relation_name, $relation_obj)
1023
-    {
1024
-        if ($relation_obj instanceof EE_Belongs_To_Relation) {
1025
-            return strtolower($relation_name);
1026
-        } else {
1027
-            return EEH_Inflector::pluralize_and_lower($relation_name);
1028
-        }
1029
-    }
1030
-
1031
-
1032
-
1033
-    /**
1034
-     * Gets the one model object with the specified id for the specified model
1035
-     *
1036
-     * @param EEM_Base        $model
1037
-     * @param WP_REST_Request $request
1038
-     * @return array|WP_Error
1039
-     */
1040
-    public function getEntityFromModel($model, $request)
1041
-    {
1042
-        $context = $this->validateContext($request->get_param('caps'));
1043
-        return $this->getOneOrReportPermissionError($model, $request, $context);
1044
-    }
1045
-
1046
-
1047
-
1048
-    /**
1049
-     * If a context is provided which isn't valid, maybe it was added in a future
1050
-     * version so just treat it as a default read
1051
-     *
1052
-     * @param string $context
1053
-     * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
1054
-     */
1055
-    public function validateContext($context)
1056
-    {
1057
-        if (! $context) {
1058
-            $context = EEM_Base::caps_read;
1059
-        }
1060
-        $valid_contexts = EEM_Base::valid_cap_contexts();
1061
-        if (in_array($context, $valid_contexts)) {
1062
-            return $context;
1063
-        } else {
1064
-            return EEM_Base::caps_read;
1065
-        }
1066
-    }
1067
-
1068
-
1069
-
1070
-    /**
1071
-     * Verifies the passed in value is an allowable default where conditions value.
1072
-     *
1073
-     * @param $default_query_params
1074
-     * @return string
1075
-     */
1076
-    public function validateDefaultQueryParams($default_query_params)
1077
-    {
1078
-        $valid_default_where_conditions_for_api_calls = array(
1079
-            EEM_Base::default_where_conditions_all,
1080
-            EEM_Base::default_where_conditions_minimum_all,
1081
-            EEM_Base::default_where_conditions_minimum_others,
1082
-        );
1083
-        if (! $default_query_params) {
1084
-            $default_query_params = EEM_Base::default_where_conditions_all;
1085
-        }
1086
-        if (in_array(
1087
-            $default_query_params,
1088
-            $valid_default_where_conditions_for_api_calls,
1089
-            true
1090
-        )) {
1091
-            return $default_query_params;
1092
-        } else {
1093
-            return EEM_Base::default_where_conditions_all;
1094
-        }
1095
-    }
1096
-
1097
-
1098
-
1099
-    /**
1100
-     * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
1101
-     * Note: right now the query parameter keys for fields (and related fields)
1102
-     * can be left as-is, but it's quite possible this will change someday.
1103
-     * Also, this method's contents might be candidate for moving to Model_Data_Translator
1104
-     *
1105
-     * @param EEM_Base $model
1106
-     * @param array     $query_parameters from $_GET parameter @see Read:handle_request_get_all
1107
-     * @return array like what EEM_Base::get_all() expects or FALSE to indicate
1108
-     *                                    that absolutely no results should be returned
1109
-     * @throws EE_Error
1110
-     * @throws RestException
1111
-     */
1112
-    public function createModelQueryParams($model, $query_parameters)
1113
-    {
1114
-        $model_query_params = array();
1115
-        if (isset($query_parameters['where'])) {
1116
-            $model_query_params[0] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
1117
-                $query_parameters['where'],
1118
-                $model,
1119
-                $this->getModelVersionInfo()->requestedVersion()
1120
-            );
1121
-        }
1122
-        if (isset($query_parameters['order_by'])) {
1123
-            $order_by = $query_parameters['order_by'];
1124
-        } elseif (isset($query_parameters['orderby'])) {
1125
-            $order_by = $query_parameters['orderby'];
1126
-        } else {
1127
-            $order_by = null;
1128
-        }
1129
-        if ($order_by !== null) {
1130
-            if (is_array($order_by)) {
1131
-                $order_by = ModelDataTranslator::prepareFieldNamesInArrayKeysFromJson($order_by);
1132
-            } else {
1133
-                //it's a single item
1134
-                $order_by = ModelDataTranslator::prepareFieldNameFromJson($order_by);
1135
-            }
1136
-            $model_query_params['order_by'] = $order_by;
1137
-        }
1138
-        if (isset($query_parameters['group_by'])) {
1139
-            $group_by = $query_parameters['group_by'];
1140
-        } elseif (isset($query_parameters['groupby'])) {
1141
-            $group_by = $query_parameters['groupby'];
1142
-        } else {
1143
-            $group_by = array_keys($model->get_combined_primary_key_fields());
1144
-        }
1145
-        //make sure they're all real names
1146
-        if (is_array($group_by)) {
1147
-            $group_by = ModelDataTranslator::prepareFieldNamesFromJson($group_by);
1148
-        }
1149
-        if ($group_by !== null) {
1150
-            $model_query_params['group_by'] = $group_by;
1151
-        }
1152
-        if (isset($query_parameters['having'])) {
1153
-            $model_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
1154
-                $query_parameters['having'],
1155
-                $model,
1156
-                $this->getModelVersionInfo()->requestedVersion()
1157
-            );
1158
-        }
1159
-        if (isset($query_parameters['order'])) {
1160
-            $model_query_params['order'] = $query_parameters['order'];
1161
-        }
1162
-        if (isset($query_parameters['mine'])) {
1163
-            $model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
1164
-        }
1165
-        if (isset($query_parameters['limit'])) {
1166
-            //limit should be either a string like '23' or '23,43', or an array with two items in it
1167
-            if (! is_array($query_parameters['limit'])) {
1168
-                $limit_array = explode(',', (string)$query_parameters['limit']);
1169
-            } else {
1170
-                $limit_array = $query_parameters['limit'];
1171
-            }
1172
-            $sanitized_limit = array();
1173
-            foreach ($limit_array as $key => $limit_part) {
1174
-                if ($this->debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1175
-                    throw new EE_Error(
1176
-                        sprintf(
1177
-                            __(
1178
-                                // @codingStandardsIgnoreStart
1179
-                                'An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.',
1180
-                                // @codingStandardsIgnoreEnd
1181
-                                'event_espresso'
1182
-                            ),
1183
-                            wp_json_encode($query_parameters['limit'])
1184
-                        )
1185
-                    );
1186
-                }
1187
-                $sanitized_limit[] = (int)$limit_part;
1188
-            }
1189
-            $model_query_params['limit'] = implode(',', $sanitized_limit);
1190
-        } else {
1191
-            $model_query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
1192
-        }
1193
-        if (isset($query_parameters['caps'])) {
1194
-            $model_query_params['caps'] = $this->validateContext($query_parameters['caps']);
1195
-        } else {
1196
-            $model_query_params['caps'] = EEM_Base::caps_read;
1197
-        }
1198
-        if (isset($query_parameters['default_where_conditions'])) {
1199
-            $model_query_params['default_where_conditions'] = $this->validateDefaultQueryParams(
1200
-                $query_parameters['default_where_conditions']
1201
-            );
1202
-        }
1203
-        return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
1204
-    }
1205
-
1206
-
1207
-
1208
-    /**
1209
-     * Changes the REST-style query params for use in the models
1210
-     *
1211
-     * @deprecated
1212
-     * @param EEM_Base $model
1213
-     * @param array     $query_params sub-array from @see EEM_Base::get_all()
1214
-     * @return array
1215
-     */
1216
-    public function prepareRestQueryParamsKeyForModels($model, $query_params)
1217
-    {
1218
-        $model_ready_query_params = array();
1219
-        foreach ($query_params as $key => $value) {
1220
-            if (is_array($value)) {
1221
-                $model_ready_query_params[$key] = $this->prepareRestQueryParamsKeyForModels($model, $value);
1222
-            } else {
1223
-                $model_ready_query_params[$key] = $value;
1224
-            }
1225
-        }
1226
-        return $model_ready_query_params;
1227
-    }
1228
-
1229
-
1230
-
1231
-    /**
1232
-     * @deprecated instead use ModelDataTranslator::prepareFieldValuesFromJson()
1233
-     * @param $model
1234
-     * @param $query_params
1235
-     * @return array
1236
-     */
1237
-    public function prepareRestQueryParamsValuesForModels($model, $query_params)
1238
-    {
1239
-        $model_ready_query_params = array();
1240
-        foreach ($query_params as $key => $value) {
1241
-            if (is_array($value)) {
1242
-                $model_ready_query_params[$key] = $this->prepareRestQueryParamsValuesForModels($model, $value);
1243
-            } else {
1244
-                $model_ready_query_params[$key] = $value;
1245
-            }
1246
-        }
1247
-        return $model_ready_query_params;
1248
-    }
1249
-
1250
-
1251
-
1252
-    /**
1253
-     * Explodes the string on commas, and only returns items with $prefix followed by a period.
1254
-     * If no prefix is specified, returns items with no period.
1255
-     *
1256
-     * @param string|array $string_to_explode eg "jibba,jabba, blah, blah, blah" or array('jibba', 'jabba' )
1257
-     * @param string       $prefix            "Event" or "foobar"
1258
-     * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1259
-     *                                        we only return strings starting with that and a period; if no prefix was
1260
-     *                                        specified we return all items containing NO periods
1261
-     */
1262
-    public function explodeAndGetItemsPrefixedWith($string_to_explode, $prefix)
1263
-    {
1264
-        if (is_string($string_to_explode)) {
1265
-            $exploded_contents = explode(',', $string_to_explode);
1266
-        } elseif (is_array($string_to_explode)) {
1267
-            $exploded_contents = $string_to_explode;
1268
-        } else {
1269
-            $exploded_contents = array();
1270
-        }
1271
-        //if the string was empty, we want an empty array
1272
-        $exploded_contents = array_filter($exploded_contents);
1273
-        $contents_with_prefix = array();
1274
-        foreach ($exploded_contents as $item) {
1275
-            $item = trim($item);
1276
-            //if no prefix was provided, so we look for items with no "." in them
1277
-            if (! $prefix) {
1278
-                //does this item have a period?
1279
-                if (strpos($item, '.') === false) {
1280
-                    //if not, then its what we're looking for
1281
-                    $contents_with_prefix[] = $item;
1282
-                }
1283
-            } elseif (strpos($item, $prefix . '.') === 0) {
1284
-                //this item has the prefix and a period, grab it
1285
-                $contents_with_prefix[] = substr(
1286
-                    $item,
1287
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1288
-                );
1289
-            } elseif ($item === $prefix) {
1290
-                //this item is JUST the prefix
1291
-                //so let's grab everything after, which is a blank string
1292
-                $contents_with_prefix[] = '';
1293
-            }
1294
-        }
1295
-        return $contents_with_prefix;
1296
-    }
1297
-
1298
-
1299
-
1300
-    /**
1301
-     * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1302
-     * Deprecated because its return values were really quite confusing- sometimes it returned
1303
-     * an empty array (when the include string was blank or '*') or sometimes it returned
1304
-     * array('*') (when you provided a model and a model of that kind was found).
1305
-     * Parses the $include_string so we fetch all the field names relating to THIS model
1306
-     * (ie have NO period in them), or for the provided model (ie start with the model
1307
-     * name and then a period).
1308
-     * @param string $include_string @see Read:handle_request_get_all
1309
-     * @param string $model_name
1310
-     * @return array of fields for this model. If $model_name is provided, then
1311
-     *                               the fields for that model, with the model's name removed from each.
1312
-     *                               If $include_string was blank or '*' returns an empty array
1313
-     */
1314
-    public function extractIncludesForThisModel($include_string, $model_name = null)
1315
-    {
1316
-        if (is_array($include_string)) {
1317
-            $include_string = implode(',', $include_string);
1318
-        }
1319
-        if ($include_string === '*' || $include_string === '') {
1320
-            return array();
1321
-        }
1322
-        $includes = explode(',', $include_string);
1323
-        $extracted_fields_to_include = array();
1324
-        if ($model_name) {
1325
-            foreach ($includes as $field_to_include) {
1326
-                $field_to_include = trim($field_to_include);
1327
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1328
-                    //found the model name at the exact start
1329
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1330
-                    $extracted_fields_to_include[] = $field_sans_model_name;
1331
-                } elseif ($field_to_include == $model_name) {
1332
-                    $extracted_fields_to_include[] = '*';
1333
-                }
1334
-            }
1335
-        } else {
1336
-            //look for ones with no period
1337
-            foreach ($includes as $field_to_include) {
1338
-                $field_to_include = trim($field_to_include);
1339
-                if (strpos($field_to_include, '.') === false
1340
-                    && ! $this->getModelVersionInfo()->isModelNameInThisVersion($field_to_include)
1341
-                ) {
1342
-                    $extracted_fields_to_include[] = $field_to_include;
1343
-                }
1344
-            }
1345
-        }
1346
-        return $extracted_fields_to_include;
1347
-    }
1348
-
1349
-
1350
-
1351
-    /**
1352
-     * Gets the single item using the model according to the request in the context given, otherwise
1353
-     * returns that it's inaccessible to the current user
1354
-
1355
-     *
501
+	 * @param \EE_Model_Relation_Base $relation
502
+	 * @param WP_REST_Request        $request
503
+	 * @return array|WP_Error
504
+	 * @throws EE_Error
505
+	 */
506
+	public function getEntitiesFromRelation($id, $relation, $request)
507
+	{
508
+		if (! $relation->get_this_model()->has_primary_key_field()) {
509
+			throw new EE_Error(
510
+				sprintf(
511
+					__(
512
+						// @codingStandardsIgnoreStart
513
+						'Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
514
+						// @codingStandardsIgnoreEnd
515
+						'event_espresso'
516
+					),
517
+					$relation->get_this_model()->get_this_model_name()
518
+				)
519
+			);
520
+		}
521
+		return $this->getEntitiesFromRelationUsingModelQueryParams(
522
+			array(
523
+				array(
524
+					$relation->get_this_model()->primary_key_name() => $id,
525
+				),
526
+			),
527
+			$relation,
528
+			$request
529
+		);
530
+	}
531
+
532
+
533
+
534
+	/**
535
+	 * Sets the headers that are based on the model and query params,
536
+	 * like the total records. This should only be called on the original request
537
+	 * from the client, not on subsequent internal
538
+	 *
539
+	 * @param EEM_Base $model
540
+	 * @param array     $query_params
541
+	 * @return void
542
+	 */
543
+	protected function setHeadersFromQueryParams($model, $query_params)
544
+	{
545
+		$this->setDebugInfo('model query params', $query_params);
546
+		$this->setDebugInfo(
547
+			'missing caps',
548
+			Capabilities::getMissingPermissionsString($model, $query_params['caps'])
549
+		);
550
+		//normally the limit to a 2-part array, where the 2nd item is the limit
551
+		if (! isset($query_params['limit'])) {
552
+			$query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
553
+		}
554
+		if (is_array($query_params['limit'])) {
555
+			$limit_parts = $query_params['limit'];
556
+		} else {
557
+			$limit_parts = explode(',', $query_params['limit']);
558
+			if (count($limit_parts) == 1) {
559
+				$limit_parts = array(0, $limit_parts[0]);
560
+			}
561
+		}
562
+		//remove the group by and having parts of the query, as those will
563
+		//make the sql query return an array of values, instead of just a single value
564
+		unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
565
+		$count = $model->count($query_params, null, true);
566
+		$pages = $count / $limit_parts[1];
567
+		$this->setResponseHeader('Total', $count, false);
568
+		$this->setResponseHeader('PageSize', $limit_parts[1], false);
569
+		$this->setResponseHeader('TotalPages', ceil($pages), false);
570
+	}
571
+
572
+
573
+
574
+	/**
575
+	 * Changes database results into REST API entities
576
+	 *
577
+	 * @param EEM_Base        $model
578
+	 * @param array            $db_row     like results from $wpdb->get_results()
579
+	 * @param WP_REST_Request $rest_request
580
+	 * @param string           $deprecated no longer used
581
+	 * @return array ready for being converted into json for sending to client
582
+	 */
583
+	public function createEntityFromWpdbResult($model, $db_row, $rest_request, $deprecated = null)
584
+	{
585
+		if (! $rest_request instanceof WP_REST_Request) {
586
+			//ok so this was called in the old style, where the 3rd arg was
587
+			//$include, and the 4th arg was $context
588
+			//now setup the request just to avoid fatal errors, although we won't be able
589
+			//to truly make use of it because it's kinda devoid of info
590
+			$rest_request = new WP_REST_Request();
591
+			$rest_request->set_param('include', $rest_request);
592
+			$rest_request->set_param('caps', $deprecated);
593
+		}
594
+		if ($rest_request->get_param('caps') == null) {
595
+			$rest_request->set_param('caps', EEM_Base::caps_read);
596
+		}
597
+		$entity_array = $this->createBareEntityFromWpdbResults($model, $db_row);
598
+		$entity_array = $this->addExtraFields($model, $db_row, $entity_array);
599
+		$entity_array['_links'] = $this->getEntityLinks($model, $db_row, $entity_array);
600
+		$entity_array['_calculated_fields'] = $this->getEntityCalculations($model, $db_row, $rest_request);
601
+		$entity_array = apply_filters(
602
+			'FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models',
603
+			$entity_array,
604
+			$model,
605
+			$rest_request->get_param('caps'),
606
+			$rest_request,
607
+			$this
608
+		);
609
+		$entity_array = $this->includeRequestedModels($model, $rest_request, $entity_array, $db_row);
610
+		$entity_array = apply_filters(
611
+			'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
612
+			$entity_array,
613
+			$model,
614
+			$rest_request->get_param('caps'),
615
+			$rest_request,
616
+			$this
617
+		);
618
+		$result_without_inaccessible_fields = Capabilities::filterOutInaccessibleEntityFields(
619
+			$entity_array,
620
+			$model,
621
+			$rest_request->get_param('caps'),
622
+			$this->getModelVersionInfo(),
623
+			$model->get_index_primary_key_string(
624
+				$model->deduce_fields_n_values_from_cols_n_values($db_row)
625
+			)
626
+		);
627
+		$this->setDebugInfo(
628
+			'inaccessible fields',
629
+			array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
630
+		);
631
+		return apply_filters(
632
+			'FHEE__Read__create_entity_from_wpdb_results__entity_return',
633
+			$result_without_inaccessible_fields,
634
+			$model,
635
+			$rest_request->get_param('caps')
636
+		);
637
+	}
638
+
639
+
640
+
641
+	/**
642
+	 * Creates a REST entity array (JSON object we're going to return in the response, but
643
+	 * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
644
+	 * from $wpdb->get_row( $sql, ARRAY_A)
645
+	 *
646
+	 * @param EEM_Base $model
647
+	 * @param array     $db_row
648
+	 * @return array entity mostly ready for converting to JSON and sending in the response
649
+	 *
650
+	 */
651
+	protected function createBareEntityFromWpdbResults(EEM_Base $model, $db_row)
652
+	{
653
+		$result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
654
+		$result = array_intersect_key(
655
+			$result,
656
+			$this->getModelVersionInfo()->fieldsOnModelInThisVersion($model)
657
+		);
658
+		//if this is a CPT, we need to set the global $post to it,
659
+		//otherwise shortcodes etc won't work properly while rendering it
660
+		if ($model instanceof \EEM_CPT_Base) {
661
+			$do_chevy_shuffle = true;
662
+		} else {
663
+			$do_chevy_shuffle = false;
664
+		}
665
+		if ($do_chevy_shuffle) {
666
+			global $post;
667
+			$old_post = $post;
668
+			$post = get_post($result[$model->primary_key_name()]);
669
+			if (! $post instanceof \WP_Post) {
670
+				//well that's weird, because $result is what we JUST fetched from the database
671
+				throw new RestException(
672
+					'error_fetching_post_from_database_results',
673
+					esc_html__(
674
+						'An item was retrieved from the database but it\'s not a WP_Post like it should be.',
675
+						'event_espresso'
676
+					)
677
+				);
678
+			}
679
+			$model_object_classname = 'EE_' . $model->get_this_model_name();
680
+			$post->{$model_object_classname} = \EE_Registry::instance()->load_class(
681
+				$model_object_classname,
682
+				$result,
683
+				false,
684
+				false
685
+			);
686
+		}
687
+		foreach ($result as $field_name => $field_value) {
688
+			$field_obj = $model->field_settings_for($field_name);
689
+			if ($this->isSubclassOfOne($field_obj, $this->getModelVersionInfo()->fieldsIgnored())) {
690
+				unset($result[$field_name]);
691
+			} elseif ($this->isSubclassOfOne(
692
+				$field_obj,
693
+				$this->getModelVersionInfo()->fieldsThatHaveRenderedFormat()
694
+			)
695
+			) {
696
+				$result[$field_name] = array(
697
+					'raw'      => $this->prepareFieldObjValueForJson($field_obj, $field_value),
698
+					'rendered' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
699
+				);
700
+			} elseif ($this->isSubclassOfOne(
701
+				$field_obj,
702
+				$this->getModelVersionInfo()->fieldsThatHavePrettyFormat()
703
+			)
704
+			) {
705
+				$result[$field_name] = array(
706
+					'raw'    => $this->prepareFieldObjValueForJson($field_obj, $field_value),
707
+					'pretty' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
708
+				);
709
+			} elseif ($field_obj instanceof \EE_Datetime_Field) {
710
+				$field_value = $field_obj->prepare_for_set_from_db($field_value);
711
+				$timezone = $field_value->getTimezone();
712
+				$field_value->setTimezone(new \DateTimeZone('UTC'));
713
+				// workaround for php datetime bug
714
+				// @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
715
+				$field_value->getTimestamp();
716
+				$result[$field_name . '_gmt'] = ModelDataTranslator::prepareFieldValuesForJson(
717
+					$field_obj,
718
+					$field_value,
719
+					$this->getModelVersionInfo()->requestedVersion()
720
+				);
721
+				$field_value->setTimezone($timezone);
722
+				// workaround for php datetime bug
723
+				// @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
724
+				$field_value->getTimestamp();
725
+				$result[$field_name] = ModelDataTranslator::prepareFieldValuesForJson(
726
+					$field_obj,
727
+					$field_value,
728
+					$this->getModelVersionInfo()->requestedVersion()
729
+				);
730
+			} else {
731
+				$result[$field_name] = $this->prepareFieldObjValueForJson($field_obj, $field_value);
732
+			}
733
+		}
734
+		if ($do_chevy_shuffle) {
735
+			$post = $old_post;
736
+		}
737
+		return $result;
738
+	}
739
+
740
+
741
+
742
+	/**
743
+	 * Takes a value all the way from the DB representation, to the model object's representation, to the
744
+	 * user-facing PHP representation, to the REST API representation. (Assumes you've already taken from the DB
745
+	 * representation using $field_obj->prepare_for_set_from_db())
746
+	 *
747
+	 * @param EE_Model_Field_Base $field_obj
748
+	 * @param mixed $value as it's stored on a model object
749
+	 * @param string $format valid values are 'normal' (default), 'pretty', 'datetime_obj'
750
+	 * @return mixed
751
+	 * @throws ObjectDetectedException if $value contains a PHP object
752
+	 */
753
+	protected function prepareFieldObjValueForJson(EE_Model_Field_Base $field_obj, $value, $format = 'normal')
754
+	{
755
+		$value = $field_obj->prepare_for_set_from_db($value);
756
+		switch ($format) {
757
+			case 'pretty':
758
+				$value = $field_obj->prepare_for_pretty_echoing($value);
759
+				break;
760
+			case 'normal':
761
+			default:
762
+				$value = $field_obj->prepare_for_get($value);
763
+				break;
764
+		}
765
+		return ModelDataTranslator::prepareFieldValuesForJson(
766
+			$field_obj,
767
+			$value,
768
+			$this->getModelVersionInfo()->requestedVersion()
769
+		);
770
+	}
771
+
772
+
773
+
774
+	/**
775
+	 * Adds a few extra fields to the entity response
776
+	 *
777
+	 * @param EEM_Base $model
778
+	 * @param array     $db_row
779
+	 * @param array     $entity_array
780
+	 * @return array modified entity
781
+	 */
782
+	protected function addExtraFields(EEM_Base $model, $db_row, $entity_array)
783
+	{
784
+		if ($model instanceof EEM_CPT_Base) {
785
+			$entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
786
+		}
787
+		return $entity_array;
788
+	}
789
+
790
+
791
+
792
+	/**
793
+	 * Gets links we want to add to the response
794
+	 *
795
+	 * @global \WP_REST_Server $wp_rest_server
796
+	 * @param EEM_Base        $model
797
+	 * @param array            $db_row
798
+	 * @param array            $entity_array
799
+	 * @return array the _links item in the entity
800
+	 */
801
+	protected function getEntityLinks($model, $db_row, $entity_array)
802
+	{
803
+		//add basic links
804
+		$links = array();
805
+		if ($model->has_primary_key_field()) {
806
+			$links['self'] = array(
807
+				array(
808
+					'href' => $this->getVersionedLinkTo(
809
+						EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
810
+						. '/'
811
+						. $entity_array[$model->primary_key_name()]
812
+					),
813
+				),
814
+			);
815
+		}
816
+		$links['collection'] = array(
817
+			array(
818
+				'href' => $this->getVersionedLinkTo(
819
+					EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
820
+				),
821
+			),
822
+		);
823
+		//add links to related models
824
+		if ($model->has_primary_key_field()) {
825
+			foreach ($this->getModelVersionInfo()->relationSettings($model) as $relation_name => $relation_obj) {
826
+				$related_model_part = Read::getRelatedEntityName($relation_name, $relation_obj);
827
+				$links[EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
828
+					array(
829
+						'href'   => $this->getVersionedLinkTo(
830
+							EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
831
+							. '/'
832
+							. $entity_array[$model->primary_key_name()]
833
+							. '/'
834
+							. $related_model_part
835
+						),
836
+						'single' => $relation_obj instanceof EE_Belongs_To_Relation ? true : false,
837
+					),
838
+				);
839
+			}
840
+		}
841
+		return $links;
842
+	}
843
+
844
+
845
+
846
+	/**
847
+	 * Adds the included models indicated in the request to the entity provided
848
+	 *
849
+	 * @param EEM_Base        $model
850
+	 * @param WP_REST_Request $rest_request
851
+	 * @param array            $entity_array
852
+	 * @param array            $db_row
853
+	 * @return array the modified entity
854
+	 */
855
+	protected function includeRequestedModels(
856
+		EEM_Base $model,
857
+		WP_REST_Request $rest_request,
858
+		$entity_array,
859
+		$db_row = array()
860
+	) {
861
+		//if $db_row not included, hope the entity array has what we need
862
+		if (! $db_row) {
863
+			$db_row = $entity_array;
864
+		}
865
+		$includes_for_this_model = $this->explodeAndGetItemsPrefixedWith($rest_request->get_param('include'), '');
866
+		$includes_for_this_model = $this->removeModelNamesFromArray($includes_for_this_model);
867
+		//if they passed in * or didn't specify any includes, return everything
868
+		if (! in_array('*', $includes_for_this_model)
869
+			&& ! empty($includes_for_this_model)
870
+		) {
871
+			if ($model->has_primary_key_field()) {
872
+				//always include the primary key. ya just gotta know that at least
873
+				$includes_for_this_model[] = $model->primary_key_name();
874
+			}
875
+			if ($this->explodeAndGetItemsPrefixedWith($rest_request->get_param('calculate'), '')) {
876
+				$includes_for_this_model[] = '_calculated_fields';
877
+			}
878
+			$entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
879
+		}
880
+		$relation_settings = $this->getModelVersionInfo()->relationSettings($model);
881
+		foreach ($relation_settings as $relation_name => $relation_obj) {
882
+			$related_fields_to_include = $this->explodeAndGetItemsPrefixedWith(
883
+				$rest_request->get_param('include'),
884
+				$relation_name
885
+			);
886
+			$related_fields_to_calculate = $this->explodeAndGetItemsPrefixedWith(
887
+				$rest_request->get_param('calculate'),
888
+				$relation_name
889
+			);
890
+			//did they specify they wanted to include a related model, or
891
+			//specific fields from a related model?
892
+			//or did they specify to calculate a field from a related model?
893
+			if ($related_fields_to_include || $related_fields_to_calculate) {
894
+				//if so, we should include at least some part of the related model
895
+				$pretend_related_request = new WP_REST_Request();
896
+				$pretend_related_request->set_query_params(
897
+					array(
898
+						'caps'      => $rest_request->get_param('caps'),
899
+						'include'   => $related_fields_to_include,
900
+						'calculate' => $related_fields_to_calculate,
901
+					)
902
+				);
903
+				$pretend_related_request->add_header('no_rest_headers', true);
904
+				$primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
905
+					$model->get_index_primary_key_string(
906
+						$model->deduce_fields_n_values_from_cols_n_values($db_row)
907
+					)
908
+				);
909
+				$related_results = $this->getEntitiesFromRelationUsingModelQueryParams(
910
+					$primary_model_query_params,
911
+					$relation_obj,
912
+					$pretend_related_request
913
+				);
914
+				$entity_array[Read::getRelatedEntityName($relation_name, $relation_obj)] = $related_results
915
+																						   instanceof
916
+																						   WP_Error
917
+					? null
918
+					: $related_results;
919
+			}
920
+		}
921
+		return $entity_array;
922
+	}
923
+
924
+
925
+
926
+	/**
927
+	 * Returns a new array with all the names of models removed. Eg
928
+	 * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
929
+	 *
930
+	 * @param array $arr
931
+	 * @return array
932
+	 */
933
+	private function removeModelNamesFromArray($arr)
934
+	{
935
+		return array_diff($arr, array_keys(EE_Registry::instance()->non_abstract_db_models));
936
+	}
937
+
938
+
939
+
940
+	/**
941
+	 * Gets the calculated fields for the response
942
+	 *
943
+	 * @param EEM_Base        $model
944
+	 * @param array            $wpdb_row
945
+	 * @param WP_REST_Request $rest_request
946
+	 * @return \stdClass the _calculations item in the entity
947
+	 * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we
948
+	 * did, let's know about it ASAP, so let the exception bubble up)
949
+	 */
950
+	protected function getEntityCalculations($model, $wpdb_row, $rest_request)
951
+	{
952
+		$calculated_fields = $this->explodeAndGetItemsPrefixedWith(
953
+			$rest_request->get_param('calculate'),
954
+			''
955
+		);
956
+		//note: setting calculate=* doesn't do anything
957
+		$calculated_fields_to_return = new \stdClass();
958
+		foreach ($calculated_fields as $field_to_calculate) {
959
+			try {
960
+				$calculated_fields_to_return->$field_to_calculate = ModelDataTranslator::prepareFieldValueForJson(
961
+					null,
962
+					$this->fields_calculator->retrieveCalculatedFieldValue(
963
+						$model,
964
+						$field_to_calculate,
965
+						$wpdb_row,
966
+						$rest_request,
967
+						$this
968
+					),
969
+					$this->getModelVersionInfo()->requestedVersion()
970
+				);
971
+			} catch (RestException $e) {
972
+				//if we don't have permission to read it, just leave it out. but let devs know about the problem
973
+				$this->setResponseHeader(
974
+					'Notices-Field-Calculation-Errors['
975
+					. $e->getStringCode()
976
+					. ']['
977
+					. $model->get_this_model_name()
978
+					. ']['
979
+					. $field_to_calculate
980
+					. ']',
981
+					$e->getMessage(),
982
+					true
983
+				);
984
+			}
985
+		}
986
+		return $calculated_fields_to_return;
987
+	}
988
+
989
+
990
+
991
+	/**
992
+	 * Gets the full URL to the resource, taking the requested version into account
993
+	 *
994
+	 * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
995
+	 * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
996
+	 */
997
+	public function getVersionedLinkTo($link_part_after_version_and_slash)
998
+	{
999
+		return rest_url(
1000
+			EED_Core_Rest_Api::get_versioned_route_to(
1001
+				$link_part_after_version_and_slash,
1002
+				$this->getModelVersionInfo()->requestedVersion()
1003
+			)
1004
+		);
1005
+	}
1006
+
1007
+
1008
+
1009
+	/**
1010
+	 * Gets the correct lowercase name for the relation in the API according
1011
+	 * to the relation's type
1012
+	 *
1013
+	 * @param string                  $relation_name
1014
+	 * @param \EE_Model_Relation_Base $relation_obj
1015
+	 * @return string
1016
+	 */
1017
+	public static function getRelatedEntityName($relation_name, $relation_obj)
1018
+	{
1019
+		if ($relation_obj instanceof EE_Belongs_To_Relation) {
1020
+			return strtolower($relation_name);
1021
+		} else {
1022
+			return EEH_Inflector::pluralize_and_lower($relation_name);
1023
+		}
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Gets the one model object with the specified id for the specified model
1030
+	 *
1031
+	 * @param EEM_Base        $model
1032
+	 * @param WP_REST_Request $request
1033
+	 * @return array|WP_Error
1034
+	 */
1035
+	public function getEntityFromModel($model, $request)
1036
+	{
1037
+		$context = $this->validateContext($request->get_param('caps'));
1038
+		return $this->getOneOrReportPermissionError($model, $request, $context);
1039
+	}
1040
+
1041
+
1042
+
1043
+	/**
1044
+	 * If a context is provided which isn't valid, maybe it was added in a future
1045
+	 * version so just treat it as a default read
1046
+	 *
1047
+	 * @param string $context
1048
+	 * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
1049
+	 */
1050
+	public function validateContext($context)
1051
+	{
1052
+		if (! $context) {
1053
+			$context = EEM_Base::caps_read;
1054
+		}
1055
+		$valid_contexts = EEM_Base::valid_cap_contexts();
1056
+		if (in_array($context, $valid_contexts)) {
1057
+			return $context;
1058
+		} else {
1059
+			return EEM_Base::caps_read;
1060
+		}
1061
+	}
1062
+
1063
+
1064
+
1065
+	/**
1066
+	 * Verifies the passed in value is an allowable default where conditions value.
1067
+	 *
1068
+	 * @param $default_query_params
1069
+	 * @return string
1070
+	 */
1071
+	public function validateDefaultQueryParams($default_query_params)
1072
+	{
1073
+		$valid_default_where_conditions_for_api_calls = array(
1074
+			EEM_Base::default_where_conditions_all,
1075
+			EEM_Base::default_where_conditions_minimum_all,
1076
+			EEM_Base::default_where_conditions_minimum_others,
1077
+		);
1078
+		if (! $default_query_params) {
1079
+			$default_query_params = EEM_Base::default_where_conditions_all;
1080
+		}
1081
+		if (in_array(
1082
+			$default_query_params,
1083
+			$valid_default_where_conditions_for_api_calls,
1084
+			true
1085
+		)) {
1086
+			return $default_query_params;
1087
+		} else {
1088
+			return EEM_Base::default_where_conditions_all;
1089
+		}
1090
+	}
1091
+
1092
+
1093
+
1094
+	/**
1095
+	 * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
1096
+	 * Note: right now the query parameter keys for fields (and related fields)
1097
+	 * can be left as-is, but it's quite possible this will change someday.
1098
+	 * Also, this method's contents might be candidate for moving to Model_Data_Translator
1099
+	 *
1100
+	 * @param EEM_Base $model
1101
+	 * @param array     $query_parameters from $_GET parameter @see Read:handle_request_get_all
1102
+	 * @return array like what EEM_Base::get_all() expects or FALSE to indicate
1103
+	 *                                    that absolutely no results should be returned
1104
+	 * @throws EE_Error
1105
+	 * @throws RestException
1106
+	 */
1107
+	public function createModelQueryParams($model, $query_parameters)
1108
+	{
1109
+		$model_query_params = array();
1110
+		if (isset($query_parameters['where'])) {
1111
+			$model_query_params[0] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
1112
+				$query_parameters['where'],
1113
+				$model,
1114
+				$this->getModelVersionInfo()->requestedVersion()
1115
+			);
1116
+		}
1117
+		if (isset($query_parameters['order_by'])) {
1118
+			$order_by = $query_parameters['order_by'];
1119
+		} elseif (isset($query_parameters['orderby'])) {
1120
+			$order_by = $query_parameters['orderby'];
1121
+		} else {
1122
+			$order_by = null;
1123
+		}
1124
+		if ($order_by !== null) {
1125
+			if (is_array($order_by)) {
1126
+				$order_by = ModelDataTranslator::prepareFieldNamesInArrayKeysFromJson($order_by);
1127
+			} else {
1128
+				//it's a single item
1129
+				$order_by = ModelDataTranslator::prepareFieldNameFromJson($order_by);
1130
+			}
1131
+			$model_query_params['order_by'] = $order_by;
1132
+		}
1133
+		if (isset($query_parameters['group_by'])) {
1134
+			$group_by = $query_parameters['group_by'];
1135
+		} elseif (isset($query_parameters['groupby'])) {
1136
+			$group_by = $query_parameters['groupby'];
1137
+		} else {
1138
+			$group_by = array_keys($model->get_combined_primary_key_fields());
1139
+		}
1140
+		//make sure they're all real names
1141
+		if (is_array($group_by)) {
1142
+			$group_by = ModelDataTranslator::prepareFieldNamesFromJson($group_by);
1143
+		}
1144
+		if ($group_by !== null) {
1145
+			$model_query_params['group_by'] = $group_by;
1146
+		}
1147
+		if (isset($query_parameters['having'])) {
1148
+			$model_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
1149
+				$query_parameters['having'],
1150
+				$model,
1151
+				$this->getModelVersionInfo()->requestedVersion()
1152
+			);
1153
+		}
1154
+		if (isset($query_parameters['order'])) {
1155
+			$model_query_params['order'] = $query_parameters['order'];
1156
+		}
1157
+		if (isset($query_parameters['mine'])) {
1158
+			$model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
1159
+		}
1160
+		if (isset($query_parameters['limit'])) {
1161
+			//limit should be either a string like '23' or '23,43', or an array with two items in it
1162
+			if (! is_array($query_parameters['limit'])) {
1163
+				$limit_array = explode(',', (string)$query_parameters['limit']);
1164
+			} else {
1165
+				$limit_array = $query_parameters['limit'];
1166
+			}
1167
+			$sanitized_limit = array();
1168
+			foreach ($limit_array as $key => $limit_part) {
1169
+				if ($this->debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1170
+					throw new EE_Error(
1171
+						sprintf(
1172
+							__(
1173
+								// @codingStandardsIgnoreStart
1174
+								'An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.',
1175
+								// @codingStandardsIgnoreEnd
1176
+								'event_espresso'
1177
+							),
1178
+							wp_json_encode($query_parameters['limit'])
1179
+						)
1180
+					);
1181
+				}
1182
+				$sanitized_limit[] = (int)$limit_part;
1183
+			}
1184
+			$model_query_params['limit'] = implode(',', $sanitized_limit);
1185
+		} else {
1186
+			$model_query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
1187
+		}
1188
+		if (isset($query_parameters['caps'])) {
1189
+			$model_query_params['caps'] = $this->validateContext($query_parameters['caps']);
1190
+		} else {
1191
+			$model_query_params['caps'] = EEM_Base::caps_read;
1192
+		}
1193
+		if (isset($query_parameters['default_where_conditions'])) {
1194
+			$model_query_params['default_where_conditions'] = $this->validateDefaultQueryParams(
1195
+				$query_parameters['default_where_conditions']
1196
+			);
1197
+		}
1198
+		return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
1199
+	}
1200
+
1201
+
1202
+
1203
+	/**
1204
+	 * Changes the REST-style query params for use in the models
1205
+	 *
1206
+	 * @deprecated
1207
+	 * @param EEM_Base $model
1208
+	 * @param array     $query_params sub-array from @see EEM_Base::get_all()
1209
+	 * @return array
1210
+	 */
1211
+	public function prepareRestQueryParamsKeyForModels($model, $query_params)
1212
+	{
1213
+		$model_ready_query_params = array();
1214
+		foreach ($query_params as $key => $value) {
1215
+			if (is_array($value)) {
1216
+				$model_ready_query_params[$key] = $this->prepareRestQueryParamsKeyForModels($model, $value);
1217
+			} else {
1218
+				$model_ready_query_params[$key] = $value;
1219
+			}
1220
+		}
1221
+		return $model_ready_query_params;
1222
+	}
1223
+
1224
+
1225
+
1226
+	/**
1227
+	 * @deprecated instead use ModelDataTranslator::prepareFieldValuesFromJson()
1228
+	 * @param $model
1229
+	 * @param $query_params
1230
+	 * @return array
1231
+	 */
1232
+	public function prepareRestQueryParamsValuesForModels($model, $query_params)
1233
+	{
1234
+		$model_ready_query_params = array();
1235
+		foreach ($query_params as $key => $value) {
1236
+			if (is_array($value)) {
1237
+				$model_ready_query_params[$key] = $this->prepareRestQueryParamsValuesForModels($model, $value);
1238
+			} else {
1239
+				$model_ready_query_params[$key] = $value;
1240
+			}
1241
+		}
1242
+		return $model_ready_query_params;
1243
+	}
1244
+
1245
+
1246
+
1247
+	/**
1248
+	 * Explodes the string on commas, and only returns items with $prefix followed by a period.
1249
+	 * If no prefix is specified, returns items with no period.
1250
+	 *
1251
+	 * @param string|array $string_to_explode eg "jibba,jabba, blah, blah, blah" or array('jibba', 'jabba' )
1252
+	 * @param string       $prefix            "Event" or "foobar"
1253
+	 * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1254
+	 *                                        we only return strings starting with that and a period; if no prefix was
1255
+	 *                                        specified we return all items containing NO periods
1256
+	 */
1257
+	public function explodeAndGetItemsPrefixedWith($string_to_explode, $prefix)
1258
+	{
1259
+		if (is_string($string_to_explode)) {
1260
+			$exploded_contents = explode(',', $string_to_explode);
1261
+		} elseif (is_array($string_to_explode)) {
1262
+			$exploded_contents = $string_to_explode;
1263
+		} else {
1264
+			$exploded_contents = array();
1265
+		}
1266
+		//if the string was empty, we want an empty array
1267
+		$exploded_contents = array_filter($exploded_contents);
1268
+		$contents_with_prefix = array();
1269
+		foreach ($exploded_contents as $item) {
1270
+			$item = trim($item);
1271
+			//if no prefix was provided, so we look for items with no "." in them
1272
+			if (! $prefix) {
1273
+				//does this item have a period?
1274
+				if (strpos($item, '.') === false) {
1275
+					//if not, then its what we're looking for
1276
+					$contents_with_prefix[] = $item;
1277
+				}
1278
+			} elseif (strpos($item, $prefix . '.') === 0) {
1279
+				//this item has the prefix and a period, grab it
1280
+				$contents_with_prefix[] = substr(
1281
+					$item,
1282
+					strpos($item, $prefix . '.') + strlen($prefix . '.')
1283
+				);
1284
+			} elseif ($item === $prefix) {
1285
+				//this item is JUST the prefix
1286
+				//so let's grab everything after, which is a blank string
1287
+				$contents_with_prefix[] = '';
1288
+			}
1289
+		}
1290
+		return $contents_with_prefix;
1291
+	}
1292
+
1293
+
1294
+
1295
+	/**
1296
+	 * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1297
+	 * Deprecated because its return values were really quite confusing- sometimes it returned
1298
+	 * an empty array (when the include string was blank or '*') or sometimes it returned
1299
+	 * array('*') (when you provided a model and a model of that kind was found).
1300
+	 * Parses the $include_string so we fetch all the field names relating to THIS model
1301
+	 * (ie have NO period in them), or for the provided model (ie start with the model
1302
+	 * name and then a period).
1303
+	 * @param string $include_string @see Read:handle_request_get_all
1304
+	 * @param string $model_name
1305
+	 * @return array of fields for this model. If $model_name is provided, then
1306
+	 *                               the fields for that model, with the model's name removed from each.
1307
+	 *                               If $include_string was blank or '*' returns an empty array
1308
+	 */
1309
+	public function extractIncludesForThisModel($include_string, $model_name = null)
1310
+	{
1311
+		if (is_array($include_string)) {
1312
+			$include_string = implode(',', $include_string);
1313
+		}
1314
+		if ($include_string === '*' || $include_string === '') {
1315
+			return array();
1316
+		}
1317
+		$includes = explode(',', $include_string);
1318
+		$extracted_fields_to_include = array();
1319
+		if ($model_name) {
1320
+			foreach ($includes as $field_to_include) {
1321
+				$field_to_include = trim($field_to_include);
1322
+				if (strpos($field_to_include, $model_name . '.') === 0) {
1323
+					//found the model name at the exact start
1324
+					$field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1325
+					$extracted_fields_to_include[] = $field_sans_model_name;
1326
+				} elseif ($field_to_include == $model_name) {
1327
+					$extracted_fields_to_include[] = '*';
1328
+				}
1329
+			}
1330
+		} else {
1331
+			//look for ones with no period
1332
+			foreach ($includes as $field_to_include) {
1333
+				$field_to_include = trim($field_to_include);
1334
+				if (strpos($field_to_include, '.') === false
1335
+					&& ! $this->getModelVersionInfo()->isModelNameInThisVersion($field_to_include)
1336
+				) {
1337
+					$extracted_fields_to_include[] = $field_to_include;
1338
+				}
1339
+			}
1340
+		}
1341
+		return $extracted_fields_to_include;
1342
+	}
1343
+
1344
+
1345
+
1346
+	/**
1347
+	 * Gets the single item using the model according to the request in the context given, otherwise
1348
+	 * returns that it's inaccessible to the current user
1349
+	 *
1356 1350
 *@param EEM_Base        $model
1357
-     * @param WP_REST_Request $request
1358
-     * @param null             $context
1359
-     * @return array|WP_Error
1360
-     */
1361
-    public function getOneOrReportPermissionError(EEM_Base $model, WP_REST_Request $request, $context = null)
1362
-    {
1363
-        $query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
1364
-        if ($model instanceof \EEM_Soft_Delete_Base) {
1365
-            $query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
1366
-        }
1367
-        $restricted_query_params = $query_params;
1368
-        $restricted_query_params['caps'] = $context;
1369
-        $this->setDebugInfo('model query params', $restricted_query_params);
1370
-        $model_rows = $model->get_all_wpdb_results($restricted_query_params);
1371
-        if (! empty($model_rows)) {
1372
-            return $this->createEntityFromWpdbResult(
1373
-                $model,
1374
-                array_shift($model_rows),
1375
-                $request
1376
-            );
1377
-        } else {
1378
-            //ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
1379
-            $lowercase_model_name = strtolower($model->get_this_model_name());
1380
-            $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
1381
-            if (! empty($model_rows_found_sans_restrictions)) {
1382
-                //you got shafted- it existed but we didn't want to tell you!
1383
-                return new WP_Error(
1384
-                    'rest_user_cannot_' . $context,
1385
-                    sprintf(
1386
-                        __('Sorry, you cannot %1$s this %2$s. Missing permissions are: %3$s', 'event_espresso'),
1387
-                        $context,
1388
-                        strtolower($model->get_this_model_name()),
1389
-                        Capabilities::getMissingPermissionsString(
1390
-                            $model,
1391
-                            $context
1392
-                        )
1393
-                    ),
1394
-                    array('status' => 403)
1395
-                );
1396
-            } else {
1397
-                //it's not you. It just doesn't exist
1398
-                return new WP_Error(
1399
-                    sprintf('rest_%s_invalid_id', $lowercase_model_name),
1400
-                    sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
1401
-                    array('status' => 404)
1402
-                );
1403
-            }
1404
-        }
1405
-    }
1351
+	 * @param WP_REST_Request $request
1352
+	 * @param null             $context
1353
+	 * @return array|WP_Error
1354
+	 */
1355
+	public function getOneOrReportPermissionError(EEM_Base $model, WP_REST_Request $request, $context = null)
1356
+	{
1357
+		$query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
1358
+		if ($model instanceof \EEM_Soft_Delete_Base) {
1359
+			$query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
1360
+		}
1361
+		$restricted_query_params = $query_params;
1362
+		$restricted_query_params['caps'] = $context;
1363
+		$this->setDebugInfo('model query params', $restricted_query_params);
1364
+		$model_rows = $model->get_all_wpdb_results($restricted_query_params);
1365
+		if (! empty($model_rows)) {
1366
+			return $this->createEntityFromWpdbResult(
1367
+				$model,
1368
+				array_shift($model_rows),
1369
+				$request
1370
+			);
1371
+		} else {
1372
+			//ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
1373
+			$lowercase_model_name = strtolower($model->get_this_model_name());
1374
+			$model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
1375
+			if (! empty($model_rows_found_sans_restrictions)) {
1376
+				//you got shafted- it existed but we didn't want to tell you!
1377
+				return new WP_Error(
1378
+					'rest_user_cannot_' . $context,
1379
+					sprintf(
1380
+						__('Sorry, you cannot %1$s this %2$s. Missing permissions are: %3$s', 'event_espresso'),
1381
+						$context,
1382
+						strtolower($model->get_this_model_name()),
1383
+						Capabilities::getMissingPermissionsString(
1384
+							$model,
1385
+							$context
1386
+						)
1387
+					),
1388
+					array('status' => 403)
1389
+				);
1390
+			} else {
1391
+				//it's not you. It just doesn't exist
1392
+				return new WP_Error(
1393
+					sprintf('rest_%s_invalid_id', $lowercase_model_name),
1394
+					sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
1395
+					array('status' => 404)
1396
+				);
1397
+			}
1398
+		}
1399
+	}
1406 1400
 }
1407 1401
 
1408 1402
 
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
 use EEM_Base;
21 21
 use EEM_CPT_Base;
22 22
 
23
-if (! defined('EVENT_ESPRESSO_VERSION')) {
23
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
24 24
     exit('No direct script access allowed');
25 25
 }
26 26
 
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
         $controller = new Read();
72 72
         try {
73 73
             $controller->setRequestedVersion($version);
74
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
74
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
75 75
                 return $controller->sendResponse(
76 76
                     new WP_Error(
77 77
                         'endpoint_parsing_error',
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
         $controller = new Read();
111 111
         try {
112 112
             $controller->setRequestedVersion($version);
113
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
113
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
114 114
                 return array();
115 115
             }
116 116
             //get the model for this version
@@ -207,9 +207,9 @@  discard block
 block discarded – undo
207 207
     protected function maybeAddExtraFieldsToSchema($field_name, EE_Model_Field_Base $field, array $schema)
208 208
     {
209 209
         if ($field instanceof EE_Datetime_Field) {
210
-            $schema['properties'][$field_name . '_gmt'] = $field->getSchema();
210
+            $schema['properties'][$field_name.'_gmt'] = $field->getSchema();
211 211
             //modify the description
212
-            $schema['properties'][$field_name . '_gmt']['description'] = sprintf(
212
+            $schema['properties'][$field_name.'_gmt']['description'] = sprintf(
213 213
                 esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
214 214
                 wp_specialchars_decode($field->get_nicename(), ENT_QUOTES)
215 215
             );
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
         $controller = new Read();
253 253
         try {
254 254
             $controller->setRequestedVersion($version);
255
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
255
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
256 256
                 return $controller->sendResponse(
257 257
                     new WP_Error(
258 258
                         'endpoint_parsing_error',
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
         $controller = new Read();
300 300
         try {
301 301
             $controller->setRequestedVersion($version);
302
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
302
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
303 303
                 return $controller->sendResponse(
304 304
                     new WP_Error(
305 305
                         'endpoint_parsing_error',
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
                 );
315 315
             }
316 316
             $main_model = $controller->getModelVersionInfo()->loadModel($model_name);
317
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($related_model_name)) {
317
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($related_model_name)) {
318 318
                 return $controller->sendResponse(
319 319
                     new WP_Error(
320 320
                         'endpoint_parsing_error',
@@ -353,7 +353,7 @@  discard block
 block discarded – undo
353 353
     public function getEntitiesFromModel($model, $request)
354 354
     {
355 355
         $query_params = $this->createModelQueryParams($model, $request->get_params());
356
-        if (! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) {
356
+        if ( ! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) {
357 357
             $model_name_plural = EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
358 358
             return new WP_Error(
359 359
                 sprintf('rest_%s_cannot_list', $model_name_plural),
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
                 array('status' => 403)
366 366
             );
367 367
         }
368
-        if (! $request->get_header('no_rest_headers')) {
368
+        if ( ! $request->get_header('no_rest_headers')) {
369 369
             $this->setHeadersFromQueryParams($model, $query_params);
370 370
         }
371 371
         /** @type array $results */
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
         $context = $this->validateContext($request->get_param('caps'));
402 402
         $model = $relation->get_this_model();
403 403
         $related_model = $relation->get_other_model();
404
-        if (! isset($primary_model_query_params[0])) {
404
+        if ( ! isset($primary_model_query_params[0])) {
405 405
             $primary_model_query_params[0] = array();
406 406
         }
407 407
         //check if they can access the 1st model object
@@ -418,7 +418,7 @@  discard block
 block discarded – undo
418 418
         $restricted_query_params['caps'] = $context;
419 419
         $this->setDebugInfo('main model query params', $restricted_query_params);
420 420
         $this->setDebugInfo('missing caps', Capabilities::getMissingPermissionsString($related_model, $context));
421
-        if (! (
421
+        if ( ! (
422 422
             Capabilities::currentUserHasPartialAccessTo($related_model, $context)
423 423
             && $model->exists($restricted_query_params)
424 424
         )
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
         }
458 458
         $query_params['default_where_conditions'] = 'none';
459 459
         $query_params['caps'] = $context;
460
-        if (! $request->get_header('no_rest_headers')) {
460
+        if ( ! $request->get_header('no_rest_headers')) {
461 461
             $this->setHeadersFromQueryParams($relation->get_other_model(), $query_params);
462 462
         }
463 463
         /** @type array $results */
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
      */
511 511
     public function getEntitiesFromRelation($id, $relation, $request)
512 512
     {
513
-        if (! $relation->get_this_model()->has_primary_key_field()) {
513
+        if ( ! $relation->get_this_model()->has_primary_key_field()) {
514 514
             throw new EE_Error(
515 515
                 sprintf(
516 516
                     __(
@@ -553,7 +553,7 @@  discard block
 block discarded – undo
553 553
             Capabilities::getMissingPermissionsString($model, $query_params['caps'])
554 554
         );
555 555
         //normally the limit to a 2-part array, where the 2nd item is the limit
556
-        if (! isset($query_params['limit'])) {
556
+        if ( ! isset($query_params['limit'])) {
557 557
             $query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
558 558
         }
559 559
         if (is_array($query_params['limit'])) {
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
      */
588 588
     public function createEntityFromWpdbResult($model, $db_row, $rest_request, $deprecated = null)
589 589
     {
590
-        if (! $rest_request instanceof WP_REST_Request) {
590
+        if ( ! $rest_request instanceof WP_REST_Request) {
591 591
             //ok so this was called in the old style, where the 3rd arg was
592 592
             //$include, and the 4th arg was $context
593 593
             //now setup the request just to avoid fatal errors, although we won't be able
@@ -671,7 +671,7 @@  discard block
 block discarded – undo
671 671
             global $post;
672 672
             $old_post = $post;
673 673
             $post = get_post($result[$model->primary_key_name()]);
674
-            if (! $post instanceof \WP_Post) {
674
+            if ( ! $post instanceof \WP_Post) {
675 675
                 //well that's weird, because $result is what we JUST fetched from the database
676 676
                 throw new RestException(
677 677
                     'error_fetching_post_from_database_results',
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
                     )
682 682
                 );
683 683
             }
684
-            $model_object_classname = 'EE_' . $model->get_this_model_name();
684
+            $model_object_classname = 'EE_'.$model->get_this_model_name();
685 685
             $post->{$model_object_classname} = \EE_Registry::instance()->load_class(
686 686
                 $model_object_classname,
687 687
                 $result,
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
                 // workaround for php datetime bug
719 719
                 // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
720 720
                 $field_value->getTimestamp();
721
-                $result[$field_name . '_gmt'] = ModelDataTranslator::prepareFieldValuesForJson(
721
+                $result[$field_name.'_gmt'] = ModelDataTranslator::prepareFieldValuesForJson(
722 722
                     $field_obj,
723 723
                     $field_value,
724 724
                     $this->getModelVersionInfo()->requestedVersion()
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
         if ($model->has_primary_key_field()) {
830 830
             foreach ($this->getModelVersionInfo()->relationSettings($model) as $relation_name => $relation_obj) {
831 831
                 $related_model_part = Read::getRelatedEntityName($relation_name, $relation_obj);
832
-                $links[EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
832
+                $links[EED_Core_Rest_Api::ee_api_link_namespace.$related_model_part] = array(
833 833
                     array(
834 834
                         'href'   => $this->getVersionedLinkTo(
835 835
                             EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
@@ -864,13 +864,13 @@  discard block
 block discarded – undo
864 864
         $db_row = array()
865 865
     ) {
866 866
         //if $db_row not included, hope the entity array has what we need
867
-        if (! $db_row) {
867
+        if ( ! $db_row) {
868 868
             $db_row = $entity_array;
869 869
         }
870 870
         $includes_for_this_model = $this->explodeAndGetItemsPrefixedWith($rest_request->get_param('include'), '');
871 871
         $includes_for_this_model = $this->removeModelNamesFromArray($includes_for_this_model);
872 872
         //if they passed in * or didn't specify any includes, return everything
873
-        if (! in_array('*', $includes_for_this_model)
873
+        if ( ! in_array('*', $includes_for_this_model)
874 874
             && ! empty($includes_for_this_model)
875 875
         ) {
876 876
             if ($model->has_primary_key_field()) {
@@ -1054,7 +1054,7 @@  discard block
 block discarded – undo
1054 1054
      */
1055 1055
     public function validateContext($context)
1056 1056
     {
1057
-        if (! $context) {
1057
+        if ( ! $context) {
1058 1058
             $context = EEM_Base::caps_read;
1059 1059
         }
1060 1060
         $valid_contexts = EEM_Base::valid_cap_contexts();
@@ -1080,7 +1080,7 @@  discard block
 block discarded – undo
1080 1080
             EEM_Base::default_where_conditions_minimum_all,
1081 1081
             EEM_Base::default_where_conditions_minimum_others,
1082 1082
         );
1083
-        if (! $default_query_params) {
1083
+        if ( ! $default_query_params) {
1084 1084
             $default_query_params = EEM_Base::default_where_conditions_all;
1085 1085
         }
1086 1086
         if (in_array(
@@ -1164,14 +1164,14 @@  discard block
 block discarded – undo
1164 1164
         }
1165 1165
         if (isset($query_parameters['limit'])) {
1166 1166
             //limit should be either a string like '23' or '23,43', or an array with two items in it
1167
-            if (! is_array($query_parameters['limit'])) {
1168
-                $limit_array = explode(',', (string)$query_parameters['limit']);
1167
+            if ( ! is_array($query_parameters['limit'])) {
1168
+                $limit_array = explode(',', (string) $query_parameters['limit']);
1169 1169
             } else {
1170 1170
                 $limit_array = $query_parameters['limit'];
1171 1171
             }
1172 1172
             $sanitized_limit = array();
1173 1173
             foreach ($limit_array as $key => $limit_part) {
1174
-                if ($this->debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1174
+                if ($this->debug_mode && ( ! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1175 1175
                     throw new EE_Error(
1176 1176
                         sprintf(
1177 1177
                             __(
@@ -1184,7 +1184,7 @@  discard block
 block discarded – undo
1184 1184
                         )
1185 1185
                     );
1186 1186
                 }
1187
-                $sanitized_limit[] = (int)$limit_part;
1187
+                $sanitized_limit[] = (int) $limit_part;
1188 1188
             }
1189 1189
             $model_query_params['limit'] = implode(',', $sanitized_limit);
1190 1190
         } else {
@@ -1274,17 +1274,17 @@  discard block
 block discarded – undo
1274 1274
         foreach ($exploded_contents as $item) {
1275 1275
             $item = trim($item);
1276 1276
             //if no prefix was provided, so we look for items with no "." in them
1277
-            if (! $prefix) {
1277
+            if ( ! $prefix) {
1278 1278
                 //does this item have a period?
1279 1279
                 if (strpos($item, '.') === false) {
1280 1280
                     //if not, then its what we're looking for
1281 1281
                     $contents_with_prefix[] = $item;
1282 1282
                 }
1283
-            } elseif (strpos($item, $prefix . '.') === 0) {
1283
+            } elseif (strpos($item, $prefix.'.') === 0) {
1284 1284
                 //this item has the prefix and a period, grab it
1285 1285
                 $contents_with_prefix[] = substr(
1286 1286
                     $item,
1287
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1287
+                    strpos($item, $prefix.'.') + strlen($prefix.'.')
1288 1288
                 );
1289 1289
             } elseif ($item === $prefix) {
1290 1290
                 //this item is JUST the prefix
@@ -1324,9 +1324,9 @@  discard block
 block discarded – undo
1324 1324
         if ($model_name) {
1325 1325
             foreach ($includes as $field_to_include) {
1326 1326
                 $field_to_include = trim($field_to_include);
1327
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1327
+                if (strpos($field_to_include, $model_name.'.') === 0) {
1328 1328
                     //found the model name at the exact start
1329
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1329
+                    $field_sans_model_name = str_replace($model_name.'.', '', $field_to_include);
1330 1330
                     $extracted_fields_to_include[] = $field_sans_model_name;
1331 1331
                 } elseif ($field_to_include == $model_name) {
1332 1332
                     $extracted_fields_to_include[] = '*';
@@ -1368,7 +1368,7 @@  discard block
 block discarded – undo
1368 1368
         $restricted_query_params['caps'] = $context;
1369 1369
         $this->setDebugInfo('model query params', $restricted_query_params);
1370 1370
         $model_rows = $model->get_all_wpdb_results($restricted_query_params);
1371
-        if (! empty($model_rows)) {
1371
+        if ( ! empty($model_rows)) {
1372 1372
             return $this->createEntityFromWpdbResult(
1373 1373
                 $model,
1374 1374
                 array_shift($model_rows),
@@ -1378,10 +1378,10 @@  discard block
 block discarded – undo
1378 1378
             //ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
1379 1379
             $lowercase_model_name = strtolower($model->get_this_model_name());
1380 1380
             $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
1381
-            if (! empty($model_rows_found_sans_restrictions)) {
1381
+            if ( ! empty($model_rows_found_sans_restrictions)) {
1382 1382
                 //you got shafted- it existed but we didn't want to tell you!
1383 1383
                 return new WP_Error(
1384
-                    'rest_user_cannot_' . $context,
1384
+                    'rest_user_cannot_'.$context,
1385 1385
                     sprintf(
1386 1386
                         __('Sorry, you cannot %1$s this %2$s. Missing permissions are: %3$s', 'event_espresso'),
1387 1387
                         $context,
Please login to merge, or discard this patch.
core/db_models/fields/EE_Datetime_Field.php 2 patches
Indentation   +770 added lines, -770 removed lines patch added patch discarded remove patch
@@ -17,775 +17,775 @@
 block discarded – undo
17 17
 class EE_Datetime_Field extends EE_Model_Field_Base
18 18
 {
19 19
 
20
-    /**
21
-     * The pattern we're looking for is if only the characters 0-9 are found and there are only
22
-     * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
23
-     *
24
-     * @type string unix_timestamp_regex
25
-     */
26
-    const unix_timestamp_regex = '/[0-9]{10,}/';
27
-
28
-    /**
29
-     * @type string mysql_timestamp_format
30
-     */
31
-    const mysql_timestamp_format = 'Y-m-d H:i:s';
32
-
33
-    /**
34
-     * @type string mysql_date_format
35
-     */
36
-    const mysql_date_format = 'Y-m-d';
37
-
38
-    /**
39
-     * @type string mysql_time_format
40
-     */
41
-    const mysql_time_format = 'H:i:s';
42
-
43
-    /**
44
-     * Const for using in the default value. If the field's default is set to this,
45
-     * then we will return the time of calling `get_default_value()`, not
46
-     * just the current time at construction
47
-     */
48
-    const now = 'now';
49
-
50
-    /**
51
-     * The following properties hold the default formats for date and time.
52
-     * Defaults are set via the constructor and can be overridden on class instantiation.
53
-     * However they can also be overridden later by the set_format() method
54
-     * (and corresponding set_date_format, set_time_format methods);
55
-     */
56
-    /**
57
-     * @type string $_date_format
58
-     */
59
-    protected $_date_format = '';
60
-
61
-    /**
62
-     * @type string $_time_format
63
-     */
64
-    protected $_time_format = '';
65
-
66
-    /**
67
-     * @type string $_pretty_date_format
68
-     */
69
-    protected $_pretty_date_format = '';
70
-
71
-    /**
72
-     * @type string $_pretty_time_format
73
-     */
74
-    protected $_pretty_time_format = '';
75
-
76
-    /**
77
-     * @type DateTimeZone $_DateTimeZone
78
-     */
79
-    protected $_DateTimeZone;
80
-
81
-    /**
82
-     * @type DateTimeZone $_UTC_DateTimeZone
83
-     */
84
-    protected $_UTC_DateTimeZone;
85
-
86
-    /**
87
-     * @type DateTimeZone $_blog_DateTimeZone
88
-     */
89
-    protected $_blog_DateTimeZone;
90
-
91
-
92
-    /**
93
-     * This property holds how we want the output returned when getting a datetime string.  It is set for the
94
-     * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
95
-     * and time returned via getters.
96
-     *
97
-     * @var mixed (null|string)
98
-     */
99
-    protected $_date_time_output;
100
-
101
-
102
-    /**
103
-     * timezone string
104
-     * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
105
-     * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
106
-     * coming out of the object to be in.  Default timezone is the current WP timezone option setting
107
-     *
108
-     * @var string
109
-     */
110
-    protected $_timezone_string;
111
-
112
-
113
-    /**
114
-     * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
115
-     * offsets for comparison purposes).
116
-     *
117
-     * @var int
118
-     */
119
-    protected $_blog_offset;
120
-
121
-
122
-
123
-    /**
124
-     * @param string $table_column
125
-     * @param string $nice_name
126
-     * @param bool   $nullable
127
-     * @param string $default_value
128
-     * @param string $timezone_string
129
-     * @param string $date_format
130
-     * @param string $time_format
131
-     * @param string $pretty_date_format
132
-     * @param string $pretty_time_format
133
-     * @throws EE_Error
134
-     * @throws InvalidArgumentException
135
-     */
136
-    public function __construct(
137
-        $table_column,
138
-        $nice_name,
139
-        $nullable,
140
-        $default_value,
141
-        $timezone_string = '',
142
-        $date_format = '',
143
-        $time_format = '',
144
-        $pretty_date_format = '',
145
-        $pretty_time_format = ''
146
-    ) {
147
-
148
-        $this->_date_format        = ! empty($date_format) ? $date_format : get_option('date_format');
149
-        $this->_time_format        = ! empty($time_format) ? $time_format : get_option('time_format');
150
-        $this->_pretty_date_format = ! empty($pretty_date_format) ? $pretty_date_format : get_option('date_format');
151
-        $this->_pretty_time_format = ! empty($pretty_time_format) ? $pretty_time_format : get_option('time_format');
152
-
153
-        parent::__construct($table_column, $nice_name, $nullable, $default_value);
154
-        $this->set_timezone($timezone_string);
155
-        $this->setSchemaFormat('date-time');
156
-    }
157
-
158
-
159
-    /**
160
-     * @return DateTimeZone
161
-     * @throws \EE_Error
162
-     */
163
-    public function get_UTC_DateTimeZone()
164
-    {
165
-        return $this->_UTC_DateTimeZone instanceof DateTimeZone
166
-            ? $this->_UTC_DateTimeZone
167
-            : $this->_create_timezone_object_from_timezone_string('UTC');
168
-    }
169
-
170
-
171
-    /**
172
-     * @return DateTimeZone
173
-     * @throws \EE_Error
174
-     */
175
-    public function get_blog_DateTimeZone()
176
-    {
177
-        return $this->_blog_DateTimeZone instanceof DateTimeZone
178
-            ? $this->_blog_DateTimeZone
179
-            : $this->_create_timezone_object_from_timezone_string('');
180
-    }
181
-
182
-
183
-    /**
184
-     * this prepares any incoming date data and make sure its converted to a utc unix timestamp
185
-     *
186
-     * @param  string|int $value_inputted_for_field_on_model_object could be a string formatted date time or int unix
187
-     *                                                              timestamp
188
-     * @return DateTime
189
-     */
190
-    public function prepare_for_set($value_inputted_for_field_on_model_object)
191
-    {
192
-        return $this->_get_date_object($value_inputted_for_field_on_model_object);
193
-    }
194
-
195
-
196
-    /**
197
-     * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
198
-     * getters need to know whether we're just returning the date or the time or both.  By default we return both.
199
-     *
200
-     * @param bool $pretty If we're returning the pretty formats or standard format string.
201
-     * @return string    The final assembled format string.
202
-     */
203
-    protected function _get_date_time_output($pretty = false)
204
-    {
205
-
206
-        switch ($this->_date_time_output) {
207
-            case 'time' :
208
-                return $pretty ? $this->_pretty_time_format : $this->_time_format;
209
-                break;
210
-
211
-            case 'date' :
212
-                return $pretty ? $this->_pretty_date_format : $this->_date_format;
213
-                break;
214
-
215
-            default :
216
-                return $pretty
217
-                    ? $this->_pretty_date_format . ' ' . $this->_pretty_time_format
218
-                    : $this->_date_format . ' ' . $this->_time_format;
219
-        }
220
-    }
221
-
222
-
223
-    /**
224
-     * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
225
-     * returned (using the format properties)
226
-     *
227
-     * @param string $what acceptable values are 'time' or 'date'.
228
-     *                     Any other value will be set but will always result
229
-     *                     in both 'date' and 'time' being returned.
230
-     * @return void
231
-     */
232
-    public function set_date_time_output($what = null)
233
-    {
234
-        $this->_date_time_output = $what;
235
-    }
236
-
237
-
238
-    /**
239
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
240
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
241
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
242
-     * We also set some other properties in this method.
243
-     *
244
-     * @param string $timezone_string A valid timezone string as described by @link
245
-     *                                http://www.php.net/manual/en/timezones.php
246
-     * @return void
247
-     * @throws InvalidArgumentException
248
-     * @throws InvalidDataTypeException
249
-     * @throws InvalidInterfaceException
250
-     */
251
-    public function set_timezone($timezone_string)
252
-    {
253
-        if (empty($timezone_string) && $this->_timezone_string !== null) {
254
-            // leave the timezone AS-IS if we already have one and
255
-            // the function arg didn't provide one
256
-            return;
257
-        }
258
-        $timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
259
-        $this->_timezone_string = ! empty($timezone_string) ? $timezone_string : 'UTC';
260
-        $this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
261
-    }
262
-
263
-
264
-    /**
265
-     * _create_timezone_object_from_timezone_name
266
-     *
267
-     * @access protected
268
-     * @param string $timezone_string
269
-     * @return \DateTimeZone
270
-     * @throws InvalidArgumentException
271
-     * @throws InvalidDataTypeException
272
-     * @throws InvalidInterfaceException
273
-     */
274
-    protected function _create_timezone_object_from_timezone_string($timezone_string = '')
275
-    {
276
-        return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
277
-    }
278
-
279
-
280
-    /**
281
-     * This just returns whatever is set for the current timezone.
282
-     *
283
-     * @access public
284
-     * @return string timezone string
285
-     */
286
-    public function get_timezone()
287
-    {
288
-        return $this->_timezone_string;
289
-    }
290
-
291
-
292
-    /**
293
-     * set the $_date_format property
294
-     *
295
-     * @access public
296
-     * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
297
-     * @param bool   $pretty Whether to set pretty format or not.
298
-     * @return void
299
-     */
300
-    public function set_date_format($format, $pretty = false)
301
-    {
302
-        if ($pretty) {
303
-            $this->_pretty_date_format = $format;
304
-        } else {
305
-            $this->_date_format = $format;
306
-        }
307
-    }
308
-
309
-
310
-    /**
311
-     * return the $_date_format property value.
312
-     *
313
-     * @param bool $pretty Whether to get pretty format or not.
314
-     * @return string
315
-     */
316
-    public function get_date_format($pretty = false)
317
-    {
318
-        return $pretty ? $this->_pretty_date_format : $this->_date_format;
319
-    }
320
-
321
-
322
-    /**
323
-     * set the $_time_format property
324
-     *
325
-     * @access public
326
-     * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
327
-     * @param bool   $pretty Whether to set pretty format or not.
328
-     * @return void
329
-     */
330
-    public function set_time_format($format, $pretty = false)
331
-    {
332
-        if ($pretty) {
333
-            $this->_pretty_time_format = $format;
334
-        } else {
335
-            $this->_time_format = $format;
336
-        }
337
-    }
338
-
339
-
340
-    /**
341
-     * return the $_time_format property value.
342
-     *
343
-     * @param bool $pretty Whether to get pretty format or not.
344
-     * @return string
345
-     */
346
-    public function get_time_format($pretty = false)
347
-    {
348
-        return $pretty ? $this->_pretty_time_format : $this->_time_format;
349
-    }
350
-
351
-
352
-    /**
353
-     * set the $_pretty_date_format property
354
-     *
355
-     * @access public
356
-     * @param string $format a new pretty date format (corresponding to formats accepted by PHP date() function)
357
-     * @return void
358
-     */
359
-    public function set_pretty_date_format($format)
360
-    {
361
-        $this->_pretty_date_format = $format;
362
-    }
363
-
364
-
365
-    /**
366
-     * set the $_pretty_time_format property
367
-     *
368
-     * @access public
369
-     * @param string $format a new pretty time format (corresponding to formats accepted by PHP date() function)
370
-     * @return void
371
-     */
372
-    public function set_pretty_time_format($format)
373
-    {
374
-        $this->_pretty_time_format = $format;
375
-    }
376
-
377
-
378
-    /**
379
-     * Only sets the time portion of the datetime.
380
-     *
381
-     * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
382
-     * @param DateTime        $current            current DateTime object for the datetime field
383
-     * @return DateTime
384
-     */
385
-    public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current)
386
-    {
387
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
388
-        // Otherwise parse the string.
389
-        if ($time_to_set_string instanceof DateTime) {
390
-            $parsed = array(
391
-                'hour'   => $time_to_set_string->format('H'),
392
-                'minute' => $time_to_set_string->format('i'),
393
-                'second' => $time_to_set_string->format('s'),
394
-            );
395
-        } else {
396
-            //parse incoming string
397
-            $parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
398
-        }
399
-
400
-        //make sure $current is in the correct timezone.
401
-        $current->setTimezone($this->_DateTimeZone);
402
-        // workaround for php datetime bug
403
-        // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
404
-        $current->getTimestamp();
405
-
406
-        return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
407
-    }
408
-
409
-
410
-    /**
411
-     * Only sets the date portion of the datetime.
412
-     *
413
-     * @param string|DateTime $date_to_set_string like Friday, January 8th or a DateTime object.
414
-     * @param DateTime        $current            current DateTime object for the datetime field
415
-     * @return DateTime
416
-     */
417
-    public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current)
418
-    {
419
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
420
-        // Otherwise parse the string.
421
-        if ($date_to_set_string instanceof DateTime) {
422
-            $parsed = array(
423
-                'year'  => $date_to_set_string->format('Y'),
424
-                'month' => $date_to_set_string->format('m'),
425
-                'day'   => $date_to_set_string->format('d'),
426
-            );
427
-        } else {
428
-            //parse incoming string
429
-            $parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
430
-        }
431
-
432
-        //make sure $current is in the correct timezone
433
-        $current->setTimezone($this->_DateTimeZone);
434
-        // workaround for php datetime bug
435
-        // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
436
-        $current->getTimestamp();
437
-
438
-        return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
439
-    }
440
-
441
-
442
-    /**
443
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).  When the
444
-     * datetime gets to this stage it should ALREADY be in UTC time
445
-     *
446
-     * @param  DateTime $DateTime
447
-     * @return string formatted date time for given timezone
448
-     * @throws \EE_Error
449
-     */
450
-    public function prepare_for_get($DateTime)
451
-    {
452
-        return $this->_prepare_for_display($DateTime);
453
-    }
454
-
455
-
456
-    /**
457
-     * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
458
-     * from the set wp timezone.  If so, then it returns the datetime string formatted via
459
-     * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
460
-     * abbreviation to the date_string.
461
-     *
462
-     * @param mixed $DateTime
463
-     * @param null  $schema
464
-     * @return string
465
-     * @throws \EE_Error
466
-     */
467
-    public function prepare_for_pretty_echoing($DateTime, $schema = null)
468
-    {
469
-        return $this->_prepare_for_display($DateTime, $schema ? $schema : true);
470
-    }
471
-
472
-
473
-    /**
474
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
475
-     * timezone).
476
-     *
477
-     * @param DateTime    $DateTime
478
-     * @param bool|string $schema
479
-     * @return string
480
-     * @throws \EE_Error
481
-     */
482
-    protected function _prepare_for_display($DateTime, $schema = false)
483
-    {
484
-        if (! $DateTime instanceof DateTime) {
485
-            if ($this->_nullable) {
486
-                return '';
487
-            } else {
488
-                if (WP_DEBUG) {
489
-                    throw new EE_Error(
490
-                        sprintf(
491
-                            __(
492
-                                'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.',
493
-                                'event_espresso'
494
-                            ),
495
-                            $this->_nicename
496
-                        )
497
-                    );
498
-                } else {
499
-                    $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now);
500
-                    EE_Error::add_error(
501
-                        sprintf(
502
-                            __(
503
-                                'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.  When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.',
504
-                                'event_espresso'
505
-                            ),
506
-                            $this->_nicename
507
-                        )
508
-                    );
509
-                }
510
-            }
511
-        }
512
-        $format_string = $this->_get_date_time_output($schema);
513
-        //make sure datetime_value is in the correct timezone (in case that's been updated).
514
-        $DateTime->setTimezone($this->_DateTimeZone);
515
-        // workaround for php datetime bug
516
-        // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
517
-        $DateTime->getTimestamp();
518
-        if ($schema) {
519
-            if ($this->_display_timezone()) {
520
-                //must be explicit because schema could equal true.
521
-                if ($schema === 'no_html') {
522
-                    $timezone_string = ' (' . $DateTime->format('T') . ')';
523
-                } else {
524
-                    $timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
525
-                }
526
-            } else {
527
-                $timezone_string = '';
528
-            }
529
-
530
-            return $DateTime->format($format_string) . $timezone_string;
531
-        }
532
-        return $DateTime->format($format_string);
533
-    }
534
-
535
-
536
-    /**
537
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
538
-     * timezone).
539
-     *
540
-     * @param  mixed $datetime_value u
541
-     * @return string mysql timestamp in UTC
542
-     * @throws \EE_Error
543
-     */
544
-    public function prepare_for_use_in_db($datetime_value)
545
-    {
546
-        //we allow an empty value or DateTime object, but nothing else.
547
-        if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
548
-            throw new EE_Error(
549
-            	sprintf(
550
-            	    __(
551
-            		    'The incoming value being prepared for setting in the database must either be empty or a php 
20
+	/**
21
+	 * The pattern we're looking for is if only the characters 0-9 are found and there are only
22
+	 * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
23
+	 *
24
+	 * @type string unix_timestamp_regex
25
+	 */
26
+	const unix_timestamp_regex = '/[0-9]{10,}/';
27
+
28
+	/**
29
+	 * @type string mysql_timestamp_format
30
+	 */
31
+	const mysql_timestamp_format = 'Y-m-d H:i:s';
32
+
33
+	/**
34
+	 * @type string mysql_date_format
35
+	 */
36
+	const mysql_date_format = 'Y-m-d';
37
+
38
+	/**
39
+	 * @type string mysql_time_format
40
+	 */
41
+	const mysql_time_format = 'H:i:s';
42
+
43
+	/**
44
+	 * Const for using in the default value. If the field's default is set to this,
45
+	 * then we will return the time of calling `get_default_value()`, not
46
+	 * just the current time at construction
47
+	 */
48
+	const now = 'now';
49
+
50
+	/**
51
+	 * The following properties hold the default formats for date and time.
52
+	 * Defaults are set via the constructor and can be overridden on class instantiation.
53
+	 * However they can also be overridden later by the set_format() method
54
+	 * (and corresponding set_date_format, set_time_format methods);
55
+	 */
56
+	/**
57
+	 * @type string $_date_format
58
+	 */
59
+	protected $_date_format = '';
60
+
61
+	/**
62
+	 * @type string $_time_format
63
+	 */
64
+	protected $_time_format = '';
65
+
66
+	/**
67
+	 * @type string $_pretty_date_format
68
+	 */
69
+	protected $_pretty_date_format = '';
70
+
71
+	/**
72
+	 * @type string $_pretty_time_format
73
+	 */
74
+	protected $_pretty_time_format = '';
75
+
76
+	/**
77
+	 * @type DateTimeZone $_DateTimeZone
78
+	 */
79
+	protected $_DateTimeZone;
80
+
81
+	/**
82
+	 * @type DateTimeZone $_UTC_DateTimeZone
83
+	 */
84
+	protected $_UTC_DateTimeZone;
85
+
86
+	/**
87
+	 * @type DateTimeZone $_blog_DateTimeZone
88
+	 */
89
+	protected $_blog_DateTimeZone;
90
+
91
+
92
+	/**
93
+	 * This property holds how we want the output returned when getting a datetime string.  It is set for the
94
+	 * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
95
+	 * and time returned via getters.
96
+	 *
97
+	 * @var mixed (null|string)
98
+	 */
99
+	protected $_date_time_output;
100
+
101
+
102
+	/**
103
+	 * timezone string
104
+	 * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
105
+	 * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
106
+	 * coming out of the object to be in.  Default timezone is the current WP timezone option setting
107
+	 *
108
+	 * @var string
109
+	 */
110
+	protected $_timezone_string;
111
+
112
+
113
+	/**
114
+	 * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
115
+	 * offsets for comparison purposes).
116
+	 *
117
+	 * @var int
118
+	 */
119
+	protected $_blog_offset;
120
+
121
+
122
+
123
+	/**
124
+	 * @param string $table_column
125
+	 * @param string $nice_name
126
+	 * @param bool   $nullable
127
+	 * @param string $default_value
128
+	 * @param string $timezone_string
129
+	 * @param string $date_format
130
+	 * @param string $time_format
131
+	 * @param string $pretty_date_format
132
+	 * @param string $pretty_time_format
133
+	 * @throws EE_Error
134
+	 * @throws InvalidArgumentException
135
+	 */
136
+	public function __construct(
137
+		$table_column,
138
+		$nice_name,
139
+		$nullable,
140
+		$default_value,
141
+		$timezone_string = '',
142
+		$date_format = '',
143
+		$time_format = '',
144
+		$pretty_date_format = '',
145
+		$pretty_time_format = ''
146
+	) {
147
+
148
+		$this->_date_format        = ! empty($date_format) ? $date_format : get_option('date_format');
149
+		$this->_time_format        = ! empty($time_format) ? $time_format : get_option('time_format');
150
+		$this->_pretty_date_format = ! empty($pretty_date_format) ? $pretty_date_format : get_option('date_format');
151
+		$this->_pretty_time_format = ! empty($pretty_time_format) ? $pretty_time_format : get_option('time_format');
152
+
153
+		parent::__construct($table_column, $nice_name, $nullable, $default_value);
154
+		$this->set_timezone($timezone_string);
155
+		$this->setSchemaFormat('date-time');
156
+	}
157
+
158
+
159
+	/**
160
+	 * @return DateTimeZone
161
+	 * @throws \EE_Error
162
+	 */
163
+	public function get_UTC_DateTimeZone()
164
+	{
165
+		return $this->_UTC_DateTimeZone instanceof DateTimeZone
166
+			? $this->_UTC_DateTimeZone
167
+			: $this->_create_timezone_object_from_timezone_string('UTC');
168
+	}
169
+
170
+
171
+	/**
172
+	 * @return DateTimeZone
173
+	 * @throws \EE_Error
174
+	 */
175
+	public function get_blog_DateTimeZone()
176
+	{
177
+		return $this->_blog_DateTimeZone instanceof DateTimeZone
178
+			? $this->_blog_DateTimeZone
179
+			: $this->_create_timezone_object_from_timezone_string('');
180
+	}
181
+
182
+
183
+	/**
184
+	 * this prepares any incoming date data and make sure its converted to a utc unix timestamp
185
+	 *
186
+	 * @param  string|int $value_inputted_for_field_on_model_object could be a string formatted date time or int unix
187
+	 *                                                              timestamp
188
+	 * @return DateTime
189
+	 */
190
+	public function prepare_for_set($value_inputted_for_field_on_model_object)
191
+	{
192
+		return $this->_get_date_object($value_inputted_for_field_on_model_object);
193
+	}
194
+
195
+
196
+	/**
197
+	 * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
198
+	 * getters need to know whether we're just returning the date or the time or both.  By default we return both.
199
+	 *
200
+	 * @param bool $pretty If we're returning the pretty formats or standard format string.
201
+	 * @return string    The final assembled format string.
202
+	 */
203
+	protected function _get_date_time_output($pretty = false)
204
+	{
205
+
206
+		switch ($this->_date_time_output) {
207
+			case 'time' :
208
+				return $pretty ? $this->_pretty_time_format : $this->_time_format;
209
+				break;
210
+
211
+			case 'date' :
212
+				return $pretty ? $this->_pretty_date_format : $this->_date_format;
213
+				break;
214
+
215
+			default :
216
+				return $pretty
217
+					? $this->_pretty_date_format . ' ' . $this->_pretty_time_format
218
+					: $this->_date_format . ' ' . $this->_time_format;
219
+		}
220
+	}
221
+
222
+
223
+	/**
224
+	 * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
225
+	 * returned (using the format properties)
226
+	 *
227
+	 * @param string $what acceptable values are 'time' or 'date'.
228
+	 *                     Any other value will be set but will always result
229
+	 *                     in both 'date' and 'time' being returned.
230
+	 * @return void
231
+	 */
232
+	public function set_date_time_output($what = null)
233
+	{
234
+		$this->_date_time_output = $what;
235
+	}
236
+
237
+
238
+	/**
239
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
240
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
241
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
242
+	 * We also set some other properties in this method.
243
+	 *
244
+	 * @param string $timezone_string A valid timezone string as described by @link
245
+	 *                                http://www.php.net/manual/en/timezones.php
246
+	 * @return void
247
+	 * @throws InvalidArgumentException
248
+	 * @throws InvalidDataTypeException
249
+	 * @throws InvalidInterfaceException
250
+	 */
251
+	public function set_timezone($timezone_string)
252
+	{
253
+		if (empty($timezone_string) && $this->_timezone_string !== null) {
254
+			// leave the timezone AS-IS if we already have one and
255
+			// the function arg didn't provide one
256
+			return;
257
+		}
258
+		$timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
259
+		$this->_timezone_string = ! empty($timezone_string) ? $timezone_string : 'UTC';
260
+		$this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
261
+	}
262
+
263
+
264
+	/**
265
+	 * _create_timezone_object_from_timezone_name
266
+	 *
267
+	 * @access protected
268
+	 * @param string $timezone_string
269
+	 * @return \DateTimeZone
270
+	 * @throws InvalidArgumentException
271
+	 * @throws InvalidDataTypeException
272
+	 * @throws InvalidInterfaceException
273
+	 */
274
+	protected function _create_timezone_object_from_timezone_string($timezone_string = '')
275
+	{
276
+		return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
277
+	}
278
+
279
+
280
+	/**
281
+	 * This just returns whatever is set for the current timezone.
282
+	 *
283
+	 * @access public
284
+	 * @return string timezone string
285
+	 */
286
+	public function get_timezone()
287
+	{
288
+		return $this->_timezone_string;
289
+	}
290
+
291
+
292
+	/**
293
+	 * set the $_date_format property
294
+	 *
295
+	 * @access public
296
+	 * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
297
+	 * @param bool   $pretty Whether to set pretty format or not.
298
+	 * @return void
299
+	 */
300
+	public function set_date_format($format, $pretty = false)
301
+	{
302
+		if ($pretty) {
303
+			$this->_pretty_date_format = $format;
304
+		} else {
305
+			$this->_date_format = $format;
306
+		}
307
+	}
308
+
309
+
310
+	/**
311
+	 * return the $_date_format property value.
312
+	 *
313
+	 * @param bool $pretty Whether to get pretty format or not.
314
+	 * @return string
315
+	 */
316
+	public function get_date_format($pretty = false)
317
+	{
318
+		return $pretty ? $this->_pretty_date_format : $this->_date_format;
319
+	}
320
+
321
+
322
+	/**
323
+	 * set the $_time_format property
324
+	 *
325
+	 * @access public
326
+	 * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
327
+	 * @param bool   $pretty Whether to set pretty format or not.
328
+	 * @return void
329
+	 */
330
+	public function set_time_format($format, $pretty = false)
331
+	{
332
+		if ($pretty) {
333
+			$this->_pretty_time_format = $format;
334
+		} else {
335
+			$this->_time_format = $format;
336
+		}
337
+	}
338
+
339
+
340
+	/**
341
+	 * return the $_time_format property value.
342
+	 *
343
+	 * @param bool $pretty Whether to get pretty format or not.
344
+	 * @return string
345
+	 */
346
+	public function get_time_format($pretty = false)
347
+	{
348
+		return $pretty ? $this->_pretty_time_format : $this->_time_format;
349
+	}
350
+
351
+
352
+	/**
353
+	 * set the $_pretty_date_format property
354
+	 *
355
+	 * @access public
356
+	 * @param string $format a new pretty date format (corresponding to formats accepted by PHP date() function)
357
+	 * @return void
358
+	 */
359
+	public function set_pretty_date_format($format)
360
+	{
361
+		$this->_pretty_date_format = $format;
362
+	}
363
+
364
+
365
+	/**
366
+	 * set the $_pretty_time_format property
367
+	 *
368
+	 * @access public
369
+	 * @param string $format a new pretty time format (corresponding to formats accepted by PHP date() function)
370
+	 * @return void
371
+	 */
372
+	public function set_pretty_time_format($format)
373
+	{
374
+		$this->_pretty_time_format = $format;
375
+	}
376
+
377
+
378
+	/**
379
+	 * Only sets the time portion of the datetime.
380
+	 *
381
+	 * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
382
+	 * @param DateTime        $current            current DateTime object for the datetime field
383
+	 * @return DateTime
384
+	 */
385
+	public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current)
386
+	{
387
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
388
+		// Otherwise parse the string.
389
+		if ($time_to_set_string instanceof DateTime) {
390
+			$parsed = array(
391
+				'hour'   => $time_to_set_string->format('H'),
392
+				'minute' => $time_to_set_string->format('i'),
393
+				'second' => $time_to_set_string->format('s'),
394
+			);
395
+		} else {
396
+			//parse incoming string
397
+			$parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
398
+		}
399
+
400
+		//make sure $current is in the correct timezone.
401
+		$current->setTimezone($this->_DateTimeZone);
402
+		// workaround for php datetime bug
403
+		// @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
404
+		$current->getTimestamp();
405
+
406
+		return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
407
+	}
408
+
409
+
410
+	/**
411
+	 * Only sets the date portion of the datetime.
412
+	 *
413
+	 * @param string|DateTime $date_to_set_string like Friday, January 8th or a DateTime object.
414
+	 * @param DateTime        $current            current DateTime object for the datetime field
415
+	 * @return DateTime
416
+	 */
417
+	public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current)
418
+	{
419
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
420
+		// Otherwise parse the string.
421
+		if ($date_to_set_string instanceof DateTime) {
422
+			$parsed = array(
423
+				'year'  => $date_to_set_string->format('Y'),
424
+				'month' => $date_to_set_string->format('m'),
425
+				'day'   => $date_to_set_string->format('d'),
426
+			);
427
+		} else {
428
+			//parse incoming string
429
+			$parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
430
+		}
431
+
432
+		//make sure $current is in the correct timezone
433
+		$current->setTimezone($this->_DateTimeZone);
434
+		// workaround for php datetime bug
435
+		// @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
436
+		$current->getTimestamp();
437
+
438
+		return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
439
+	}
440
+
441
+
442
+	/**
443
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).  When the
444
+	 * datetime gets to this stage it should ALREADY be in UTC time
445
+	 *
446
+	 * @param  DateTime $DateTime
447
+	 * @return string formatted date time for given timezone
448
+	 * @throws \EE_Error
449
+	 */
450
+	public function prepare_for_get($DateTime)
451
+	{
452
+		return $this->_prepare_for_display($DateTime);
453
+	}
454
+
455
+
456
+	/**
457
+	 * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
458
+	 * from the set wp timezone.  If so, then it returns the datetime string formatted via
459
+	 * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
460
+	 * abbreviation to the date_string.
461
+	 *
462
+	 * @param mixed $DateTime
463
+	 * @param null  $schema
464
+	 * @return string
465
+	 * @throws \EE_Error
466
+	 */
467
+	public function prepare_for_pretty_echoing($DateTime, $schema = null)
468
+	{
469
+		return $this->_prepare_for_display($DateTime, $schema ? $schema : true);
470
+	}
471
+
472
+
473
+	/**
474
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
475
+	 * timezone).
476
+	 *
477
+	 * @param DateTime    $DateTime
478
+	 * @param bool|string $schema
479
+	 * @return string
480
+	 * @throws \EE_Error
481
+	 */
482
+	protected function _prepare_for_display($DateTime, $schema = false)
483
+	{
484
+		if (! $DateTime instanceof DateTime) {
485
+			if ($this->_nullable) {
486
+				return '';
487
+			} else {
488
+				if (WP_DEBUG) {
489
+					throw new EE_Error(
490
+						sprintf(
491
+							__(
492
+								'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.',
493
+								'event_espresso'
494
+							),
495
+							$this->_nicename
496
+						)
497
+					);
498
+				} else {
499
+					$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now);
500
+					EE_Error::add_error(
501
+						sprintf(
502
+							__(
503
+								'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.  When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.',
504
+								'event_espresso'
505
+							),
506
+							$this->_nicename
507
+						)
508
+					);
509
+				}
510
+			}
511
+		}
512
+		$format_string = $this->_get_date_time_output($schema);
513
+		//make sure datetime_value is in the correct timezone (in case that's been updated).
514
+		$DateTime->setTimezone($this->_DateTimeZone);
515
+		// workaround for php datetime bug
516
+		// @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
517
+		$DateTime->getTimestamp();
518
+		if ($schema) {
519
+			if ($this->_display_timezone()) {
520
+				//must be explicit because schema could equal true.
521
+				if ($schema === 'no_html') {
522
+					$timezone_string = ' (' . $DateTime->format('T') . ')';
523
+				} else {
524
+					$timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
525
+				}
526
+			} else {
527
+				$timezone_string = '';
528
+			}
529
+
530
+			return $DateTime->format($format_string) . $timezone_string;
531
+		}
532
+		return $DateTime->format($format_string);
533
+	}
534
+
535
+
536
+	/**
537
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
538
+	 * timezone).
539
+	 *
540
+	 * @param  mixed $datetime_value u
541
+	 * @return string mysql timestamp in UTC
542
+	 * @throws \EE_Error
543
+	 */
544
+	public function prepare_for_use_in_db($datetime_value)
545
+	{
546
+		//we allow an empty value or DateTime object, but nothing else.
547
+		if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
548
+			throw new EE_Error(
549
+				sprintf(
550
+					__(
551
+						'The incoming value being prepared for setting in the database must either be empty or a php 
552 552
             		    DateTime object, instead of: %1$s %2$s',
553
-                        'event_espresso'
554
-	                ),
555
-                    '<br />',
556
-                    print_r($datetime_value, true)
557
-                )
558
-            );
559
-        }
560
-
561
-        if ($datetime_value instanceof DateTime) {
562
-            if (! $datetime_value instanceof DbSafeDateTime) {
563
-                $datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
564
-            }
565
-
566
-            $datetime_value->setTimezone($this->get_UTC_DateTimeZone());
567
-            // workaround for php datetime bug
568
-            // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
569
-            $datetime_value->getTimestamp();
570
-            return $datetime_value->format(
571
-                EE_Datetime_Field::mysql_timestamp_format
572
-            );
573
-        }
574
-
575
-        // if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
576
-        return ! $this->_nullable && empty($datetime_value) ? current_time('mysql', true) : null;
577
-    }
578
-
579
-
580
-    /**
581
-     * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
582
-     * allowed)
583
-     *
584
-     * @param string $datetime_string mysql timestamp in UTC
585
-     * @return  mixed null | DateTime
586
-     * @throws \EE_Error
587
-     */
588
-    public function prepare_for_set_from_db($datetime_string)
589
-    {
590
-        //if $datetime_value is empty, and ! $this->_nullable, just use time()
591
-        if (empty($datetime_string) && $this->_nullable) {
592
-            return null;
593
-        }
594
-        // datetime strings from the db should ALWAYS be in UTC+0, so use UTC_DateTimeZone when creating
595
-        if (empty($datetime_string)) {
596
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
597
-        } else {
598
-            $DateTime = DateTime::createFromFormat(
599
-                EE_Datetime_Field::mysql_timestamp_format,
600
-                $datetime_string,
601
-                $this->get_UTC_DateTimeZone()
602
-            );
603
-            if ($DateTime instanceof \DateTime) {
604
-                $DateTime = new DbSafeDateTime(
605
-                    $DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
606
-                    $this->get_UTC_DateTimeZone()
607
-                );
608
-            }
609
-        }
610
-
611
-        if (! $DateTime instanceof DbSafeDateTime) {
612
-            // if still no datetime object, then let's just use now
613
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
614
-        }
615
-        // THEN apply the field's set DateTimeZone
616
-        $DateTime->setTimezone($this->_DateTimeZone);
617
-        //apparently in PHP5.6 this is needed to ensure the correct timestamp is internal on this object.  This fixes
618
-        //failing tests against PHP5.6 for the `Read_Test::test_handle_request_get_one__event` test.
619
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/11233
620
-        // and https://events.codebasehq.com/projects/event-espresso/tickets/11407
621
-        $DateTime->getTimestamp();
622
-        return $DateTime;
623
-    }
624
-
625
-
626
-    /**
627
-     * All this method does is determine if we're going to display the timezone string or not on any output.
628
-     * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
629
-     * If so, then true.
630
-     *
631
-     * @return bool true for yes false for no
632
-     * @throws \EE_Error
633
-     */
634
-    protected function _display_timezone()
635
-    {
636
-
637
-        // first let's do a comparison of timezone strings.
638
-        // If they match then we can get out without any further calculations
639
-        $blog_string = get_option('timezone_string');
640
-        if ($blog_string === $this->_timezone_string) {
641
-            return false;
642
-        }
643
-        // now we need to calc the offset for the timezone string so we can compare with the blog offset.
644
-        $this_offset = $this->get_timezone_offset($this->_DateTimeZone);
645
-        $blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
646
-        // now compare
647
-        return $blog_offset !== $this_offset;
648
-    }
649
-
650
-
651
-    /**
652
-     * This method returns a php DateTime object for setting on the EE_Base_Class model.
653
-     * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
654
-     * with.
655
-     *
656
-     * @param int|string|DateTime $date_string            This should be the incoming date string.  It's assumed to be
657
-     *                                                    in the format that is set on the date_field (or DateTime
658
-     *                                                    object)!
659
-     * @return DateTime
660
-     */
661
-    protected function _get_date_object($date_string)
662
-    {
663
-        //first if this is an empty date_string and nullable is allowed, just return null.
664
-        if ($this->_nullable && empty($date_string)) {
665
-            return null;
666
-        }
667
-
668
-        // if incoming date
669
-        if ($date_string instanceof DateTime) {
670
-            $date_string->setTimezone($this->_DateTimeZone);
671
-            // workaround for php datetime bug
672
-            // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
673
-            $date_string->getTimestamp();
674
-            return $date_string;
675
-        }
676
-        // if empty date_string and made it here.
677
-        // Return a datetime object for now in the given timezone.
678
-        if (empty($date_string)) {
679
-            return new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
680
-        }
681
-        // if $date_string is matches something that looks like a Unix timestamp let's just use it.
682
-        if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
683
-            try {
684
-                // This is operating under the assumption that the incoming Unix timestamp
685
-                // is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
686
-                $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
687
-                $DateTime->setTimestamp($date_string);
688
-
689
-                return $DateTime;
690
-            } catch (Exception $e) {
691
-                // should be rare, but if things got fooled then let's just continue
692
-            }
693
-        }
694
-        //not a unix timestamp.  So we will use the set format on this object and set timezone to
695
-        //create the DateTime object.
696
-        $format = $this->_date_format . ' ' . $this->_time_format;
697
-        try {
698
-            $DateTime = DateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
699
-            if ($DateTime instanceof DateTime) {
700
-                $DateTime = new DbSafeDateTime(
701
-                    $DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
702
-                    $this->_DateTimeZone
703
-                );
704
-            }
705
-            if (! $DateTime instanceof DbSafeDateTime) {
706
-                throw new EE_Error(
707
-                    sprintf(
708
-                        __('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
709
-                        $date_string,
710
-                        $format
711
-                    )
712
-                );
713
-            }
714
-        } catch (Exception $e) {
715
-            // if we made it here then likely then something went really wrong.
716
-            // Instead of throwing an exception, let's just return a DateTime object for now, in the set timezone.
717
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
718
-        }
719
-
720
-        return $DateTime;
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * get_timezone_transitions
727
-     *
728
-     * @param \DateTimeZone $DateTimeZone
729
-     * @param int           $time
730
-     * @param bool          $first_only
731
-     * @return mixed
732
-     */
733
-    public function get_timezone_transitions(DateTimeZone $DateTimeZone, $time = null, $first_only = true)
734
-    {
735
-        return EEH_DTT_Helper::get_timezone_transitions($DateTimeZone, $time, $first_only);
736
-    }
737
-
738
-
739
-
740
-    /**
741
-     * get_timezone_offset
742
-     *
743
-     * @param \DateTimeZone $DateTimeZone
744
-     * @param int           $time
745
-     * @return mixed
746
-     * @throws \DomainException
747
-     */
748
-    public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
749
-    {
750
-        return EEH_DTT_Helper::get_timezone_offset($DateTimeZone, $time);
751
-    }
752
-
753
-
754
-    /**
755
-     * This will take an incoming timezone string and return the abbreviation for that timezone
756
-     *
757
-     * @param  string $timezone_string
758
-     * @return string           abbreviation
759
-     * @throws \EE_Error
760
-     */
761
-    public function get_timezone_abbrev($timezone_string)
762
-    {
763
-        $timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
764
-        $dateTime        = new DateTime(\EE_Datetime_Field::now, new DateTimeZone($timezone_string));
765
-
766
-        return $dateTime->format('T');
767
-    }
768
-
769
-    /**
770
-     * Overrides the parent to allow for having a dynamic "now" value
771
-     *
772
-     * @return mixed
773
-     */
774
-    public function get_default_value()
775
-    {
776
-        if ($this->_default_value === EE_Datetime_Field::now) {
777
-            return time();
778
-        } else {
779
-            return parent::get_default_value();
780
-        }
781
-    }
782
-
783
-
784
-    public function getSchemaDescription()
785
-    {
786
-        return sprintf(
787
-            esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
788
-            $this->get_nicename()
789
-        );
790
-    }
553
+						'event_espresso'
554
+					),
555
+					'<br />',
556
+					print_r($datetime_value, true)
557
+				)
558
+			);
559
+		}
560
+
561
+		if ($datetime_value instanceof DateTime) {
562
+			if (! $datetime_value instanceof DbSafeDateTime) {
563
+				$datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
564
+			}
565
+
566
+			$datetime_value->setTimezone($this->get_UTC_DateTimeZone());
567
+			// workaround for php datetime bug
568
+			// @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
569
+			$datetime_value->getTimestamp();
570
+			return $datetime_value->format(
571
+				EE_Datetime_Field::mysql_timestamp_format
572
+			);
573
+		}
574
+
575
+		// if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
576
+		return ! $this->_nullable && empty($datetime_value) ? current_time('mysql', true) : null;
577
+	}
578
+
579
+
580
+	/**
581
+	 * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
582
+	 * allowed)
583
+	 *
584
+	 * @param string $datetime_string mysql timestamp in UTC
585
+	 * @return  mixed null | DateTime
586
+	 * @throws \EE_Error
587
+	 */
588
+	public function prepare_for_set_from_db($datetime_string)
589
+	{
590
+		//if $datetime_value is empty, and ! $this->_nullable, just use time()
591
+		if (empty($datetime_string) && $this->_nullable) {
592
+			return null;
593
+		}
594
+		// datetime strings from the db should ALWAYS be in UTC+0, so use UTC_DateTimeZone when creating
595
+		if (empty($datetime_string)) {
596
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
597
+		} else {
598
+			$DateTime = DateTime::createFromFormat(
599
+				EE_Datetime_Field::mysql_timestamp_format,
600
+				$datetime_string,
601
+				$this->get_UTC_DateTimeZone()
602
+			);
603
+			if ($DateTime instanceof \DateTime) {
604
+				$DateTime = new DbSafeDateTime(
605
+					$DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
606
+					$this->get_UTC_DateTimeZone()
607
+				);
608
+			}
609
+		}
610
+
611
+		if (! $DateTime instanceof DbSafeDateTime) {
612
+			// if still no datetime object, then let's just use now
613
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
614
+		}
615
+		// THEN apply the field's set DateTimeZone
616
+		$DateTime->setTimezone($this->_DateTimeZone);
617
+		//apparently in PHP5.6 this is needed to ensure the correct timestamp is internal on this object.  This fixes
618
+		//failing tests against PHP5.6 for the `Read_Test::test_handle_request_get_one__event` test.
619
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/11233
620
+		// and https://events.codebasehq.com/projects/event-espresso/tickets/11407
621
+		$DateTime->getTimestamp();
622
+		return $DateTime;
623
+	}
624
+
625
+
626
+	/**
627
+	 * All this method does is determine if we're going to display the timezone string or not on any output.
628
+	 * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
629
+	 * If so, then true.
630
+	 *
631
+	 * @return bool true for yes false for no
632
+	 * @throws \EE_Error
633
+	 */
634
+	protected function _display_timezone()
635
+	{
636
+
637
+		// first let's do a comparison of timezone strings.
638
+		// If they match then we can get out without any further calculations
639
+		$blog_string = get_option('timezone_string');
640
+		if ($blog_string === $this->_timezone_string) {
641
+			return false;
642
+		}
643
+		// now we need to calc the offset for the timezone string so we can compare with the blog offset.
644
+		$this_offset = $this->get_timezone_offset($this->_DateTimeZone);
645
+		$blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
646
+		// now compare
647
+		return $blog_offset !== $this_offset;
648
+	}
649
+
650
+
651
+	/**
652
+	 * This method returns a php DateTime object for setting on the EE_Base_Class model.
653
+	 * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
654
+	 * with.
655
+	 *
656
+	 * @param int|string|DateTime $date_string            This should be the incoming date string.  It's assumed to be
657
+	 *                                                    in the format that is set on the date_field (or DateTime
658
+	 *                                                    object)!
659
+	 * @return DateTime
660
+	 */
661
+	protected function _get_date_object($date_string)
662
+	{
663
+		//first if this is an empty date_string and nullable is allowed, just return null.
664
+		if ($this->_nullable && empty($date_string)) {
665
+			return null;
666
+		}
667
+
668
+		// if incoming date
669
+		if ($date_string instanceof DateTime) {
670
+			$date_string->setTimezone($this->_DateTimeZone);
671
+			// workaround for php datetime bug
672
+			// @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
673
+			$date_string->getTimestamp();
674
+			return $date_string;
675
+		}
676
+		// if empty date_string and made it here.
677
+		// Return a datetime object for now in the given timezone.
678
+		if (empty($date_string)) {
679
+			return new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
680
+		}
681
+		// if $date_string is matches something that looks like a Unix timestamp let's just use it.
682
+		if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
683
+			try {
684
+				// This is operating under the assumption that the incoming Unix timestamp
685
+				// is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
686
+				$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
687
+				$DateTime->setTimestamp($date_string);
688
+
689
+				return $DateTime;
690
+			} catch (Exception $e) {
691
+				// should be rare, but if things got fooled then let's just continue
692
+			}
693
+		}
694
+		//not a unix timestamp.  So we will use the set format on this object and set timezone to
695
+		//create the DateTime object.
696
+		$format = $this->_date_format . ' ' . $this->_time_format;
697
+		try {
698
+			$DateTime = DateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
699
+			if ($DateTime instanceof DateTime) {
700
+				$DateTime = new DbSafeDateTime(
701
+					$DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
702
+					$this->_DateTimeZone
703
+				);
704
+			}
705
+			if (! $DateTime instanceof DbSafeDateTime) {
706
+				throw new EE_Error(
707
+					sprintf(
708
+						__('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
709
+						$date_string,
710
+						$format
711
+					)
712
+				);
713
+			}
714
+		} catch (Exception $e) {
715
+			// if we made it here then likely then something went really wrong.
716
+			// Instead of throwing an exception, let's just return a DateTime object for now, in the set timezone.
717
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
718
+		}
719
+
720
+		return $DateTime;
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * get_timezone_transitions
727
+	 *
728
+	 * @param \DateTimeZone $DateTimeZone
729
+	 * @param int           $time
730
+	 * @param bool          $first_only
731
+	 * @return mixed
732
+	 */
733
+	public function get_timezone_transitions(DateTimeZone $DateTimeZone, $time = null, $first_only = true)
734
+	{
735
+		return EEH_DTT_Helper::get_timezone_transitions($DateTimeZone, $time, $first_only);
736
+	}
737
+
738
+
739
+
740
+	/**
741
+	 * get_timezone_offset
742
+	 *
743
+	 * @param \DateTimeZone $DateTimeZone
744
+	 * @param int           $time
745
+	 * @return mixed
746
+	 * @throws \DomainException
747
+	 */
748
+	public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
749
+	{
750
+		return EEH_DTT_Helper::get_timezone_offset($DateTimeZone, $time);
751
+	}
752
+
753
+
754
+	/**
755
+	 * This will take an incoming timezone string and return the abbreviation for that timezone
756
+	 *
757
+	 * @param  string $timezone_string
758
+	 * @return string           abbreviation
759
+	 * @throws \EE_Error
760
+	 */
761
+	public function get_timezone_abbrev($timezone_string)
762
+	{
763
+		$timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
764
+		$dateTime        = new DateTime(\EE_Datetime_Field::now, new DateTimeZone($timezone_string));
765
+
766
+		return $dateTime->format('T');
767
+	}
768
+
769
+	/**
770
+	 * Overrides the parent to allow for having a dynamic "now" value
771
+	 *
772
+	 * @return mixed
773
+	 */
774
+	public function get_default_value()
775
+	{
776
+		if ($this->_default_value === EE_Datetime_Field::now) {
777
+			return time();
778
+		} else {
779
+			return parent::get_default_value();
780
+		}
781
+	}
782
+
783
+
784
+	public function getSchemaDescription()
785
+	{
786
+		return sprintf(
787
+			esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
788
+			$this->get_nicename()
789
+		);
790
+	}
791 791
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -214,8 +214,8 @@  discard block
 block discarded – undo
214 214
 
215 215
             default :
216 216
                 return $pretty
217
-                    ? $this->_pretty_date_format . ' ' . $this->_pretty_time_format
218
-                    : $this->_date_format . ' ' . $this->_time_format;
217
+                    ? $this->_pretty_date_format.' '.$this->_pretty_time_format
218
+                    : $this->_date_format.' '.$this->_time_format;
219 219
         }
220 220
     }
221 221
 
@@ -481,7 +481,7 @@  discard block
 block discarded – undo
481 481
      */
482 482
     protected function _prepare_for_display($DateTime, $schema = false)
483 483
     {
484
-        if (! $DateTime instanceof DateTime) {
484
+        if ( ! $DateTime instanceof DateTime) {
485 485
             if ($this->_nullable) {
486 486
                 return '';
487 487
             } else {
@@ -519,15 +519,15 @@  discard block
 block discarded – undo
519 519
             if ($this->_display_timezone()) {
520 520
                 //must be explicit because schema could equal true.
521 521
                 if ($schema === 'no_html') {
522
-                    $timezone_string = ' (' . $DateTime->format('T') . ')';
522
+                    $timezone_string = ' ('.$DateTime->format('T').')';
523 523
                 } else {
524
-                    $timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
524
+                    $timezone_string = ' <span class="ee_dtt_timezone_string">('.$DateTime->format('T').')</span>';
525 525
                 }
526 526
             } else {
527 527
                 $timezone_string = '';
528 528
             }
529 529
 
530
-            return $DateTime->format($format_string) . $timezone_string;
530
+            return $DateTime->format($format_string).$timezone_string;
531 531
         }
532 532
         return $DateTime->format($format_string);
533 533
     }
@@ -544,7 +544,7 @@  discard block
 block discarded – undo
544 544
     public function prepare_for_use_in_db($datetime_value)
545 545
     {
546 546
         //we allow an empty value or DateTime object, but nothing else.
547
-        if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
547
+        if ( ! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
548 548
             throw new EE_Error(
549 549
             	sprintf(
550 550
             	    __(
@@ -559,7 +559,7 @@  discard block
 block discarded – undo
559 559
         }
560 560
 
561 561
         if ($datetime_value instanceof DateTime) {
562
-            if (! $datetime_value instanceof DbSafeDateTime) {
562
+            if ( ! $datetime_value instanceof DbSafeDateTime) {
563 563
                 $datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
564 564
             }
565 565
 
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
             }
609 609
         }
610 610
 
611
-        if (! $DateTime instanceof DbSafeDateTime) {
611
+        if ( ! $DateTime instanceof DbSafeDateTime) {
612 612
             // if still no datetime object, then let's just use now
613 613
             $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
614 614
         }
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
         }
694 694
         //not a unix timestamp.  So we will use the set format on this object and set timezone to
695 695
         //create the DateTime object.
696
-        $format = $this->_date_format . ' ' . $this->_time_format;
696
+        $format = $this->_date_format.' '.$this->_time_format;
697 697
         try {
698 698
             $DateTime = DateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
699 699
             if ($DateTime instanceof DateTime) {
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
                     $this->_DateTimeZone
703 703
                 );
704 704
             }
705
-            if (! $DateTime instanceof DbSafeDateTime) {
705
+            if ( ! $DateTime instanceof DbSafeDateTime) {
706 706
                 throw new EE_Error(
707 707
                     sprintf(
708 708
                         __('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6180 added lines, -6180 removed lines patch added patch discarded remove patch
@@ -34,6188 +34,6188 @@
 block discarded – undo
34 34
 abstract class EEM_Base extends EE_Base implements ResettableInterface
35 35
 {
36 36
 
37
-    /**
38
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
-     * They almost always WILL NOT, but it's not necessarily a requirement.
41
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
-     *
43
-     * @var boolean
44
-     */
45
-    private $_values_already_prepared_by_model_object = 0;
46
-
47
-    /**
48
-     * when $_values_already_prepared_by_model_object equals this, we assume
49
-     * the data is just like form input that needs to have the model fields'
50
-     * prepare_for_set and prepare_for_use_in_db called on it
51
-     */
52
-    const not_prepared_by_model_object = 0;
53
-
54
-    /**
55
-     * when $_values_already_prepared_by_model_object equals this, we
56
-     * assume this value is coming from a model object and doesn't need to have
57
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
58
-     */
59
-    const prepared_by_model_object = 1;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the values are already to be used in the database (ie no processing is done
64
-     * on them by the model's fields)
65
-     */
66
-    const prepared_for_use_in_db = 2;
67
-
68
-
69
-    protected $singular_item = 'Item';
70
-
71
-    protected $plural_item   = 'Items';
72
-
73
-    /**
74
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
-     */
76
-    protected $_tables;
77
-
78
-    /**
79
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
-     *
83
-     * @var \EE_Model_Field_Base[][] $_fields
84
-     */
85
-    protected $_fields;
86
-
87
-    /**
88
-     * array of different kinds of relations
89
-     *
90
-     * @var \EE_Model_Relation_Base[] $_model_relations
91
-     */
92
-    protected $_model_relations;
93
-
94
-    /**
95
-     * @var \EE_Index[] $_indexes
96
-     */
97
-    protected $_indexes = array();
98
-
99
-    /**
100
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
101
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
-     * by setting the same columns as used in these queries in the query yourself.
103
-     *
104
-     * @var EE_Default_Where_Conditions
105
-     */
106
-    protected $_default_where_conditions_strategy;
107
-
108
-    /**
109
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
-     * This is particularly useful when you want something between 'none' and 'default'
111
-     *
112
-     * @var EE_Default_Where_Conditions
113
-     */
114
-    protected $_minimum_where_conditions_strategy;
115
-
116
-    /**
117
-     * String describing how to find the "owner" of this model's objects.
118
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
-     * But when there isn't, this indicates which related model, or transiently-related model,
120
-     * has the foreign key to the wp_users table.
121
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
-     * related to events, and events have a foreign key to wp_users.
123
-     * On EEM_Transaction, this would be 'Transaction.Event'
124
-     *
125
-     * @var string
126
-     */
127
-    protected $_model_chain_to_wp_user = '';
128
-
129
-    /**
130
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
-     * don't need it (particularly CPT models)
132
-     *
133
-     * @var bool
134
-     */
135
-    protected $_ignore_where_strategy = false;
136
-
137
-    /**
138
-     * String used in caps relating to this model. Eg, if the caps relating to this
139
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
-     *
141
-     * @var string. If null it hasn't been initialized yet. If false then we
142
-     * have indicated capabilities don't apply to this
143
-     */
144
-    protected $_caps_slug = null;
145
-
146
-    /**
147
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
-     * and next-level keys are capability names, and each's value is a
149
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
-     * they specify which context to use (ie, frontend, backend, edit or delete)
151
-     * and then each capability in the corresponding sub-array that they're missing
152
-     * adds the where conditions onto the query.
153
-     *
154
-     * @var array
155
-     */
156
-    protected $_cap_restrictions = array(
157
-        self::caps_read       => array(),
158
-        self::caps_read_admin => array(),
159
-        self::caps_edit       => array(),
160
-        self::caps_delete     => array(),
161
-    );
162
-
163
-    /**
164
-     * Array defining which cap restriction generators to use to create default
165
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
166
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
-     * automatically set this to false (not just null).
169
-     *
170
-     * @var EE_Restriction_Generator_Base[]
171
-     */
172
-    protected $_cap_restriction_generators = array();
173
-
174
-    /**
175
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
-     */
177
-    const caps_read       = 'read';
178
-
179
-    const caps_read_admin = 'read_admin';
180
-
181
-    const caps_edit       = 'edit';
182
-
183
-    const caps_delete     = 'delete';
184
-
185
-    /**
186
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
-     * maps to 'read' because when looking for relevant permissions we're going to use
189
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
190
-     *
191
-     * @var array
192
-     */
193
-    protected $_cap_contexts_to_cap_action_map = array(
194
-        self::caps_read       => 'read',
195
-        self::caps_read_admin => 'read',
196
-        self::caps_edit       => 'edit',
197
-        self::caps_delete     => 'delete',
198
-    );
199
-
200
-    /**
201
-     * Timezone
202
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
-     * EE_Datetime_Field data type will have access to it.
206
-     *
207
-     * @var string
208
-     */
209
-    protected $_timezone;
210
-
211
-
212
-    /**
213
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
-     * multisite.
215
-     *
216
-     * @var int
217
-     */
218
-    protected static $_model_query_blog_id;
219
-
220
-    /**
221
-     * A copy of _fields, except the array keys are the model names pointed to by
222
-     * the field
223
-     *
224
-     * @var EE_Model_Field_Base[]
225
-     */
226
-    private $_cache_foreign_key_to_fields = array();
227
-
228
-    /**
229
-     * Cached list of all the fields on the model, indexed by their name
230
-     *
231
-     * @var EE_Model_Field_Base[]
232
-     */
233
-    private $_cached_fields = null;
234
-
235
-    /**
236
-     * Cached list of all the fields on the model, except those that are
237
-     * marked as only pertinent to the database
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cached_fields_non_db_only = null;
242
-
243
-    /**
244
-     * A cached reference to the primary key for quick lookup
245
-     *
246
-     * @var EE_Model_Field_Base
247
-     */
248
-    private $_primary_key_field = null;
249
-
250
-    /**
251
-     * Flag indicating whether this model has a primary key or not
252
-     *
253
-     * @var boolean
254
-     */
255
-    protected $_has_primary_key_field = null;
256
-
257
-    /**
258
-     * Whether or not this model is based off a table in WP core only (CPTs should set
259
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
-     * This should be true for models that deal with data that should exist independent of EE.
261
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
263
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
265
-     * @var boolean
266
-     */
267
-    protected $_wp_core_model = false;
268
-
269
-    /**
270
-     *    List of valid operators that can be used for querying.
271
-     * The keys are all operators we'll accept, the values are the real SQL
272
-     * operators used
273
-     *
274
-     * @var array
275
-     */
276
-    protected $_valid_operators = array(
277
-        '='           => '=',
278
-        '<='          => '<=',
279
-        '<'           => '<',
280
-        '>='          => '>=',
281
-        '>'           => '>',
282
-        '!='          => '!=',
283
-        'LIKE'        => 'LIKE',
284
-        'like'        => 'LIKE',
285
-        'NOT_LIKE'    => 'NOT LIKE',
286
-        'not_like'    => 'NOT LIKE',
287
-        'NOT LIKE'    => 'NOT LIKE',
288
-        'not like'    => 'NOT LIKE',
289
-        'IN'          => 'IN',
290
-        'in'          => 'IN',
291
-        'NOT_IN'      => 'NOT IN',
292
-        'not_in'      => 'NOT IN',
293
-        'NOT IN'      => 'NOT IN',
294
-        'not in'      => 'NOT IN',
295
-        'between'     => 'BETWEEN',
296
-        'BETWEEN'     => 'BETWEEN',
297
-        'IS_NOT_NULL' => 'IS NOT NULL',
298
-        'is_not_null' => 'IS NOT NULL',
299
-        'IS NOT NULL' => 'IS NOT NULL',
300
-        'is not null' => 'IS NOT NULL',
301
-        'IS_NULL'     => 'IS NULL',
302
-        'is_null'     => 'IS NULL',
303
-        'IS NULL'     => 'IS NULL',
304
-        'is null'     => 'IS NULL',
305
-        'REGEXP'      => 'REGEXP',
306
-        'regexp'      => 'REGEXP',
307
-        'NOT_REGEXP'  => 'NOT REGEXP',
308
-        'not_regexp'  => 'NOT REGEXP',
309
-        'NOT REGEXP'  => 'NOT REGEXP',
310
-        'not regexp'  => 'NOT REGEXP',
311
-    );
312
-
313
-    /**
314
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_in_style_operators = array('IN', 'NOT IN');
319
-
320
-    /**
321
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
-     * '12-31-2012'"
323
-     *
324
-     * @var array
325
-     */
326
-    protected $_between_style_operators = array('BETWEEN');
327
-
328
-    /**
329
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
-     * @var array
331
-     */
332
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
-    /**
334
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
-     * on a join table.
336
-     *
337
-     * @var array
338
-     */
339
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
-
341
-    /**
342
-     * Allowed values for $query_params['order'] for ordering in queries
343
-     *
344
-     * @var array
345
-     */
346
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
-
348
-    /**
349
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
351
-     *
352
-     * @var array
353
-     */
354
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
-
356
-    /**
357
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
359
-     *
360
-     * @var array
361
-     */
362
-    private $_allowed_query_params = array(
363
-        0,
364
-        'limit',
365
-        'order_by',
366
-        'group_by',
367
-        'having',
368
-        'force_join',
369
-        'order',
370
-        'on_join_limit',
371
-        'default_where_conditions',
372
-        'caps',
373
-        'extra_selects'
374
-    );
375
-
376
-    /**
377
-     * All the data types that can be used in $wpdb->prepare statements.
378
-     *
379
-     * @var array
380
-     */
381
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
-
383
-    /**
384
-     * @var EE_Registry $EE
385
-     */
386
-    protected $EE = null;
387
-
388
-
389
-    /**
390
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
-     *
392
-     * @var int
393
-     */
394
-    protected $_show_next_x_db_queries = 0;
395
-
396
-    /**
397
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
-     * WHERE, GROUP_BY, etc.
400
-     *
401
-     * @var CustomSelects
402
-     */
403
-    protected $_custom_selections = array();
404
-
405
-    /**
406
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
-     * caches every model object we've fetched from the DB on this request
408
-     *
409
-     * @var array
410
-     */
411
-    protected $_entity_map;
412
-
413
-    /**
414
-     * @var LoaderInterface $loader
415
-     */
416
-    private static $loader;
417
-
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
520
-                sprintf(
521
-                    __('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.',
522
-                        'event_espresso'),
523
-                    get_class($this)
524
-                )
525
-            );
526
-        }
527
-        /**
528
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
-         */
530
-        if (empty(EEM_Base::$_model_query_blog_id)) {
531
-            EEM_Base::set_model_query_blog_id();
532
-        }
533
-        /**
534
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
-         * just use EE_Register_Model_Extension
536
-         *
537
-         * @var EE_Table_Base[] $_tables
538
-         */
539
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
-        foreach ($this->_tables as $table_alias => $table_obj) {
541
-            /** @var $table_obj EE_Table_Base */
542
-            $table_obj->_construct_finalize_with_alias($table_alias);
543
-            if ($table_obj instanceof EE_Secondary_Table) {
544
-                /** @var $table_obj EE_Secondary_Table */
545
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
-            }
547
-        }
548
-        /**
549
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
-         * EE_Register_Model_Extension
551
-         *
552
-         * @param EE_Model_Field_Base[] $_fields
553
-         */
554
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
-        $this->_invalidate_field_caches();
556
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
-            }
561
-            foreach ($fields_for_table as $field_name => $field_obj) {
562
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
-                //primary key field base has a slightly different _construct_finalize
564
-                /** @var $field_obj EE_Model_Field_Base */
565
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
-            }
567
-        }
568
-        // everything is related to Extra_Meta
569
-        if (get_class($this) !== 'EEM_Extra_Meta') {
570
-            //make extra meta related to everything, but don't block deleting things just
571
-            //because they have related extra meta info. For now just orphan those extra meta
572
-            //in the future we should automatically delete them
573
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        //and change logs
576
-        if (get_class($this) !== 'EEM_Change_Log') {
577
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        /**
580
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
-         * EE_Register_Model_Extension
582
-         *
583
-         * @param EE_Model_Relation_Base[] $_model_relations
584
-         */
585
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
-            $this->_model_relations);
587
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
-            /** @var $relation_obj EE_Model_Relation_Base */
589
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
-        }
591
-        foreach ($this->_indexes as $index_name => $index_obj) {
592
-            /** @var $index_obj EE_Index */
593
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
-        }
595
-        $this->set_timezone($timezone);
596
-        //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
603
-            //nothing was set during child constructor, so set default
604
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
-        }
606
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
-        //to indicate to NOT set it, set it to the logical default
609
-        if ($this->_caps_slug === null) {
610
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
-        }
612
-        //initialize the standard cap restriction generators if none were specified by the child constructor
613
-        if ($this->_cap_restriction_generators !== false) {
614
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
-                        new EE_Restriction_Generator_Protected(),
619
-                        $cap_context,
620
-                        $this
621
-                    );
622
-                }
623
-            }
624
-        }
625
-        //if there are cap restriction generators, use them to make the default cap restrictions
626
-        if ($this->_cap_restriction_generators !== false) {
627
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
629
-                    continue;
630
-                }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
-                    throw new EE_Error(
633
-                        sprintf(
634
-                            __('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.',
635
-                                'event_espresso'),
636
-                            $context,
637
-                            $this->get_this_model_name()
638
-                        )
639
-                    );
640
-                }
641
-                $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
643
-                    $generator_object->_construct_finalize($this, $action);
644
-                }
645
-            }
646
-        }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Used to set the $_model_query_blog_id static property.
654
-     *
655
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
656
-     *                      value for get_current_blog_id() will be used.
657
-     */
658
-    public static function set_model_query_blog_id($blog_id = 0)
659
-    {
660
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
661
-    }
662
-
663
-
664
-
665
-    /**
666
-     * Returns whatever is set as the internal $model_query_blog_id.
667
-     *
668
-     * @return int
669
-     */
670
-    public static function get_model_query_blog_id()
671
-    {
672
-        return EEM_Base::$_model_query_blog_id;
673
-    }
674
-
675
-
676
-
677
-    /**
678
-     * This function is a singleton method used to instantiate the Espresso_model object
679
-     *
680
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
681
-     *                                (and any incoming timezone data that gets saved).
682
-     *                                Note this just sends the timezone info to the date time model field objects.
683
-     *                                Default is NULL
684
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
685
-     * @return static (as in the concrete child class)
686
-     * @throws EE_Error
687
-     * @throws InvalidArgumentException
688
-     * @throws InvalidDataTypeException
689
-     * @throws InvalidInterfaceException
690
-     */
691
-    public static function instance($timezone = null)
692
-    {
693
-        // check if instance of Espresso_model already exists
694
-        if (! static::$_instance instanceof static) {
695
-            // instantiate Espresso_model
696
-            static::$_instance = new static(
697
-                $timezone,
698
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
699
-            );
700
-        }
701
-        //we might have a timezone set, let set_timezone decide what to do with it
702
-        static::$_instance->set_timezone($timezone);
703
-        // Espresso_model object
704
-        return static::$_instance;
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     * resets the model and returns it
711
-     *
712
-     * @param null | string $timezone
713
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
714
-     * all its properties reset; if it wasn't instantiated, returns null)
715
-     * @throws EE_Error
716
-     * @throws ReflectionException
717
-     * @throws InvalidArgumentException
718
-     * @throws InvalidDataTypeException
719
-     * @throws InvalidInterfaceException
720
-     */
721
-    public static function reset($timezone = null)
722
-    {
723
-        if (static::$_instance instanceof EEM_Base) {
724
-            //let's try to NOT swap out the current instance for a new one
725
-            //because if someone has a reference to it, we can't remove their reference
726
-            //so it's best to keep using the same reference, but change the original object
727
-            //reset all its properties to their original values as defined in the class
728
-            $r = new ReflectionClass(get_class(static::$_instance));
729
-            $static_properties = $r->getStaticProperties();
730
-            foreach ($r->getDefaultProperties() as $property => $value) {
731
-                //don't set instance to null like it was originally,
732
-                //but it's static anyways, and we're ignoring static properties (for now at least)
733
-                if (! isset($static_properties[$property])) {
734
-                    static::$_instance->{$property} = $value;
735
-                }
736
-            }
737
-            //and then directly call its constructor again, like we would if we were creating a new one
738
-            static::$_instance->__construct(
739
-                $timezone,
740
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
741
-            );
742
-            return self::instance();
743
-        }
744
-        return null;
745
-    }
746
-
747
-
748
-
749
-    /**
750
-     * @return LoaderInterface
751
-     * @throws InvalidArgumentException
752
-     * @throws InvalidDataTypeException
753
-     * @throws InvalidInterfaceException
754
-     */
755
-    private static function getLoader()
756
-    {
757
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
758
-            EEM_Base::$loader = LoaderFactory::getLoader();
759
-        }
760
-        return EEM_Base::$loader;
761
-    }
762
-
763
-
764
-
765
-    /**
766
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
767
-     *
768
-     * @param  boolean $translated return localized strings or JUST the array.
769
-     * @return array
770
-     * @throws EE_Error
771
-     * @throws InvalidArgumentException
772
-     * @throws InvalidDataTypeException
773
-     * @throws InvalidInterfaceException
774
-     */
775
-    public function status_array($translated = false)
776
-    {
777
-        if (! array_key_exists('Status', $this->_model_relations)) {
778
-            return array();
779
-        }
780
-        $model_name = $this->get_this_model_name();
781
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
782
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
783
-        $status_array = array();
784
-        foreach ($stati as $status) {
785
-            $status_array[$status->ID()] = $status->get('STS_code');
786
-        }
787
-        return $translated
788
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
789
-            : $status_array;
790
-    }
791
-
792
-
793
-
794
-    /**
795
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
796
-     *
797
-     * @param array $query_params             {
798
-     * @var array $0 (where) array {
799
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
800
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
801
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
802
-     *                                        conditions based on related models (and even
803
-     *                                        models-related-to-related-models) prepend the model's name onto the field
804
-     *                                        name. Eg,
805
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
806
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
807
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
808
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
809
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
810
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
811
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
812
-     *                                        to Venues (even when each of those models actually consisted of two
813
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
814
-     *                                        just having
815
-     *                                        "Venue.VNU_ID", you could have
816
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
817
-     *                                        events are related to Registrations, which are related to Attendees). You
818
-     *                                        can take it even further with
819
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
820
-     *                                        (from the default of '='), change the value to an numerically-indexed
821
-     *                                        array, where the first item in the list is the operator. eg: array(
822
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
823
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
824
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
825
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
826
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
827
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
828
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
829
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
830
-     *                                        the value is a field, simply provide a third array item (true) to the
831
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
832
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
833
-     *                                        Note: you can also use related model field names like you would any other
834
-     *                                        field name. eg:
835
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
836
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
837
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
838
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
839
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
840
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
841
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
842
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
843
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
844
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
845
-     *                                        "stick" until you specify an AND. eg
846
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
847
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
848
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
849
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
850
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
851
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
852
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
853
-     *                                        too, eg:
854
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
855
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
856
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
857
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
858
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
859
-     *                                        the OFFSET, the 2nd is the LIMIT
860
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
861
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
862
-     *                                        following format array('on_join_limit'
863
-     *                                        => array( 'table_alias', array(1,2) ) ).
864
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
865
-     *                                        values are either 'ASC' or 'DESC'.
866
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
867
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
868
-     *                                        DESC..." respectively. Like the
869
-     *                                        'where' conditions, these fields can be on related models. Eg
870
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
871
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
872
-     *                                        Attendee, Price, Datetime, etc.)
873
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
874
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
875
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
876
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
877
-     *                                        order by the primary key. Eg,
878
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
879
-     *                                        //(will join with the Datetime model's table(s) and order by its field
880
-     *                                        DTT_EVT_start) or
881
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
882
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
883
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
884
-     *                                        'group_by'=>'VNU_ID', or
885
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
886
-     *                                        if no
887
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
888
-     *                                        model's primary key (or combined primary keys). This avoids some
889
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
890
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
891
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
892
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
893
-     *                                        results)
894
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
895
-     *                                        array where values are models to be joined in the query.Eg
896
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
897
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
898
-     *                                        probably only want to do this in hopes of increasing efficiency, as
899
-     *                                        related models which belongs to the current model
900
-     *                                        (ie, the current model has a foreign key to them, like how Registration
901
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
902
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
903
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
904
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
905
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
906
-     *                                        default where conditions set it to 'other_models_only'. If you only want
907
-     *                                        this model's default where conditions added to the query, use
908
-     *                                        'this_model_only'. If you want to use all default where conditions
909
-     *                                        (default), set to 'all'.
910
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
911
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
912
-     *                                        everything? Or should we only show the current user items they should be
913
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
914
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
915
-     *                                        }
916
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
917
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
918
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
919
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
920
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
921
-     *                                        array( array(
922
-     *                                        'OR'=>array(
923
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
924
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
925
-     *                                        )
926
-     *                                        ),
927
-     *                                        'limit'=>10,
928
-     *                                        'group_by'=>'TXN_ID'
929
-     *                                        ));
930
-     *                                        get all the answers to the question titled "shirt size" for event with id
931
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
932
-     *                                        'Question.QST_display_text'=>'shirt size',
933
-     *                                        'Registration.Event.EVT_ID'=>12
934
-     *                                        ),
935
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
936
-     *                                        ));
937
-     * @throws EE_Error
938
-     */
939
-    public function get_all($query_params = array())
940
-    {
941
-        if (isset($query_params['limit'])
942
-            && ! isset($query_params['group_by'])
943
-        ) {
944
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
945
-        }
946
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
947
-    }
948
-
949
-
950
-
951
-    /**
952
-     * Modifies the query parameters so we only get back model objects
953
-     * that "belong" to the current user
954
-     *
955
-     * @param array $query_params @see EEM_Base::get_all()
956
-     * @return array like EEM_Base::get_all
957
-     */
958
-    public function alter_query_params_to_only_include_mine($query_params = array())
959
-    {
960
-        $wp_user_field_name = $this->wp_user_field_name();
961
-        if ($wp_user_field_name) {
962
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
963
-        }
964
-        return $query_params;
965
-    }
966
-
967
-
968
-
969
-    /**
970
-     * Returns the name of the field's name that points to the WP_User table
971
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
972
-     * foreign key to the WP_User table)
973
-     *
974
-     * @return string|boolean string on success, boolean false when there is no
975
-     * foreign key to the WP_User table
976
-     */
977
-    public function wp_user_field_name()
978
-    {
979
-        try {
980
-            if (! empty($this->_model_chain_to_wp_user)) {
981
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982
-                $last_model_name = end($models_to_follow_to_wp_users);
983
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
985
-            } else {
986
-                $model_with_fk_to_wp_users = $this;
987
-                $model_chain_to_wp_user = '';
988
-            }
989
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
991
-        } catch (EE_Error $e) {
992
-            return false;
993
-        }
994
-    }
995
-
996
-
997
-
998
-    /**
999
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
1000
-     * (or transiently-related model) has a foreign key to the wp_users table;
1001
-     * useful for finding if model objects of this type are 'owned' by the current user.
1002
-     * This is an empty string when the foreign key is on this model and when it isn't,
1003
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
1004
-     * (or transiently-related model)
1005
-     *
1006
-     * @return string
1007
-     */
1008
-    public function model_chain_to_wp_user()
1009
-    {
1010
-        return $this->_model_chain_to_wp_user;
1011
-    }
1012
-
1013
-
1014
-
1015
-    /**
1016
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1017
-     * like how registrations don't have a foreign key to wp_users, but the
1018
-     * events they are for are), or is unrelated to wp users.
1019
-     * generally available
1020
-     *
1021
-     * @return boolean
1022
-     */
1023
-    public function is_owned()
1024
-    {
1025
-        if ($this->model_chain_to_wp_user()) {
1026
-            return true;
1027
-        }
1028
-        try {
1029
-            $this->get_foreign_key_to('WP_User');
1030
-            return true;
1031
-        } catch (EE_Error $e) {
1032
-            return false;
1033
-        }
1034
-    }
1035
-
1036
-
1037
-    /**
1038
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1039
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1040
-     * the model)
1041
-     *
1042
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1043
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1044
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1045
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1046
-     *                                  override this and set the select to "*", or a specific column name, like
1047
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1048
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1049
-     *                                  the aliases used to refer to this selection, and values are to be
1050
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1051
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1052
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1053
-     * @throws EE_Error
1054
-     * @throws InvalidArgumentException
1055
-     */
1056
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057
-    {
1058
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1059
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1060
-        $select_expressions = $columns_to_select === null
1061
-            ? $this->_construct_default_select_sql($model_query_info)
1062
-            : '';
1063
-        if ($this->_custom_selections instanceof CustomSelects) {
1064
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065
-            $select_expressions .= $select_expressions
1066
-                ? ', ' . $custom_expressions
1067
-                : $custom_expressions;
1068
-        }
1069
-
1070
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1071
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072
-    }
1073
-
1074
-
1075
-    /**
1076
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1077
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1078
-     * method of including extra select information.
1079
-     *
1080
-     * @param array             $query_params
1081
-     * @param null|array|string $columns_to_select
1082
-     * @return null|CustomSelects
1083
-     * @throws InvalidArgumentException
1084
-     */
1085
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086
-    {
1087
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088
-            return null;
1089
-        }
1090
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1091
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1092
-        return new CustomSelects($selects);
1093
-    }
1094
-
1095
-
1096
-
1097
-    /**
1098
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1099
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1100
-     * take care of joins, field preparation etc.
1101
-     *
1102
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1103
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1104
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1105
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1106
-     *                                  override this and set the select to "*", or a specific column name, like
1107
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1108
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1109
-     *                                  the aliases used to refer to this selection, and values are to be
1110
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1111
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1112
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1113
-     * @throws EE_Error
1114
-     */
1115
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1116
-    {
1117
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1118
-    }
1119
-
1120
-
1121
-
1122
-    /**
1123
-     * For creating a custom select statement
1124
-     *
1125
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1126
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1127
-     *                                 SQL, and 1=>is the datatype
1128
-     * @throws EE_Error
1129
-     * @return string
1130
-     */
1131
-    private function _construct_select_from_input($columns_to_select)
1132
-    {
1133
-        if (is_array($columns_to_select)) {
1134
-            $select_sql_array = array();
1135
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137
-                    throw new EE_Error(
1138
-                        sprintf(
1139
-                            __(
1140
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1141
-                                'event_espresso'
1142
-                            ),
1143
-                            $selection_and_datatype,
1144
-                            $alias
1145
-                        )
1146
-                    );
1147
-                }
1148
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149
-                    throw new EE_Error(
1150
-                        sprintf(
1151
-                            esc_html__(
1152
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1153
-                                'event_espresso'
1154
-                            ),
1155
-                            $selection_and_datatype[1],
1156
-                            $selection_and_datatype[0],
1157
-                            $alias,
1158
-                            implode(', ', $this->_valid_wpdb_data_types)
1159
-                        )
1160
-                    );
1161
-                }
1162
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1163
-            }
1164
-            $columns_to_select_string = implode(', ', $select_sql_array);
1165
-        } else {
1166
-            $columns_to_select_string = $columns_to_select;
1167
-        }
1168
-        return $columns_to_select_string;
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1175
-     *
1176
-     * @return string
1177
-     * @throws EE_Error
1178
-     */
1179
-    public function primary_key_name()
1180
-    {
1181
-        return $this->get_primary_key_field()->get_name();
1182
-    }
1183
-
1184
-
1185
-
1186
-    /**
1187
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1188
-     * If there is no primary key on this model, $id is treated as primary key string
1189
-     *
1190
-     * @param mixed $id int or string, depending on the type of the model's primary key
1191
-     * @return EE_Base_Class
1192
-     */
1193
-    public function get_one_by_ID($id)
1194
-    {
1195
-        if ($this->get_from_entity_map($id)) {
1196
-            return $this->get_from_entity_map($id);
1197
-        }
1198
-        return $this->get_one(
1199
-            $this->alter_query_params_to_restrict_by_ID(
1200
-                $id,
1201
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1202
-            )
1203
-        );
1204
-    }
1205
-
1206
-
1207
-
1208
-    /**
1209
-     * Alters query parameters to only get items with this ID are returned.
1210
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1211
-     * or could just be a simple primary key ID
1212
-     *
1213
-     * @param int   $id
1214
-     * @param array $query_params
1215
-     * @return array of normal query params, @see EEM_Base::get_all
1216
-     * @throws EE_Error
1217
-     */
1218
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219
-    {
1220
-        if (! isset($query_params[0])) {
1221
-            $query_params[0] = array();
1222
-        }
1223
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1224
-        if ($conditions_from_id === null) {
1225
-            $query_params[0][$this->primary_key_name()] = $id;
1226
-        } else {
1227
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1228
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
-        }
1230
-        return $query_params;
1231
-    }
1232
-
1233
-
1234
-
1235
-    /**
1236
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1237
-     * array. If no item is found, null is returned.
1238
-     *
1239
-     * @param array $query_params like EEM_Base's $query_params variable.
1240
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1241
-     * @throws EE_Error
1242
-     */
1243
-    public function get_one($query_params = array())
1244
-    {
1245
-        if (! is_array($query_params)) {
1246
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1247
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248
-                    gettype($query_params)), '4.6.0');
1249
-            $query_params = array();
1250
-        }
1251
-        $query_params['limit'] = 1;
1252
-        $items = $this->get_all($query_params);
1253
-        if (empty($items)) {
1254
-            return null;
1255
-        }
1256
-        return array_shift($items);
1257
-    }
1258
-
1259
-
1260
-
1261
-    /**
1262
-     * Returns the next x number of items in sequence from the given value as
1263
-     * found in the database matching the given query conditions.
1264
-     *
1265
-     * @param mixed $current_field_value    Value used for the reference point.
1266
-     * @param null  $field_to_order_by      What field is used for the
1267
-     *                                      reference point.
1268
-     * @param int   $limit                  How many to return.
1269
-     * @param array $query_params           Extra conditions on the query.
1270
-     * @param null  $columns_to_select      If left null, then an array of
1271
-     *                                      EE_Base_Class objects is returned,
1272
-     *                                      otherwise you can indicate just the
1273
-     *                                      columns you want returned.
1274
-     * @return EE_Base_Class[]|array
1275
-     * @throws EE_Error
1276
-     */
1277
-    public function next_x(
1278
-        $current_field_value,
1279
-        $field_to_order_by = null,
1280
-        $limit = 1,
1281
-        $query_params = array(),
1282
-        $columns_to_select = null
1283
-    ) {
1284
-        return $this->_get_consecutive(
1285
-            $current_field_value,
1286
-            '>',
1287
-            $field_to_order_by,
1288
-            $limit,
1289
-            $query_params,
1290
-            $columns_to_select
1291
-        );
1292
-    }
1293
-
1294
-
1295
-
1296
-    /**
1297
-     * Returns the previous x number of items in sequence from the given value
1298
-     * as found in the database matching the given query conditions.
1299
-     *
1300
-     * @param mixed $current_field_value    Value used for the reference point.
1301
-     * @param null  $field_to_order_by      What field is used for the
1302
-     *                                      reference point.
1303
-     * @param int   $limit                  How many to return.
1304
-     * @param array $query_params           Extra conditions on the query.
1305
-     * @param null  $columns_to_select      If left null, then an array of
1306
-     *                                      EE_Base_Class objects is returned,
1307
-     *                                      otherwise you can indicate just the
1308
-     *                                      columns you want returned.
1309
-     * @return EE_Base_Class[]|array
1310
-     * @throws EE_Error
1311
-     */
1312
-    public function previous_x(
1313
-        $current_field_value,
1314
-        $field_to_order_by = null,
1315
-        $limit = 1,
1316
-        $query_params = array(),
1317
-        $columns_to_select = null
1318
-    ) {
1319
-        return $this->_get_consecutive(
1320
-            $current_field_value,
1321
-            '<',
1322
-            $field_to_order_by,
1323
-            $limit,
1324
-            $query_params,
1325
-            $columns_to_select
1326
-        );
1327
-    }
1328
-
1329
-
1330
-
1331
-    /**
1332
-     * Returns the next item in sequence from the given value as found in the
1333
-     * database matching the given query conditions.
1334
-     *
1335
-     * @param mixed $current_field_value    Value used for the reference point.
1336
-     * @param null  $field_to_order_by      What field is used for the
1337
-     *                                      reference point.
1338
-     * @param array $query_params           Extra conditions on the query.
1339
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1340
-     *                                      object is returned, otherwise you
1341
-     *                                      can indicate just the columns you
1342
-     *                                      want and a single array indexed by
1343
-     *                                      the columns will be returned.
1344
-     * @return EE_Base_Class|null|array()
1345
-     * @throws EE_Error
1346
-     */
1347
-    public function next(
1348
-        $current_field_value,
1349
-        $field_to_order_by = null,
1350
-        $query_params = array(),
1351
-        $columns_to_select = null
1352
-    ) {
1353
-        $results = $this->_get_consecutive(
1354
-            $current_field_value,
1355
-            '>',
1356
-            $field_to_order_by,
1357
-            1,
1358
-            $query_params,
1359
-            $columns_to_select
1360
-        );
1361
-        return empty($results) ? null : reset($results);
1362
-    }
1363
-
1364
-
1365
-
1366
-    /**
1367
-     * Returns the previous item in sequence from the given value as found in
1368
-     * the database matching the given query conditions.
1369
-     *
1370
-     * @param mixed $current_field_value    Value used for the reference point.
1371
-     * @param null  $field_to_order_by      What field is used for the
1372
-     *                                      reference point.
1373
-     * @param array $query_params           Extra conditions on the query.
1374
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1375
-     *                                      object is returned, otherwise you
1376
-     *                                      can indicate just the columns you
1377
-     *                                      want and a single array indexed by
1378
-     *                                      the columns will be returned.
1379
-     * @return EE_Base_Class|null|array()
1380
-     * @throws EE_Error
1381
-     */
1382
-    public function previous(
1383
-        $current_field_value,
1384
-        $field_to_order_by = null,
1385
-        $query_params = array(),
1386
-        $columns_to_select = null
1387
-    ) {
1388
-        $results = $this->_get_consecutive(
1389
-            $current_field_value,
1390
-            '<',
1391
-            $field_to_order_by,
1392
-            1,
1393
-            $query_params,
1394
-            $columns_to_select
1395
-        );
1396
-        return empty($results) ? null : reset($results);
1397
-    }
1398
-
1399
-
1400
-
1401
-    /**
1402
-     * Returns the a consecutive number of items in sequence from the given
1403
-     * value as found in the database matching the given query conditions.
1404
-     *
1405
-     * @param mixed  $current_field_value   Value used for the reference point.
1406
-     * @param string $operand               What operand is used for the sequence.
1407
-     * @param string $field_to_order_by     What field is used for the reference point.
1408
-     * @param int    $limit                 How many to return.
1409
-     * @param array  $query_params          Extra conditions on the query.
1410
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1411
-     *                                      otherwise you can indicate just the columns you want returned.
1412
-     * @return EE_Base_Class[]|array
1413
-     * @throws EE_Error
1414
-     */
1415
-    protected function _get_consecutive(
1416
-        $current_field_value,
1417
-        $operand = '>',
1418
-        $field_to_order_by = null,
1419
-        $limit = 1,
1420
-        $query_params = array(),
1421
-        $columns_to_select = null
1422
-    ) {
1423
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1424
-        if (empty($field_to_order_by)) {
1425
-            if ($this->has_primary_key_field()) {
1426
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1427
-            } else {
1428
-                if (WP_DEBUG) {
1429
-                    throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1430
-                        'event_espresso'));
1431
-                }
1432
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1433
-                return array();
1434
-            }
1435
-        }
1436
-        if (! is_array($query_params)) {
1437
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439
-                    gettype($query_params)), '4.6.0');
1440
-            $query_params = array();
1441
-        }
1442
-        //let's add the where query param for consecutive look up.
1443
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444
-        $query_params['limit'] = $limit;
1445
-        //set direction
1446
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1447
-        $query_params['order_by'] = $operand === '>'
1448
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1449
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1450
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
-        if (empty($columns_to_select)) {
1452
-            return $this->get_all($query_params);
1453
-        }
1454
-        //getting just the fields
1455
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
-    }
1457
-
1458
-
1459
-
1460
-    /**
1461
-     * This sets the _timezone property after model object has been instantiated.
1462
-     *
1463
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1464
-     */
1465
-    public function set_timezone($timezone)
1466
-    {
1467
-        if ($timezone !== null) {
1468
-            $this->_timezone = $timezone;
1469
-        }
1470
-        //note we need to loop through relations and set the timezone on those objects as well.
1471
-        foreach ($this->_model_relations as $relation) {
1472
-            $relation->set_timezone($timezone);
1473
-        }
1474
-        //and finally we do the same for any datetime fields
1475
-        foreach ($this->_fields as $field) {
1476
-            if ($field instanceof EE_Datetime_Field) {
1477
-                $field->set_timezone($timezone);
1478
-            }
1479
-        }
1480
-    }
1481
-
1482
-
1483
-
1484
-    /**
1485
-     * This just returns whatever is set for the current timezone.
1486
-     *
1487
-     * @access public
1488
-     * @return string
1489
-     */
1490
-    public function get_timezone()
1491
-    {
1492
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1493
-        if (empty($this->_timezone)) {
1494
-            foreach ($this->_fields as $field) {
1495
-                if ($field instanceof EE_Datetime_Field) {
1496
-                    $this->set_timezone($field->get_timezone());
1497
-                    break;
1498
-                }
1499
-            }
1500
-        }
1501
-        //if timezone STILL empty then return the default timezone for the site.
1502
-        if (empty($this->_timezone)) {
1503
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1504
-        }
1505
-        return $this->_timezone;
1506
-    }
1507
-
1508
-
1509
-
1510
-    /**
1511
-     * This returns the date formats set for the given field name and also ensures that
1512
-     * $this->_timezone property is set correctly.
1513
-     *
1514
-     * @since 4.6.x
1515
-     * @param string $field_name The name of the field the formats are being retrieved for.
1516
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1517
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1518
-     * @return array formats in an array with the date format first, and the time format last.
1519
-     */
1520
-    public function get_formats_for($field_name, $pretty = false)
1521
-    {
1522
-        $field_settings = $this->field_settings_for($field_name);
1523
-        //if not a valid EE_Datetime_Field then throw error
1524
-        if (! $field_settings instanceof EE_Datetime_Field) {
1525
-            throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1526
-                'event_espresso'), $field_name));
1527
-        }
1528
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1529
-        //the field.
1530
-        $this->_timezone = $field_settings->get_timezone();
1531
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1532
-    }
1533
-
1534
-
1535
-
1536
-    /**
1537
-     * This returns the current time in a format setup for a query on this model.
1538
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
-     * it will return:
1540
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
-     *  NOW
1542
-     *  - or a unix timestamp (equivalent to time())
1543
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
-     * @since 4.6.x
1547
-     * @param string $field_name       The field the current time is needed for.
1548
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
-     *                                 formatted string matching the set format for the field in the set timezone will
1550
-     *                                 be returned.
1551
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1553
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1554
-     *                                 exception is triggered.
1555
-     */
1556
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1557
-    {
1558
-        $formats = $this->get_formats_for($field_name);
1559
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1560
-        if ($timestamp) {
1561
-            return $DateTime->format('U');
1562
-        }
1563
-        //not returning timestamp, so return formatted string in timezone.
1564
-        switch ($what) {
1565
-            case 'time' :
1566
-                return $DateTime->format($formats[1]);
1567
-                break;
1568
-            case 'date' :
1569
-                return $DateTime->format($formats[0]);
1570
-                break;
1571
-            default :
1572
-                return $DateTime->format(implode(' ', $formats));
1573
-                break;
1574
-        }
1575
-    }
1576
-
1577
-
1578
-
1579
-    /**
1580
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
-     * for the model are.  Returns a DateTime object.
1582
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
-     * ignored.
1585
-     *
1586
-     * @param string $field_name      The field being setup.
1587
-     * @param string $timestring      The date time string being used.
1588
-     * @param string $incoming_format The format for the time string.
1589
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
-     *                                format is
1592
-     *                                'U', this is ignored.
1593
-     * @return DateTime
1594
-     * @throws EE_Error
1595
-     */
1596
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
-    {
1598
-        //just using this to ensure the timezone is set correctly internally
1599
-        $this->get_formats_for($field_name);
1600
-        //load EEH_DTT_Helper
1601
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
-        $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1604
-        // workaround for php datetime bug
1605
-        // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
1606
-        $incomingDateTime->getTimestamp();
1607
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1608
-    }
1609
-
1610
-
1611
-
1612
-    /**
1613
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1614
-     *
1615
-     * @return EE_Table_Base[]
1616
-     */
1617
-    public function get_tables()
1618
-    {
1619
-        return $this->_tables;
1620
-    }
1621
-
1622
-
1623
-
1624
-    /**
1625
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1626
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1627
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1628
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1629
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1630
-     * model object with EVT_ID = 1
1631
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1632
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1633
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1634
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1635
-     * are not specified)
1636
-     *
1637
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1638
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1639
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1640
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1641
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1642
-     *                                         ID=34, we'd use this method as follows:
1643
-     *                                         EEM_Transaction::instance()->update(
1644
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1645
-     *                                         array(array('TXN_ID'=>34)));
1646
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1647
-     *                                         in client code into what's expected to be stored on each field. Eg,
1648
-     *                                         consider updating Question's QST_admin_label field is of type
1649
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1650
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1651
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1652
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1653
-     *                                         TRUE, it is assumed that you've already called
1654
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1655
-     *                                         malicious javascript. However, if
1656
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1657
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1658
-     *                                         and every other field, before insertion. We provide this parameter
1659
-     *                                         because model objects perform their prepare_for_set function on all
1660
-     *                                         their values, and so don't need to be called again (and in many cases,
1661
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1662
-     *                                         prepare_for_set method...)
1663
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1664
-     *                                         in this model's entity map according to $fields_n_values that match
1665
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1666
-     *                                         by setting this to FALSE, but be aware that model objects being used
1667
-     *                                         could get out-of-sync with the database
1668
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1669
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1670
-     *                                         bad)
1671
-     * @throws EE_Error
1672
-     */
1673
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1674
-    {
1675
-        if (! is_array($query_params)) {
1676
-            EE_Error::doing_it_wrong('EEM_Base::update',
1677
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1678
-                    gettype($query_params)), '4.6.0');
1679
-            $query_params = array();
1680
-        }
1681
-        /**
1682
-         * Action called before a model update call has been made.
1683
-         *
1684
-         * @param EEM_Base $model
1685
-         * @param array    $fields_n_values the updated fields and their new values
1686
-         * @param array    $query_params    @see EEM_Base::get_all()
1687
-         */
1688
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1689
-        /**
1690
-         * Filters the fields about to be updated given the query parameters. You can provide the
1691
-         * $query_params to $this->get_all() to find exactly which records will be updated
1692
-         *
1693
-         * @param array    $fields_n_values fields and their new values
1694
-         * @param EEM_Base $model           the model being queried
1695
-         * @param array    $query_params    see EEM_Base::get_all()
1696
-         */
1697
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1698
-            $query_params);
1699
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1700
-        //to do that, for each table, verify that it's PK isn't null.
1701
-        $tables = $this->get_tables();
1702
-        //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
1703
-        //NOTE: we should make this code more efficient by NOT querying twice
1704
-        //before the real update, but that needs to first go through ALPHA testing
1705
-        //as it's dangerous. says Mike August 8 2014
1706
-        //we want to make sure the default_where strategy is ignored
1707
-        $this->_ignore_where_strategy = true;
1708
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1709
-        foreach ($wpdb_select_results as $wpdb_result) {
1710
-            // type cast stdClass as array
1711
-            $wpdb_result = (array)$wpdb_result;
1712
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1713
-            if ($this->has_primary_key_field()) {
1714
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1715
-            } else {
1716
-                //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)
1717
-                $main_table_pk_value = null;
1718
-            }
1719
-            //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
1720
-            //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
1721
-            if (count($tables) > 1) {
1722
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1723
-                //in that table, and so we'll want to insert one
1724
-                foreach ($tables as $table_obj) {
1725
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1726
-                    //if there is no private key for this table on the results, it means there's no entry
1727
-                    //in this table, right? so insert a row in the current table, using any fields available
1728
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1729
-                           && $wpdb_result[$this_table_pk_column])
1730
-                    ) {
1731
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1732
-                            $main_table_pk_value);
1733
-                        //if we died here, report the error
1734
-                        if (! $success) {
1735
-                            return false;
1736
-                        }
1737
-                    }
1738
-                }
1739
-            }
1740
-            //				//and now check that if we have cached any models by that ID on the model, that
1741
-            //				//they also get updated properly
1742
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1743
-            //				if( $model_object ){
1744
-            //					foreach( $fields_n_values as $field => $value ){
1745
-            //						$model_object->set($field, $value);
1746
-            //let's make sure default_where strategy is followed now
1747
-            $this->_ignore_where_strategy = false;
1748
-        }
1749
-        //if we want to keep model objects in sync, AND
1750
-        //if this wasn't called from a model object (to update itself)
1751
-        //then we want to make sure we keep all the existing
1752
-        //model objects in sync with the db
1753
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1754
-            if ($this->has_primary_key_field()) {
1755
-                $model_objs_affected_ids = $this->get_col($query_params);
1756
-            } else {
1757
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1758
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1759
-                $model_objs_affected_ids = array();
1760
-                foreach ($models_affected_key_columns as $row) {
1761
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1762
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1763
-                }
1764
-            }
1765
-            if (! $model_objs_affected_ids) {
1766
-                //wait wait wait- if nothing was affected let's stop here
1767
-                return 0;
1768
-            }
1769
-            foreach ($model_objs_affected_ids as $id) {
1770
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1771
-                if ($model_obj_in_entity_map) {
1772
-                    foreach ($fields_n_values as $field => $new_value) {
1773
-                        $model_obj_in_entity_map->set($field, $new_value);
1774
-                    }
1775
-                }
1776
-            }
1777
-            //if there is a primary key on this model, we can now do a slight optimization
1778
-            if ($this->has_primary_key_field()) {
1779
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1780
-                $query_params = array(
1781
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1782
-                    'limit'                    => count($model_objs_affected_ids),
1783
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1784
-                );
1785
-            }
1786
-        }
1787
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1788
-        $SQL = "UPDATE "
1789
-               . $model_query_info->get_full_join_sql()
1790
-               . " SET "
1791
-               . $this->_construct_update_sql($fields_n_values)
1792
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1793
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1794
-        /**
1795
-         * Action called after a model update call has been made.
1796
-         *
1797
-         * @param EEM_Base $model
1798
-         * @param array    $fields_n_values the updated fields and their new values
1799
-         * @param array    $query_params    @see EEM_Base::get_all()
1800
-         * @param int      $rows_affected
1801
-         */
1802
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1803
-        return $rows_affected;//how many supposedly got updated
1804
-    }
1805
-
1806
-
1807
-
1808
-    /**
1809
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1810
-     * are teh values of the field specified (or by default the primary key field)
1811
-     * that matched the query params. Note that you should pass the name of the
1812
-     * model FIELD, not the database table's column name.
1813
-     *
1814
-     * @param array  $query_params @see EEM_Base::get_all()
1815
-     * @param string $field_to_select
1816
-     * @return array just like $wpdb->get_col()
1817
-     * @throws EE_Error
1818
-     */
1819
-    public function get_col($query_params = array(), $field_to_select = null)
1820
-    {
1821
-        if ($field_to_select) {
1822
-            $field = $this->field_settings_for($field_to_select);
1823
-        } elseif ($this->has_primary_key_field()) {
1824
-            $field = $this->get_primary_key_field();
1825
-        } else {
1826
-            //no primary key, just grab the first column
1827
-            $field = reset($this->field_settings());
1828
-        }
1829
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1830
-        $select_expressions = $field->get_qualified_column();
1831
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1832
-        return $this->_do_wpdb_query('get_col', array($SQL));
1833
-    }
1834
-
1835
-
1836
-
1837
-    /**
1838
-     * Returns a single column value for a single row from the database
1839
-     *
1840
-     * @param array  $query_params    @see EEM_Base::get_all()
1841
-     * @param string $field_to_select @see EEM_Base::get_col()
1842
-     * @return string
1843
-     * @throws EE_Error
1844
-     */
1845
-    public function get_var($query_params = array(), $field_to_select = null)
1846
-    {
1847
-        $query_params['limit'] = 1;
1848
-        $col = $this->get_col($query_params, $field_to_select);
1849
-        if (! empty($col)) {
1850
-            return reset($col);
1851
-        }
1852
-        return null;
1853
-    }
1854
-
1855
-
1856
-
1857
-    /**
1858
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1859
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1860
-     * injection, but currently no further filtering is done
1861
-     *
1862
-     * @global      $wpdb
1863
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1864
-     *                               be updated to in the DB
1865
-     * @return string of SQL
1866
-     * @throws EE_Error
1867
-     */
1868
-    public function _construct_update_sql($fields_n_values)
1869
-    {
1870
-        /** @type WPDB $wpdb */
1871
-        global $wpdb;
1872
-        $cols_n_values = array();
1873
-        foreach ($fields_n_values as $field_name => $value) {
1874
-            $field_obj = $this->field_settings_for($field_name);
1875
-            //if the value is NULL, we want to assign the value to that.
1876
-            //wpdb->prepare doesn't really handle that properly
1877
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1878
-            $value_sql = $prepared_value === null ? 'NULL'
1879
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1880
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1881
-        }
1882
-        return implode(",", $cols_n_values);
1883
-    }
1884
-
1885
-
1886
-
1887
-    /**
1888
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1889
-     * Performs a HARD delete, meaning the database row should always be removed,
1890
-     * not just have a flag field on it switched
1891
-     * Wrapper for EEM_Base::delete_permanently()
1892
-     *
1893
-     * @param mixed $id
1894
-     * @param boolean $allow_blocking
1895
-     * @return int the number of rows deleted
1896
-     * @throws EE_Error
1897
-     */
1898
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1899
-    {
1900
-        return $this->delete_permanently(
1901
-            array(
1902
-                array($this->get_primary_key_field()->get_name() => $id),
1903
-                'limit' => 1,
1904
-            ),
1905
-            $allow_blocking
1906
-        );
1907
-    }
1908
-
1909
-
1910
-
1911
-    /**
1912
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1913
-     * Wrapper for EEM_Base::delete()
1914
-     *
1915
-     * @param mixed $id
1916
-     * @param boolean $allow_blocking
1917
-     * @return int the number of rows deleted
1918
-     * @throws EE_Error
1919
-     */
1920
-    public function delete_by_ID($id, $allow_blocking = true)
1921
-    {
1922
-        return $this->delete(
1923
-            array(
1924
-                array($this->get_primary_key_field()->get_name() => $id),
1925
-                'limit' => 1,
1926
-            ),
1927
-            $allow_blocking
1928
-        );
1929
-    }
1930
-
1931
-
1932
-
1933
-    /**
1934
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1935
-     * meaning if the model has a field that indicates its been "trashed" or
1936
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1937
-     *
1938
-     * @see EEM_Base::delete_permanently
1939
-     * @param array   $query_params
1940
-     * @param boolean $allow_blocking
1941
-     * @return int how many rows got deleted
1942
-     * @throws EE_Error
1943
-     */
1944
-    public function delete($query_params, $allow_blocking = true)
1945
-    {
1946
-        return $this->delete_permanently($query_params, $allow_blocking);
1947
-    }
1948
-
1949
-
1950
-
1951
-    /**
1952
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1953
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1954
-     * as archived, not actually deleted
1955
-     *
1956
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1957
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1958
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1959
-     *                                deletes regardless of other objects which may depend on it. Its generally
1960
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1961
-     *                                DB
1962
-     * @return int how many rows got deleted
1963
-     * @throws EE_Error
1964
-     */
1965
-    public function delete_permanently($query_params, $allow_blocking = true)
1966
-    {
1967
-        /**
1968
-         * Action called just before performing a real deletion query. You can use the
1969
-         * model and its $query_params to find exactly which items will be deleted
1970
-         *
1971
-         * @param EEM_Base $model
1972
-         * @param array    $query_params   @see EEM_Base::get_all()
1973
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1974
-         *                                 to block (prevent) this deletion
1975
-         */
1976
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1977
-        //some MySQL databases may be running safe mode, which may restrict
1978
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1979
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1980
-        //to delete them
1981
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1982
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1983
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1984
-            $columns_and_ids_for_deleting
1985
-        );
1986
-        /**
1987
-         * Allows client code to act on the items being deleted before the query is actually executed.
1988
-         *
1989
-         * @param EEM_Base $this  The model instance being acted on.
1990
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1991
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1992
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1993
-         *                                                  derived from the incoming query parameters.
1994
-         *                                                  @see details on the structure of this array in the phpdocs
1995
-         *                                                  for the `_get_ids_for_delete_method`
1996
-         *
1997
-         */
1998
-        do_action('AHEE__EEM_Base__delete__before_query',
1999
-            $this,
2000
-            $query_params,
2001
-            $allow_blocking,
2002
-            $columns_and_ids_for_deleting
2003
-        );
2004
-        if ($deletion_where_query_part) {
2005
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2006
-            $table_aliases = array_keys($this->_tables);
2007
-            $SQL = "DELETE "
2008
-                   . implode(", ", $table_aliases)
2009
-                   . " FROM "
2010
-                   . $model_query_info->get_full_join_sql()
2011
-                   . " WHERE "
2012
-                   . $deletion_where_query_part;
2013
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2014
-        } else {
2015
-            $rows_deleted = 0;
2016
-        }
2017
-
2018
-        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2019
-        //there was no error with the delete query.
2020
-        if ($this->has_primary_key_field()
2021
-            && $rows_deleted !== false
2022
-            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2023
-        ) {
2024
-            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2025
-            foreach ($ids_for_removal as $id) {
2026
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2027
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2028
-                }
2029
-            }
2030
-
2031
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2032
-            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2033
-            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2034
-            // (although it is possible).
2035
-            //Note this can be skipped by using the provided filter and returning false.
2036
-            if (apply_filters(
2037
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2038
-                ! $this instanceof EEM_Extra_Meta,
2039
-                $this
2040
-            )) {
2041
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2042
-                    0 => array(
2043
-                        'EXM_type' => $this->get_this_model_name(),
2044
-                        'OBJ_ID'   => array(
2045
-                            'IN',
2046
-                            $ids_for_removal
2047
-                        )
2048
-                    )
2049
-                ));
2050
-            }
2051
-        }
2052
-
2053
-        /**
2054
-         * Action called just after performing a real deletion query. Although at this point the
2055
-         * items should have been deleted
2056
-         *
2057
-         * @param EEM_Base $model
2058
-         * @param array    $query_params @see EEM_Base::get_all()
2059
-         * @param int      $rows_deleted
2060
-         */
2061
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2062
-        return $rows_deleted;//how many supposedly got deleted
2063
-    }
2064
-
2065
-
2066
-
2067
-    /**
2068
-     * Checks all the relations that throw error messages when there are blocking related objects
2069
-     * for related model objects. If there are any related model objects on those relations,
2070
-     * adds an EE_Error, and return true
2071
-     *
2072
-     * @param EE_Base_Class|int $this_model_obj_or_id
2073
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2074
-     *                                                 should be ignored when determining whether there are related
2075
-     *                                                 model objects which block this model object's deletion. Useful
2076
-     *                                                 if you know A is related to B and are considering deleting A,
2077
-     *                                                 but want to see if A has any other objects blocking its deletion
2078
-     *                                                 before removing the relation between A and B
2079
-     * @return boolean
2080
-     * @throws EE_Error
2081
-     */
2082
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2083
-    {
2084
-        //first, if $ignore_this_model_obj was supplied, get its model
2085
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2086
-            $ignored_model = $ignore_this_model_obj->get_model();
2087
-        } else {
2088
-            $ignored_model = null;
2089
-        }
2090
-        //now check all the relations of $this_model_obj_or_id and see if there
2091
-        //are any related model objects blocking it?
2092
-        $is_blocked = false;
2093
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2094
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2095
-                //if $ignore_this_model_obj was supplied, then for the query
2096
-                //on that model needs to be told to ignore $ignore_this_model_obj
2097
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2098
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2099
-                        array(
2100
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2101
-                                '!=',
2102
-                                $ignore_this_model_obj->ID(),
2103
-                            ),
2104
-                        ),
2105
-                    ));
2106
-                } else {
2107
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2108
-                }
2109
-                if ($related_model_objects) {
2110
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2111
-                    $is_blocked = true;
2112
-                }
2113
-            }
2114
-        }
2115
-        return $is_blocked;
2116
-    }
2117
-
2118
-
2119
-    /**
2120
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2121
-     * @param array $row_results_for_deleting
2122
-     * @param bool  $allow_blocking
2123
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2124
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2125
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2126
-     *                 deleted. Example:
2127
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2128
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2129
-     *                 where each element is a group of columns and values that get deleted. Example:
2130
-     *                      array(
2131
-     *                          0 => array(
2132
-     *                              'Term_Relationship.object_id' => 1
2133
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2134
-     *                          ),
2135
-     *                          1 => array(
2136
-     *                              'Term_Relationship.object_id' => 1
2137
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2138
-     *                          )
2139
-     *                      )
2140
-     * @throws EE_Error
2141
-     */
2142
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2143
-    {
2144
-        $ids_to_delete_indexed_by_column = array();
2145
-        if ($this->has_primary_key_field()) {
2146
-            $primary_table = $this->_get_main_table();
2147
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2148
-            $other_tables = $this->_get_other_tables();
2149
-            $ids_to_delete_indexed_by_column = $query = array();
2150
-            foreach ($row_results_for_deleting as $item_to_delete) {
2151
-                //before we mark this item for deletion,
2152
-                //make sure there's no related entities blocking its deletion (if we're checking)
2153
-                if (
2154
-                    $allow_blocking
2155
-                    && $this->delete_is_blocked_by_related_models(
2156
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2157
-                    )
2158
-                ) {
2159
-                    continue;
2160
-                }
2161
-                //primary table deletes
2162
-                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2163
-                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2164
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2165
-                }
2166
-            }
2167
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2168
-            $fields = $this->get_combined_primary_key_fields();
2169
-            foreach ($row_results_for_deleting as $item_to_delete) {
2170
-                $ids_to_delete_indexed_by_column_for_row = array();
2171
-                foreach ($fields as $cpk_field) {
2172
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2173
-                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2174
-                            $item_to_delete[$cpk_field->get_qualified_column()];
2175
-                    }
2176
-                }
2177
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2178
-            }
2179
-        } else {
2180
-            //so there's no primary key and no combined key...
2181
-            //sorry, can't help you
2182
-            throw new EE_Error(
2183
-                sprintf(
2184
-                    __(
2185
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2186
-                        "event_espresso"
2187
-                    ), get_class($this)
2188
-                )
2189
-            );
2190
-        }
2191
-        return $ids_to_delete_indexed_by_column;
2192
-    }
2193
-
2194
-
2195
-    /**
2196
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2197
-     * the corresponding query_part for the query performing the delete.
2198
-     *
2199
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2200
-     * @return string
2201
-     * @throws EE_Error
2202
-     */
2203
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2204
-        $query_part = '';
2205
-        if (empty($ids_to_delete_indexed_by_column)) {
2206
-            return $query_part;
2207
-        } elseif ($this->has_primary_key_field()) {
2208
-            $query = array();
2209
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2210
-                //make sure we have unique $ids
2211
-                $ids = array_unique($ids);
2212
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2213
-            }
2214
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2215
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2216
-            $ways_to_identify_a_row = array();
2217
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2218
-                $values_for_each_combined_primary_key_for_a_row = array();
2219
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2220
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2221
-                }
2222
-                $ways_to_identify_a_row[] = '('
2223
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2224
-                                            . ')';
2225
-            }
2226
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2227
-        }
2228
-        return $query_part;
2229
-    }
2230
-
2231
-
2232
-
2233
-    /**
2234
-     * Gets the model field by the fully qualified name
2235
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2236
-     * @return EE_Model_Field_Base
2237
-     */
2238
-    public function get_field_by_column($qualified_column_name)
2239
-    {
2240
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2241
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2242
-               return $field_obj;
2243
-           }
2244
-       }
2245
-        throw new EE_Error(
2246
-            sprintf(
2247
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2248
-                $this->get_this_model_name(),
2249
-                $qualified_column_name
2250
-            )
2251
-        );
2252
-    }
2253
-
2254
-
2255
-
2256
-    /**
2257
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2258
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2259
-     * column
2260
-     *
2261
-     * @param array  $query_params   like EEM_Base::get_all's
2262
-     * @param string $field_to_count field on model to count by (not column name)
2263
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2264
-     *                               that by the setting $distinct to TRUE;
2265
-     * @return int
2266
-     * @throws EE_Error
2267
-     */
2268
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2269
-    {
2270
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2271
-        if ($field_to_count) {
2272
-            $field_obj = $this->field_settings_for($field_to_count);
2273
-            $column_to_count = $field_obj->get_qualified_column();
2274
-        } elseif ($this->has_primary_key_field()) {
2275
-            $pk_field_obj = $this->get_primary_key_field();
2276
-            $column_to_count = $pk_field_obj->get_qualified_column();
2277
-        } else {
2278
-            //there's no primary key
2279
-            //if we're counting distinct items, and there's no primary key,
2280
-            //we need to list out the columns for distinction;
2281
-            //otherwise we can just use star
2282
-            if ($distinct) {
2283
-                $columns_to_use = array();
2284
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2285
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2286
-                }
2287
-                $column_to_count = implode(',', $columns_to_use);
2288
-            } else {
2289
-                $column_to_count = '*';
2290
-            }
2291
-        }
2292
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2293
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2294
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2295
-    }
2296
-
2297
-
2298
-
2299
-    /**
2300
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2301
-     *
2302
-     * @param array  $query_params like EEM_Base::get_all
2303
-     * @param string $field_to_sum name of field (array key in $_fields array)
2304
-     * @return float
2305
-     * @throws EE_Error
2306
-     */
2307
-    public function sum($query_params, $field_to_sum = null)
2308
-    {
2309
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2310
-        if ($field_to_sum) {
2311
-            $field_obj = $this->field_settings_for($field_to_sum);
2312
-        } else {
2313
-            $field_obj = $this->get_primary_key_field();
2314
-        }
2315
-        $column_to_count = $field_obj->get_qualified_column();
2316
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2317
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2318
-        $data_type = $field_obj->get_wpdb_data_type();
2319
-        if ($data_type === '%d' || $data_type === '%s') {
2320
-            return (float)$return_value;
2321
-        }
2322
-        //must be %f
2323
-        return (float)$return_value;
2324
-    }
2325
-
2326
-
2327
-
2328
-    /**
2329
-     * Just calls the specified method on $wpdb with the given arguments
2330
-     * Consolidates a little extra error handling code
2331
-     *
2332
-     * @param string $wpdb_method
2333
-     * @param array  $arguments_to_provide
2334
-     * @throws EE_Error
2335
-     * @global wpdb  $wpdb
2336
-     * @return mixed
2337
-     */
2338
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2339
-    {
2340
-        //if we're in maintenance mode level 2, DON'T run any queries
2341
-        //because level 2 indicates the database needs updating and
2342
-        //is probably out of sync with the code
2343
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2344
-            throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2345
-                "event_espresso")));
2346
-        }
2347
-        /** @type WPDB $wpdb */
2348
-        global $wpdb;
2349
-        if (! method_exists($wpdb, $wpdb_method)) {
2350
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2351
-                'event_espresso'), $wpdb_method));
2352
-        }
2353
-        if (WP_DEBUG) {
2354
-            $old_show_errors_value = $wpdb->show_errors;
2355
-            $wpdb->show_errors(false);
2356
-        }
2357
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2358
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2359
-        if (WP_DEBUG) {
2360
-            $wpdb->show_errors($old_show_errors_value);
2361
-            if (! empty($wpdb->last_error)) {
2362
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2363
-            }
2364
-            if ($result === false) {
2365
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2366
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2367
-            }
2368
-        } elseif ($result === false) {
2369
-            EE_Error::add_error(
2370
-                sprintf(
2371
-                    __('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"',
2372
-                        'event_espresso'),
2373
-                    $wpdb_method,
2374
-                    var_export($arguments_to_provide, true),
2375
-                    $wpdb->last_error
2376
-                ),
2377
-                __FILE__,
2378
-                __FUNCTION__,
2379
-                __LINE__
2380
-            );
2381
-        }
2382
-        return $result;
2383
-    }
2384
-
2385
-
2386
-
2387
-    /**
2388
-     * Attempts to run the indicated WPDB method with the provided arguments,
2389
-     * and if there's an error tries to verify the DB is correct. Uses
2390
-     * the static property EEM_Base::$_db_verification_level to determine whether
2391
-     * we should try to fix the EE core db, the addons, or just give up
2392
-     *
2393
-     * @param string $wpdb_method
2394
-     * @param array  $arguments_to_provide
2395
-     * @return mixed
2396
-     */
2397
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2398
-    {
2399
-        /** @type WPDB $wpdb */
2400
-        global $wpdb;
2401
-        $wpdb->last_error = null;
2402
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2403
-        // was there an error running the query? but we don't care on new activations
2404
-        // (we're going to setup the DB anyway on new activations)
2405
-        if (($result === false || ! empty($wpdb->last_error))
2406
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2407
-        ) {
2408
-            switch (EEM_Base::$_db_verification_level) {
2409
-                case EEM_Base::db_verified_none :
2410
-                    // let's double-check core's DB
2411
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2412
-                    break;
2413
-                case EEM_Base::db_verified_core :
2414
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2415
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2416
-                    break;
2417
-                case EEM_Base::db_verified_addons :
2418
-                    // ummmm... you in trouble
2419
-                    return $result;
2420
-                    break;
2421
-            }
2422
-            if (! empty($error_message)) {
2423
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2424
-                trigger_error($error_message);
2425
-            }
2426
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2427
-        }
2428
-        return $result;
2429
-    }
2430
-
2431
-
2432
-
2433
-    /**
2434
-     * Verifies the EE core database is up-to-date and records that we've done it on
2435
-     * EEM_Base::$_db_verification_level
2436
-     *
2437
-     * @param string $wpdb_method
2438
-     * @param array  $arguments_to_provide
2439
-     * @return string
2440
-     */
2441
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2442
-    {
2443
-        /** @type WPDB $wpdb */
2444
-        global $wpdb;
2445
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2446
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2447
-        $error_message = sprintf(
2448
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2449
-                'event_espresso'),
2450
-            $wpdb->last_error,
2451
-            $wpdb_method,
2452
-            wp_json_encode($arguments_to_provide)
2453
-        );
2454
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2455
-        return $error_message;
2456
-    }
2457
-
2458
-
2459
-
2460
-    /**
2461
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2462
-     * EEM_Base::$_db_verification_level
2463
-     *
2464
-     * @param $wpdb_method
2465
-     * @param $arguments_to_provide
2466
-     * @return string
2467
-     */
2468
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2469
-    {
2470
-        /** @type WPDB $wpdb */
2471
-        global $wpdb;
2472
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2473
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2474
-        $error_message = sprintf(
2475
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2476
-                'event_espresso'),
2477
-            $wpdb->last_error,
2478
-            $wpdb_method,
2479
-            wp_json_encode($arguments_to_provide)
2480
-        );
2481
-        EE_System::instance()->initialize_addons();
2482
-        return $error_message;
2483
-    }
2484
-
2485
-
2486
-
2487
-    /**
2488
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2489
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2490
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2491
-     * ..."
2492
-     *
2493
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2494
-     * @return string
2495
-     */
2496
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2497
-    {
2498
-        return " FROM " . $model_query_info->get_full_join_sql() .
2499
-               $model_query_info->get_where_sql() .
2500
-               $model_query_info->get_group_by_sql() .
2501
-               $model_query_info->get_having_sql() .
2502
-               $model_query_info->get_order_by_sql() .
2503
-               $model_query_info->get_limit_sql();
2504
-    }
2505
-
2506
-
2507
-
2508
-    /**
2509
-     * Set to easily debug the next X queries ran from this model.
2510
-     *
2511
-     * @param int $count
2512
-     */
2513
-    public function show_next_x_db_queries($count = 1)
2514
-    {
2515
-        $this->_show_next_x_db_queries = $count;
2516
-    }
2517
-
2518
-
2519
-
2520
-    /**
2521
-     * @param $sql_query
2522
-     */
2523
-    public function show_db_query_if_previously_requested($sql_query)
2524
-    {
2525
-        if ($this->_show_next_x_db_queries > 0) {
2526
-            echo $sql_query;
2527
-            $this->_show_next_x_db_queries--;
2528
-        }
2529
-    }
2530
-
2531
-
2532
-
2533
-    /**
2534
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2535
-     * There are the 3 cases:
2536
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2537
-     * $otherModelObject has no ID, it is first saved.
2538
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2539
-     * has no ID, it is first saved.
2540
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2541
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2542
-     * join table
2543
-     *
2544
-     * @param        EE_Base_Class                     /int $thisModelObject
2545
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2546
-     * @param string $relationName                     , key in EEM_Base::_relations
2547
-     *                                                 an attendee to a group, you also want to specify which role they
2548
-     *                                                 will have in that group. So you would use this parameter to
2549
-     *                                                 specify array('role-column-name'=>'role-id')
2550
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2551
-     *                                                 to for relation to methods that allow you to further specify
2552
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2553
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2554
-     *                                                 because these will be inserted in any new rows created as well.
2555
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2556
-     * @throws EE_Error
2557
-     */
2558
-    public function add_relationship_to(
2559
-        $id_or_obj,
2560
-        $other_model_id_or_obj,
2561
-        $relationName,
2562
-        $extra_join_model_fields_n_values = array()
2563
-    ) {
2564
-        $relation_obj = $this->related_settings_for($relationName);
2565
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2566
-    }
2567
-
2568
-
2569
-
2570
-    /**
2571
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2572
-     * There are the 3 cases:
2573
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2574
-     * error
2575
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2576
-     * an error
2577
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2578
-     *
2579
-     * @param        EE_Base_Class /int $id_or_obj
2580
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2581
-     * @param string $relationName key in EEM_Base::_relations
2582
-     * @return boolean of success
2583
-     * @throws EE_Error
2584
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2585
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2586
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2587
-     *                             because these will be inserted in any new rows created as well.
2588
-     */
2589
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2590
-    {
2591
-        $relation_obj = $this->related_settings_for($relationName);
2592
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2593
-    }
2594
-
2595
-
2596
-
2597
-    /**
2598
-     * @param mixed           $id_or_obj
2599
-     * @param string          $relationName
2600
-     * @param array           $where_query_params
2601
-     * @param EE_Base_Class[] objects to which relations were removed
2602
-     * @return \EE_Base_Class[]
2603
-     * @throws EE_Error
2604
-     */
2605
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2606
-    {
2607
-        $relation_obj = $this->related_settings_for($relationName);
2608
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2609
-    }
2610
-
2611
-
2612
-
2613
-    /**
2614
-     * Gets all the related items of the specified $model_name, using $query_params.
2615
-     * Note: by default, we remove the "default query params"
2616
-     * because we want to get even deleted items etc.
2617
-     *
2618
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2619
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2620
-     * @param array  $query_params like EEM_Base::get_all
2621
-     * @return EE_Base_Class[]
2622
-     * @throws EE_Error
2623
-     */
2624
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2625
-    {
2626
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2627
-        $relation_settings = $this->related_settings_for($model_name);
2628
-        return $relation_settings->get_all_related($model_obj, $query_params);
2629
-    }
2630
-
2631
-
2632
-
2633
-    /**
2634
-     * Deletes all the model objects across the relation indicated by $model_name
2635
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2636
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2637
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2638
-     *
2639
-     * @param EE_Base_Class|int|string $id_or_obj
2640
-     * @param string                   $model_name
2641
-     * @param array                    $query_params
2642
-     * @return int how many deleted
2643
-     * @throws EE_Error
2644
-     */
2645
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2646
-    {
2647
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2648
-        $relation_settings = $this->related_settings_for($model_name);
2649
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2650
-    }
2651
-
2652
-
2653
-
2654
-    /**
2655
-     * Hard deletes all the model objects across the relation indicated by $model_name
2656
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2657
-     * the model objects can't be hard deleted because of blocking related model objects,
2658
-     * just does a soft-delete on them instead.
2659
-     *
2660
-     * @param EE_Base_Class|int|string $id_or_obj
2661
-     * @param string                   $model_name
2662
-     * @param array                    $query_params
2663
-     * @return int how many deleted
2664
-     * @throws EE_Error
2665
-     */
2666
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2667
-    {
2668
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2669
-        $relation_settings = $this->related_settings_for($model_name);
2670
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2671
-    }
2672
-
2673
-
2674
-
2675
-    /**
2676
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2677
-     * unless otherwise specified in the $query_params
2678
-     *
2679
-     * @param        int             /EE_Base_Class $id_or_obj
2680
-     * @param string $model_name     like 'Event', or 'Registration'
2681
-     * @param array  $query_params   like EEM_Base::get_all's
2682
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2683
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2684
-     *                               that by the setting $distinct to TRUE;
2685
-     * @return int
2686
-     * @throws EE_Error
2687
-     */
2688
-    public function count_related(
2689
-        $id_or_obj,
2690
-        $model_name,
2691
-        $query_params = array(),
2692
-        $field_to_count = null,
2693
-        $distinct = false
2694
-    ) {
2695
-        $related_model = $this->get_related_model_obj($model_name);
2696
-        //we're just going to use the query params on the related model's normal get_all query,
2697
-        //except add a condition to say to match the current mod
2698
-        if (! isset($query_params['default_where_conditions'])) {
2699
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2700
-        }
2701
-        $this_model_name = $this->get_this_model_name();
2702
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2703
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2704
-        return $related_model->count($query_params, $field_to_count, $distinct);
2705
-    }
2706
-
2707
-
2708
-
2709
-    /**
2710
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2711
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2712
-     *
2713
-     * @param        int           /EE_Base_Class $id_or_obj
2714
-     * @param string $model_name   like 'Event', or 'Registration'
2715
-     * @param array  $query_params like EEM_Base::get_all's
2716
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2717
-     * @return float
2718
-     * @throws EE_Error
2719
-     */
2720
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2721
-    {
2722
-        $related_model = $this->get_related_model_obj($model_name);
2723
-        if (! is_array($query_params)) {
2724
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2725
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2726
-                    gettype($query_params)), '4.6.0');
2727
-            $query_params = array();
2728
-        }
2729
-        //we're just going to use the query params on the related model's normal get_all query,
2730
-        //except add a condition to say to match the current mod
2731
-        if (! isset($query_params['default_where_conditions'])) {
2732
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2733
-        }
2734
-        $this_model_name = $this->get_this_model_name();
2735
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2736
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2737
-        return $related_model->sum($query_params, $field_to_sum);
2738
-    }
2739
-
2740
-
2741
-
2742
-    /**
2743
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2744
-     * $modelObject
2745
-     *
2746
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2747
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2748
-     * @param array               $query_params     like EEM_Base::get_all's
2749
-     * @return EE_Base_Class
2750
-     * @throws EE_Error
2751
-     */
2752
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2753
-    {
2754
-        $query_params['limit'] = 1;
2755
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2756
-        if ($results) {
2757
-            return array_shift($results);
2758
-        }
2759
-        return null;
2760
-    }
2761
-
2762
-
2763
-
2764
-    /**
2765
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2766
-     *
2767
-     * @return string
2768
-     */
2769
-    public function get_this_model_name()
2770
-    {
2771
-        return str_replace("EEM_", "", get_class($this));
2772
-    }
2773
-
2774
-
2775
-
2776
-    /**
2777
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2778
-     *
2779
-     * @return EE_Any_Foreign_Model_Name_Field
2780
-     * @throws EE_Error
2781
-     */
2782
-    public function get_field_containing_related_model_name()
2783
-    {
2784
-        foreach ($this->field_settings(true) as $field) {
2785
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2786
-                $field_with_model_name = $field;
2787
-            }
2788
-        }
2789
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2790
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2791
-                $this->get_this_model_name()));
2792
-        }
2793
-        return $field_with_model_name;
2794
-    }
2795
-
2796
-
2797
-
2798
-    /**
2799
-     * Inserts a new entry into the database, for each table.
2800
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2801
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2802
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2803
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2804
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2805
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2806
-     *
2807
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2808
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2809
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2810
-     *                              of EEM_Base)
2811
-     * @return int new primary key on main table that got inserted
2812
-     * @throws EE_Error
2813
-     */
2814
-    public function insert($field_n_values)
2815
-    {
2816
-        /**
2817
-         * Filters the fields and their values before inserting an item using the models
2818
-         *
2819
-         * @param array    $fields_n_values keys are the fields and values are their new values
2820
-         * @param EEM_Base $model           the model used
2821
-         */
2822
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2823
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2824
-            $main_table = $this->_get_main_table();
2825
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2826
-            if ($new_id !== false) {
2827
-                foreach ($this->_get_other_tables() as $other_table) {
2828
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2829
-                }
2830
-            }
2831
-            /**
2832
-             * Done just after attempting to insert a new model object
2833
-             *
2834
-             * @param EEM_Base   $model           used
2835
-             * @param array      $fields_n_values fields and their values
2836
-             * @param int|string the              ID of the newly-inserted model object
2837
-             */
2838
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2839
-            return $new_id;
2840
-        }
2841
-        return false;
2842
-    }
2843
-
2844
-
2845
-
2846
-    /**
2847
-     * Checks that the result would satisfy the unique indexes on this model
2848
-     *
2849
-     * @param array  $field_n_values
2850
-     * @param string $action
2851
-     * @return boolean
2852
-     * @throws EE_Error
2853
-     */
2854
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2855
-    {
2856
-        foreach ($this->unique_indexes() as $index_name => $index) {
2857
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2858
-            if ($this->exists(array($uniqueness_where_params))) {
2859
-                EE_Error::add_error(
2860
-                    sprintf(
2861
-                        __(
2862
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2863
-                            "event_espresso"
2864
-                        ),
2865
-                        $action,
2866
-                        $this->_get_class_name(),
2867
-                        $index_name,
2868
-                        implode(",", $index->field_names()),
2869
-                        http_build_query($uniqueness_where_params)
2870
-                    ),
2871
-                    __FILE__,
2872
-                    __FUNCTION__,
2873
-                    __LINE__
2874
-                );
2875
-                return false;
2876
-            }
2877
-        }
2878
-        return true;
2879
-    }
2880
-
2881
-
2882
-
2883
-    /**
2884
-     * Checks the database for an item that conflicts (ie, if this item were
2885
-     * saved to the DB would break some uniqueness requirement, like a primary key
2886
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2887
-     * can be either an EE_Base_Class or an array of fields n values
2888
-     *
2889
-     * @param EE_Base_Class|array $obj_or_fields_array
2890
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2891
-     *                                                 when looking for conflicts
2892
-     *                                                 (ie, if false, we ignore the model object's primary key
2893
-     *                                                 when finding "conflicts". If true, it's also considered).
2894
-     *                                                 Only works for INT primary key,
2895
-     *                                                 STRING primary keys cannot be ignored
2896
-     * @throws EE_Error
2897
-     * @return EE_Base_Class|array
2898
-     */
2899
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2900
-    {
2901
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2902
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2903
-        } elseif (is_array($obj_or_fields_array)) {
2904
-            $fields_n_values = $obj_or_fields_array;
2905
-        } else {
2906
-            throw new EE_Error(
2907
-                sprintf(
2908
-                    __(
2909
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2910
-                        "event_espresso"
2911
-                    ),
2912
-                    get_class($this),
2913
-                    $obj_or_fields_array
2914
-                )
2915
-            );
2916
-        }
2917
-        $query_params = array();
2918
-        if ($this->has_primary_key_field()
2919
-            && ($include_primary_key
2920
-                || $this->get_primary_key_field()
2921
-                   instanceof
2922
-                   EE_Primary_Key_String_Field)
2923
-            && isset($fields_n_values[$this->primary_key_name()])
2924
-        ) {
2925
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2926
-        }
2927
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2928
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2929
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2930
-        }
2931
-        //if there is nothing to base this search on, then we shouldn't find anything
2932
-        if (empty($query_params)) {
2933
-            return array();
2934
-        }
2935
-        return $this->get_one($query_params);
2936
-    }
2937
-
2938
-
2939
-
2940
-    /**
2941
-     * Like count, but is optimized and returns a boolean instead of an int
2942
-     *
2943
-     * @param array $query_params
2944
-     * @return boolean
2945
-     * @throws EE_Error
2946
-     */
2947
-    public function exists($query_params)
2948
-    {
2949
-        $query_params['limit'] = 1;
2950
-        return $this->count($query_params) > 0;
2951
-    }
2952
-
2953
-
2954
-
2955
-    /**
2956
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2957
-     *
2958
-     * @param int|string $id
2959
-     * @return boolean
2960
-     * @throws EE_Error
2961
-     */
2962
-    public function exists_by_ID($id)
2963
-    {
2964
-        return $this->exists(
2965
-            array(
2966
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2967
-                array(
2968
-                    $this->primary_key_name() => $id,
2969
-                ),
2970
-            )
2971
-        );
2972
-    }
2973
-
2974
-
2975
-
2976
-    /**
2977
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2978
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2979
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2980
-     * on the main table)
2981
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2982
-     * cases where we want to call it directly rather than via insert().
2983
-     *
2984
-     * @access   protected
2985
-     * @param EE_Table_Base $table
2986
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2987
-     *                                       float
2988
-     * @param int           $new_id          for now we assume only int keys
2989
-     * @throws EE_Error
2990
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2991
-     * @return int ID of new row inserted, or FALSE on failure
2992
-     */
2993
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2994
-    {
2995
-        global $wpdb;
2996
-        $insertion_col_n_values = array();
2997
-        $format_for_insertion = array();
2998
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2999
-        foreach ($fields_on_table as $field_name => $field_obj) {
3000
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3001
-            if ($field_obj->is_auto_increment()) {
3002
-                continue;
3003
-            }
3004
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3005
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
3006
-            if ($prepared_value !== null) {
3007
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3008
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3009
-            }
3010
-        }
3011
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3012
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
3013
-            //so add the fk to the main table as a column
3014
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3015
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3016
-        }
3017
-        //insert the new entry
3018
-        $result = $this->_do_wpdb_query('insert',
3019
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
3020
-        if ($result === false) {
3021
-            return false;
3022
-        }
3023
-        //ok, now what do we return for the ID of the newly-inserted thing?
3024
-        if ($this->has_primary_key_field()) {
3025
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3026
-                return $wpdb->insert_id;
3027
-            }
3028
-            //it's not an auto-increment primary key, so
3029
-            //it must have been supplied
3030
-            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3031
-        }
3032
-        //we can't return a  primary key because there is none. instead return
3033
-        //a unique string indicating this model
3034
-        return $this->get_index_primary_key_string($fields_n_values);
3035
-    }
3036
-
3037
-
3038
-
3039
-    /**
3040
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3041
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3042
-     * and there is no default, we pass it along. WPDB will take care of it)
3043
-     *
3044
-     * @param EE_Model_Field_Base $field_obj
3045
-     * @param array               $fields_n_values
3046
-     * @return mixed string|int|float depending on what the table column will be expecting
3047
-     * @throws EE_Error
3048
-     */
3049
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3050
-    {
3051
-        //if this field doesn't allow nullable, don't allow it
3052
-        if (
3053
-            ! $field_obj->is_nullable()
3054
-            && (
3055
-                ! isset($fields_n_values[$field_obj->get_name()])
3056
-                || $fields_n_values[$field_obj->get_name()] === null
3057
-            )
3058
-        ) {
3059
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3060
-        }
3061
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3062
-            ? $fields_n_values[$field_obj->get_name()]
3063
-            : null;
3064
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3065
-    }
3066
-
3067
-
3068
-
3069
-    /**
3070
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3071
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3072
-     * the field's prepare_for_set() method.
3073
-     *
3074
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3075
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3076
-     *                                   top of file)
3077
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3078
-     *                                   $value is a custom selection
3079
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3080
-     */
3081
-    private function _prepare_value_for_use_in_db($value, $field)
3082
-    {
3083
-        if ($field && $field instanceof EE_Model_Field_Base) {
3084
-            switch ($this->_values_already_prepared_by_model_object) {
3085
-                /** @noinspection PhpMissingBreakStatementInspection */
3086
-                case self::not_prepared_by_model_object:
3087
-                    $value = $field->prepare_for_set($value);
3088
-                //purposefully left out "return"
3089
-                case self::prepared_by_model_object:
3090
-                    /** @noinspection SuspiciousAssignmentsInspection */
3091
-                    $value = $field->prepare_for_use_in_db($value);
3092
-                case self::prepared_for_use_in_db:
3093
-                    //leave the value alone
3094
-            }
3095
-            return $value;
3096
-        }
3097
-        return $value;
3098
-    }
3099
-
3100
-
3101
-
3102
-    /**
3103
-     * Returns the main table on this model
3104
-     *
3105
-     * @return EE_Primary_Table
3106
-     * @throws EE_Error
3107
-     */
3108
-    protected function _get_main_table()
3109
-    {
3110
-        foreach ($this->_tables as $table) {
3111
-            if ($table instanceof EE_Primary_Table) {
3112
-                return $table;
3113
-            }
3114
-        }
3115
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3116
-            'event_espresso'), get_class($this)));
3117
-    }
3118
-
3119
-
3120
-
3121
-    /**
3122
-     * table
3123
-     * returns EE_Primary_Table table name
3124
-     *
3125
-     * @return string
3126
-     * @throws EE_Error
3127
-     */
3128
-    public function table()
3129
-    {
3130
-        return $this->_get_main_table()->get_table_name();
3131
-    }
3132
-
3133
-
3134
-
3135
-    /**
3136
-     * table
3137
-     * returns first EE_Secondary_Table table name
3138
-     *
3139
-     * @return string
3140
-     */
3141
-    public function second_table()
3142
-    {
3143
-        // grab second table from tables array
3144
-        $second_table = end($this->_tables);
3145
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3146
-    }
3147
-
3148
-
3149
-
3150
-    /**
3151
-     * get_table_obj_by_alias
3152
-     * returns table name given it's alias
3153
-     *
3154
-     * @param string $table_alias
3155
-     * @return EE_Primary_Table | EE_Secondary_Table
3156
-     */
3157
-    public function get_table_obj_by_alias($table_alias = '')
3158
-    {
3159
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3160
-    }
3161
-
3162
-
3163
-
3164
-    /**
3165
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3166
-     *
3167
-     * @return EE_Secondary_Table[]
3168
-     */
3169
-    protected function _get_other_tables()
3170
-    {
3171
-        $other_tables = array();
3172
-        foreach ($this->_tables as $table_alias => $table) {
3173
-            if ($table instanceof EE_Secondary_Table) {
3174
-                $other_tables[$table_alias] = $table;
3175
-            }
3176
-        }
3177
-        return $other_tables;
3178
-    }
3179
-
3180
-
3181
-
3182
-    /**
3183
-     * Finds all the fields that correspond to the given table
3184
-     *
3185
-     * @param string $table_alias , array key in EEM_Base::_tables
3186
-     * @return EE_Model_Field_Base[]
3187
-     */
3188
-    public function _get_fields_for_table($table_alias)
3189
-    {
3190
-        return $this->_fields[$table_alias];
3191
-    }
3192
-
3193
-
3194
-
3195
-    /**
3196
-     * Recurses through all the where parameters, and finds all the related models we'll need
3197
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3198
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3199
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3200
-     * related Registration, Transaction, and Payment models.
3201
-     *
3202
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3203
-     * @return EE_Model_Query_Info_Carrier
3204
-     * @throws EE_Error
3205
-     */
3206
-    public function _extract_related_models_from_query($query_params)
3207
-    {
3208
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3209
-        if (array_key_exists(0, $query_params)) {
3210
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3211
-        }
3212
-        if (array_key_exists('group_by', $query_params)) {
3213
-            if (is_array($query_params['group_by'])) {
3214
-                $this->_extract_related_models_from_sub_params_array_values(
3215
-                    $query_params['group_by'],
3216
-                    $query_info_carrier,
3217
-                    'group_by'
3218
-                );
3219
-            } elseif (! empty ($query_params['group_by'])) {
3220
-                $this->_extract_related_model_info_from_query_param(
3221
-                    $query_params['group_by'],
3222
-                    $query_info_carrier,
3223
-                    'group_by'
3224
-                );
3225
-            }
3226
-        }
3227
-        if (array_key_exists('having', $query_params)) {
3228
-            $this->_extract_related_models_from_sub_params_array_keys(
3229
-                $query_params[0],
3230
-                $query_info_carrier,
3231
-                'having'
3232
-            );
3233
-        }
3234
-        if (array_key_exists('order_by', $query_params)) {
3235
-            if (is_array($query_params['order_by'])) {
3236
-                $this->_extract_related_models_from_sub_params_array_keys(
3237
-                    $query_params['order_by'],
3238
-                    $query_info_carrier,
3239
-                    'order_by'
3240
-                );
3241
-            } elseif (! empty($query_params['order_by'])) {
3242
-                $this->_extract_related_model_info_from_query_param(
3243
-                    $query_params['order_by'],
3244
-                    $query_info_carrier,
3245
-                    'order_by'
3246
-                );
3247
-            }
3248
-        }
3249
-        if (array_key_exists('force_join', $query_params)) {
3250
-            $this->_extract_related_models_from_sub_params_array_values(
3251
-                $query_params['force_join'],
3252
-                $query_info_carrier,
3253
-                'force_join'
3254
-            );
3255
-        }
3256
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3257
-        return $query_info_carrier;
3258
-    }
3259
-
3260
-
3261
-
3262
-    /**
3263
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3264
-     *
3265
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3266
-     *                                                      $query_params['having']
3267
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3268
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3269
-     * @throws EE_Error
3270
-     * @return \EE_Model_Query_Info_Carrier
3271
-     */
3272
-    private function _extract_related_models_from_sub_params_array_keys(
3273
-        $sub_query_params,
3274
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3275
-        $query_param_type
3276
-    ) {
3277
-        if (! empty($sub_query_params)) {
3278
-            $sub_query_params = (array)$sub_query_params;
3279
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3280
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3281
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3282
-                    $query_param_type);
3283
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3284
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3285
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3286
-                //of array('Registration.TXN_ID'=>23)
3287
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3288
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3289
-                    if (! is_array($possibly_array_of_params)) {
3290
-                        throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3291
-                            "event_espresso"),
3292
-                            $param, $possibly_array_of_params));
3293
-                    }
3294
-                    $this->_extract_related_models_from_sub_params_array_keys(
3295
-                        $possibly_array_of_params,
3296
-                        $model_query_info_carrier, $query_param_type
3297
-                    );
3298
-                } elseif ($query_param_type === 0 //ie WHERE
3299
-                          && is_array($possibly_array_of_params)
3300
-                          && isset($possibly_array_of_params[2])
3301
-                          && $possibly_array_of_params[2] == true
3302
-                ) {
3303
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3304
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3305
-                    //from which we should extract query parameters!
3306
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3307
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3308
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3309
-                    }
3310
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3311
-                        $model_query_info_carrier, $query_param_type);
3312
-                }
3313
-            }
3314
-        }
3315
-        return $model_query_info_carrier;
3316
-    }
3317
-
3318
-
3319
-
3320
-    /**
3321
-     * For extracting related models from forced_joins, where the array values contain the info about what
3322
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3323
-     *
3324
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3325
-     *                                                      $query_params['having']
3326
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3327
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3328
-     * @throws EE_Error
3329
-     * @return \EE_Model_Query_Info_Carrier
3330
-     */
3331
-    private function _extract_related_models_from_sub_params_array_values(
3332
-        $sub_query_params,
3333
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3334
-        $query_param_type
3335
-    ) {
3336
-        if (! empty($sub_query_params)) {
3337
-            if (! is_array($sub_query_params)) {
3338
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3339
-                    $sub_query_params));
3340
-            }
3341
-            foreach ($sub_query_params as $param) {
3342
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3343
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3344
-                    $query_param_type);
3345
-            }
3346
-        }
3347
-        return $model_query_info_carrier;
3348
-    }
3349
-
3350
-
3351
-
3352
-    /**
3353
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3354
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3355
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3356
-     * but use them in a different order. Eg, we need to know what models we are querying
3357
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3358
-     * other models before we can finalize the where clause SQL.
3359
-     *
3360
-     * @param array $query_params
3361
-     * @throws EE_Error
3362
-     * @return EE_Model_Query_Info_Carrier
3363
-     */
3364
-    public function _create_model_query_info_carrier($query_params)
3365
-    {
3366
-        if (! is_array($query_params)) {
3367
-            EE_Error::doing_it_wrong(
3368
-                'EEM_Base::_create_model_query_info_carrier',
3369
-                sprintf(
3370
-                    __(
3371
-                        '$query_params should be an array, you passed a variable of type %s',
3372
-                        'event_espresso'
3373
-                    ),
3374
-                    gettype($query_params)
3375
-                ),
3376
-                '4.6.0'
3377
-            );
3378
-            $query_params = array();
3379
-        }
3380
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3381
-        //first check if we should alter the query to account for caps or not
3382
-        //because the caps might require us to do extra joins
3383
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3384
-            $query_params[0] = $where_query_params = array_replace_recursive(
3385
-                $where_query_params,
3386
-                $this->caps_where_conditions(
3387
-                    $query_params['caps']
3388
-                )
3389
-            );
3390
-        }
3391
-        $query_object = $this->_extract_related_models_from_query($query_params);
3392
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3393
-        foreach ($where_query_params as $key => $value) {
3394
-            if (is_int($key)) {
3395
-                throw new EE_Error(
3396
-                    sprintf(
3397
-                        __(
3398
-                            "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.",
3399
-                            "event_espresso"
3400
-                        ),
3401
-                        $key,
3402
-                        var_export($value, true),
3403
-                        var_export($query_params, true),
3404
-                        get_class($this)
3405
-                    )
3406
-                );
3407
-            }
3408
-        }
3409
-        if (
3410
-            array_key_exists('default_where_conditions', $query_params)
3411
-            && ! empty($query_params['default_where_conditions'])
3412
-        ) {
3413
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3414
-        } else {
3415
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3416
-        }
3417
-        $where_query_params = array_merge(
3418
-            $this->_get_default_where_conditions_for_models_in_query(
3419
-                $query_object,
3420
-                $use_default_where_conditions,
3421
-                $where_query_params
3422
-            ),
3423
-            $where_query_params
3424
-        );
3425
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3426
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3427
-        // So we need to setup a subquery and use that for the main join.
3428
-        // Note for now this only works on the primary table for the model.
3429
-        // So for instance, you could set the limit array like this:
3430
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3431
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3432
-            $query_object->set_main_model_join_sql(
3433
-                $this->_construct_limit_join_select(
3434
-                    $query_params['on_join_limit'][0],
3435
-                    $query_params['on_join_limit'][1]
3436
-                )
3437
-            );
3438
-        }
3439
-        //set limit
3440
-        if (array_key_exists('limit', $query_params)) {
3441
-            if (is_array($query_params['limit'])) {
3442
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3443
-                    $e = sprintf(
3444
-                        __(
3445
-                            "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)",
3446
-                            "event_espresso"
3447
-                        ),
3448
-                        http_build_query($query_params['limit'])
3449
-                    );
3450
-                    throw new EE_Error($e . "|" . $e);
3451
-                }
3452
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3453
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3454
-            } elseif (! empty ($query_params['limit'])) {
3455
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3456
-            }
3457
-        }
3458
-        //set order by
3459
-        if (array_key_exists('order_by', $query_params)) {
3460
-            if (is_array($query_params['order_by'])) {
3461
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3462
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3463
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3464
-                if (array_key_exists('order', $query_params)) {
3465
-                    throw new EE_Error(
3466
-                        sprintf(
3467
-                            __(
3468
-                                "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 ",
3469
-                                "event_espresso"
3470
-                            ),
3471
-                            get_class($this),
3472
-                            implode(", ", array_keys($query_params['order_by'])),
3473
-                            implode(", ", $query_params['order_by']),
3474
-                            $query_params['order']
3475
-                        )
3476
-                    );
3477
-                }
3478
-                $this->_extract_related_models_from_sub_params_array_keys(
3479
-                    $query_params['order_by'],
3480
-                    $query_object,
3481
-                    'order_by'
3482
-                );
3483
-                //assume it's an array of fields to order by
3484
-                $order_array = array();
3485
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3486
-                    $order = $this->_extract_order($order);
3487
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3488
-                }
3489
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3490
-            } elseif (! empty ($query_params['order_by'])) {
3491
-                $this->_extract_related_model_info_from_query_param(
3492
-                    $query_params['order_by'],
3493
-                    $query_object,
3494
-                    'order',
3495
-                    $query_params['order_by']
3496
-                );
3497
-                $order = isset($query_params['order'])
3498
-                    ? $this->_extract_order($query_params['order'])
3499
-                    : 'DESC';
3500
-                $query_object->set_order_by_sql(
3501
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3502
-                );
3503
-            }
3504
-        }
3505
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3506
-        if (! array_key_exists('order_by', $query_params)
3507
-            && array_key_exists('order', $query_params)
3508
-            && ! empty($query_params['order'])
3509
-        ) {
3510
-            $pk_field = $this->get_primary_key_field();
3511
-            $order = $this->_extract_order($query_params['order']);
3512
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3513
-        }
3514
-        //set group by
3515
-        if (array_key_exists('group_by', $query_params)) {
3516
-            if (is_array($query_params['group_by'])) {
3517
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3518
-                $group_by_array = array();
3519
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3520
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3521
-                }
3522
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3523
-            } elseif (! empty ($query_params['group_by'])) {
3524
-                $query_object->set_group_by_sql(
3525
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3526
-                );
3527
-            }
3528
-        }
3529
-        //set having
3530
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3531
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3532
-        }
3533
-        //now, just verify they didn't pass anything wack
3534
-        foreach ($query_params as $query_key => $query_value) {
3535
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3536
-                throw new EE_Error(
3537
-                    sprintf(
3538
-                        __(
3539
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3540
-                            'event_espresso'
3541
-                        ),
3542
-                        $query_key,
3543
-                        get_class($this),
3544
-                        //						print_r( $this->_allowed_query_params, TRUE )
3545
-                        implode(',', $this->_allowed_query_params)
3546
-                    )
3547
-                );
3548
-            }
3549
-        }
3550
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3551
-        if (empty($main_model_join_sql)) {
3552
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3553
-        }
3554
-        return $query_object;
3555
-    }
3556
-
3557
-
3558
-
3559
-    /**
3560
-     * Gets the where conditions that should be imposed on the query based on the
3561
-     * context (eg reading frontend, backend, edit or delete).
3562
-     *
3563
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3564
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3565
-     * @throws EE_Error
3566
-     */
3567
-    public function caps_where_conditions($context = self::caps_read)
3568
-    {
3569
-        EEM_Base::verify_is_valid_cap_context($context);
3570
-        $cap_where_conditions = array();
3571
-        $cap_restrictions = $this->caps_missing($context);
3572
-        /**
3573
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3574
-         */
3575
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3576
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3577
-                $restriction_if_no_cap->get_default_where_conditions());
3578
-        }
3579
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3580
-            $cap_restrictions);
3581
-    }
3582
-
3583
-
3584
-
3585
-    /**
3586
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3587
-     * otherwise throws an exception
3588
-     *
3589
-     * @param string $should_be_order_string
3590
-     * @return string either ASC, asc, DESC or desc
3591
-     * @throws EE_Error
3592
-     */
3593
-    private function _extract_order($should_be_order_string)
3594
-    {
3595
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3596
-            return $should_be_order_string;
3597
-        }
3598
-        throw new EE_Error(
3599
-            sprintf(
3600
-                __(
3601
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3602
-                    "event_espresso"
3603
-                ), get_class($this), $should_be_order_string
3604
-            )
3605
-        );
3606
-    }
3607
-
3608
-
3609
-
3610
-    /**
3611
-     * Looks at all the models which are included in this query, and asks each
3612
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3613
-     * so they can be merged
3614
-     *
3615
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3616
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3617
-     *                                                                  'none' means NO default where conditions will
3618
-     *                                                                  be used AT ALL during this query.
3619
-     *                                                                  'other_models_only' means default where
3620
-     *                                                                  conditions from other models will be used, but
3621
-     *                                                                  not for this primary model. 'all', the default,
3622
-     *                                                                  means default where conditions will apply as
3623
-     *                                                                  normal
3624
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3625
-     * @throws EE_Error
3626
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3627
-     */
3628
-    private function _get_default_where_conditions_for_models_in_query(
3629
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3630
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3631
-        $where_query_params = array()
3632
-    ) {
3633
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3634
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3635
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3636
-                "event_espresso"), $use_default_where_conditions,
3637
-                implode(", ", $allowed_used_default_where_conditions_values)));
3638
-        }
3639
-        $universal_query_params = array();
3640
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3641
-            $universal_query_params = $this->_get_default_where_conditions();
3642
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3643
-            $universal_query_params = $this->_get_minimum_where_conditions();
3644
-        }
3645
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3646
-            $related_model = $this->get_related_model_obj($model_name);
3647
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3648
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3649
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3650
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3651
-            } else {
3652
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3653
-                continue;
3654
-            }
3655
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3656
-                $related_model_universal_where_params,
3657
-                $where_query_params,
3658
-                $related_model,
3659
-                $model_relation_path
3660
-            );
3661
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3662
-                $universal_query_params,
3663
-                $overrides
3664
-            );
3665
-        }
3666
-        return $universal_query_params;
3667
-    }
3668
-
3669
-
3670
-
3671
-    /**
3672
-     * Determines whether or not we should use default where conditions for the model in question
3673
-     * (this model, or other related models).
3674
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3675
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3676
-     * We should use default where conditions on related models when they requested to use default where conditions
3677
-     * on all models, or specifically just on other related models
3678
-     * @param      $default_where_conditions_value
3679
-     * @param bool $for_this_model false means this is for OTHER related models
3680
-     * @return bool
3681
-     */
3682
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3683
-    {
3684
-        return (
3685
-                   $for_this_model
3686
-                   && in_array(
3687
-                       $default_where_conditions_value,
3688
-                       array(
3689
-                           EEM_Base::default_where_conditions_all,
3690
-                           EEM_Base::default_where_conditions_this_only,
3691
-                           EEM_Base::default_where_conditions_minimum_others,
3692
-                       ),
3693
-                       true
3694
-                   )
3695
-               )
3696
-               || (
3697
-                   ! $for_this_model
3698
-                   && in_array(
3699
-                       $default_where_conditions_value,
3700
-                       array(
3701
-                           EEM_Base::default_where_conditions_all,
3702
-                           EEM_Base::default_where_conditions_others_only,
3703
-                       ),
3704
-                       true
3705
-                   )
3706
-               );
3707
-    }
3708
-
3709
-    /**
3710
-     * Determines whether or not we should use default minimum conditions for the model in question
3711
-     * (this model, or other related models).
3712
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3713
-     * where conditions.
3714
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3715
-     * on this model or others
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_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3721
-    {
3722
-        return (
3723
-                   $for_this_model
3724
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3725
-               )
3726
-               || (
3727
-                   ! $for_this_model
3728
-                   && in_array(
3729
-                       $default_where_conditions_value,
3730
-                       array(
3731
-                           EEM_Base::default_where_conditions_minimum_others,
3732
-                           EEM_Base::default_where_conditions_minimum_all,
3733
-                       ),
3734
-                       true
3735
-                   )
3736
-               );
3737
-    }
3738
-
3739
-
3740
-    /**
3741
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3742
-     * then we also add a special where condition which allows for that model's primary key
3743
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3744
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3745
-     *
3746
-     * @param array    $default_where_conditions
3747
-     * @param array    $provided_where_conditions
3748
-     * @param EEM_Base $model
3749
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3750
-     * @return array like EEM_Base::get_all's $query_params[0]
3751
-     * @throws EE_Error
3752
-     */
3753
-    private function _override_defaults_or_make_null_friendly(
3754
-        $default_where_conditions,
3755
-        $provided_where_conditions,
3756
-        $model,
3757
-        $model_relation_path
3758
-    ) {
3759
-        $null_friendly_where_conditions = array();
3760
-        $none_overridden = true;
3761
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3762
-        foreach ($default_where_conditions as $key => $val) {
3763
-            if (isset($provided_where_conditions[$key])) {
3764
-                $none_overridden = false;
3765
-            } else {
3766
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3767
-            }
3768
-        }
3769
-        if ($none_overridden && $default_where_conditions) {
3770
-            if ($model->has_primary_key_field()) {
3771
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3772
-                                                                                . "."
3773
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3774
-            }/*else{
37
+	/**
38
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
41
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
+	 *
43
+	 * @var boolean
44
+	 */
45
+	private $_values_already_prepared_by_model_object = 0;
46
+
47
+	/**
48
+	 * when $_values_already_prepared_by_model_object equals this, we assume
49
+	 * the data is just like form input that needs to have the model fields'
50
+	 * prepare_for_set and prepare_for_use_in_db called on it
51
+	 */
52
+	const not_prepared_by_model_object = 0;
53
+
54
+	/**
55
+	 * when $_values_already_prepared_by_model_object equals this, we
56
+	 * assume this value is coming from a model object and doesn't need to have
57
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
58
+	 */
59
+	const prepared_by_model_object = 1;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the values are already to be used in the database (ie no processing is done
64
+	 * on them by the model's fields)
65
+	 */
66
+	const prepared_for_use_in_db = 2;
67
+
68
+
69
+	protected $singular_item = 'Item';
70
+
71
+	protected $plural_item   = 'Items';
72
+
73
+	/**
74
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
+	 */
76
+	protected $_tables;
77
+
78
+	/**
79
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
+	 *
83
+	 * @var \EE_Model_Field_Base[][] $_fields
84
+	 */
85
+	protected $_fields;
86
+
87
+	/**
88
+	 * array of different kinds of relations
89
+	 *
90
+	 * @var \EE_Model_Relation_Base[] $_model_relations
91
+	 */
92
+	protected $_model_relations;
93
+
94
+	/**
95
+	 * @var \EE_Index[] $_indexes
96
+	 */
97
+	protected $_indexes = array();
98
+
99
+	/**
100
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
101
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
+	 * by setting the same columns as used in these queries in the query yourself.
103
+	 *
104
+	 * @var EE_Default_Where_Conditions
105
+	 */
106
+	protected $_default_where_conditions_strategy;
107
+
108
+	/**
109
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
+	 * This is particularly useful when you want something between 'none' and 'default'
111
+	 *
112
+	 * @var EE_Default_Where_Conditions
113
+	 */
114
+	protected $_minimum_where_conditions_strategy;
115
+
116
+	/**
117
+	 * String describing how to find the "owner" of this model's objects.
118
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
+	 * But when there isn't, this indicates which related model, or transiently-related model,
120
+	 * has the foreign key to the wp_users table.
121
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
+	 * related to events, and events have a foreign key to wp_users.
123
+	 * On EEM_Transaction, this would be 'Transaction.Event'
124
+	 *
125
+	 * @var string
126
+	 */
127
+	protected $_model_chain_to_wp_user = '';
128
+
129
+	/**
130
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
+	 * don't need it (particularly CPT models)
132
+	 *
133
+	 * @var bool
134
+	 */
135
+	protected $_ignore_where_strategy = false;
136
+
137
+	/**
138
+	 * String used in caps relating to this model. Eg, if the caps relating to this
139
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
+	 *
141
+	 * @var string. If null it hasn't been initialized yet. If false then we
142
+	 * have indicated capabilities don't apply to this
143
+	 */
144
+	protected $_caps_slug = null;
145
+
146
+	/**
147
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
+	 * and next-level keys are capability names, and each's value is a
149
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
151
+	 * and then each capability in the corresponding sub-array that they're missing
152
+	 * adds the where conditions onto the query.
153
+	 *
154
+	 * @var array
155
+	 */
156
+	protected $_cap_restrictions = array(
157
+		self::caps_read       => array(),
158
+		self::caps_read_admin => array(),
159
+		self::caps_edit       => array(),
160
+		self::caps_delete     => array(),
161
+	);
162
+
163
+	/**
164
+	 * Array defining which cap restriction generators to use to create default
165
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
166
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
+	 * automatically set this to false (not just null).
169
+	 *
170
+	 * @var EE_Restriction_Generator_Base[]
171
+	 */
172
+	protected $_cap_restriction_generators = array();
173
+
174
+	/**
175
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
+	 */
177
+	const caps_read       = 'read';
178
+
179
+	const caps_read_admin = 'read_admin';
180
+
181
+	const caps_edit       = 'edit';
182
+
183
+	const caps_delete     = 'delete';
184
+
185
+	/**
186
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
+	 * maps to 'read' because when looking for relevant permissions we're going to use
189
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
190
+	 *
191
+	 * @var array
192
+	 */
193
+	protected $_cap_contexts_to_cap_action_map = array(
194
+		self::caps_read       => 'read',
195
+		self::caps_read_admin => 'read',
196
+		self::caps_edit       => 'edit',
197
+		self::caps_delete     => 'delete',
198
+	);
199
+
200
+	/**
201
+	 * Timezone
202
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
+	 * EE_Datetime_Field data type will have access to it.
206
+	 *
207
+	 * @var string
208
+	 */
209
+	protected $_timezone;
210
+
211
+
212
+	/**
213
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
+	 * multisite.
215
+	 *
216
+	 * @var int
217
+	 */
218
+	protected static $_model_query_blog_id;
219
+
220
+	/**
221
+	 * A copy of _fields, except the array keys are the model names pointed to by
222
+	 * the field
223
+	 *
224
+	 * @var EE_Model_Field_Base[]
225
+	 */
226
+	private $_cache_foreign_key_to_fields = array();
227
+
228
+	/**
229
+	 * Cached list of all the fields on the model, indexed by their name
230
+	 *
231
+	 * @var EE_Model_Field_Base[]
232
+	 */
233
+	private $_cached_fields = null;
234
+
235
+	/**
236
+	 * Cached list of all the fields on the model, except those that are
237
+	 * marked as only pertinent to the database
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cached_fields_non_db_only = null;
242
+
243
+	/**
244
+	 * A cached reference to the primary key for quick lookup
245
+	 *
246
+	 * @var EE_Model_Field_Base
247
+	 */
248
+	private $_primary_key_field = null;
249
+
250
+	/**
251
+	 * Flag indicating whether this model has a primary key or not
252
+	 *
253
+	 * @var boolean
254
+	 */
255
+	protected $_has_primary_key_field = null;
256
+
257
+	/**
258
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
259
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
+	 * This should be true for models that deal with data that should exist independent of EE.
261
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
263
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
265
+	 * @var boolean
266
+	 */
267
+	protected $_wp_core_model = false;
268
+
269
+	/**
270
+	 *    List of valid operators that can be used for querying.
271
+	 * The keys are all operators we'll accept, the values are the real SQL
272
+	 * operators used
273
+	 *
274
+	 * @var array
275
+	 */
276
+	protected $_valid_operators = array(
277
+		'='           => '=',
278
+		'<='          => '<=',
279
+		'<'           => '<',
280
+		'>='          => '>=',
281
+		'>'           => '>',
282
+		'!='          => '!=',
283
+		'LIKE'        => 'LIKE',
284
+		'like'        => 'LIKE',
285
+		'NOT_LIKE'    => 'NOT LIKE',
286
+		'not_like'    => 'NOT LIKE',
287
+		'NOT LIKE'    => 'NOT LIKE',
288
+		'not like'    => 'NOT LIKE',
289
+		'IN'          => 'IN',
290
+		'in'          => 'IN',
291
+		'NOT_IN'      => 'NOT IN',
292
+		'not_in'      => 'NOT IN',
293
+		'NOT IN'      => 'NOT IN',
294
+		'not in'      => 'NOT IN',
295
+		'between'     => 'BETWEEN',
296
+		'BETWEEN'     => 'BETWEEN',
297
+		'IS_NOT_NULL' => 'IS NOT NULL',
298
+		'is_not_null' => 'IS NOT NULL',
299
+		'IS NOT NULL' => 'IS NOT NULL',
300
+		'is not null' => 'IS NOT NULL',
301
+		'IS_NULL'     => 'IS NULL',
302
+		'is_null'     => 'IS NULL',
303
+		'IS NULL'     => 'IS NULL',
304
+		'is null'     => 'IS NULL',
305
+		'REGEXP'      => 'REGEXP',
306
+		'regexp'      => 'REGEXP',
307
+		'NOT_REGEXP'  => 'NOT REGEXP',
308
+		'not_regexp'  => 'NOT REGEXP',
309
+		'NOT REGEXP'  => 'NOT REGEXP',
310
+		'not regexp'  => 'NOT REGEXP',
311
+	);
312
+
313
+	/**
314
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_in_style_operators = array('IN', 'NOT IN');
319
+
320
+	/**
321
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
+	 * '12-31-2012'"
323
+	 *
324
+	 * @var array
325
+	 */
326
+	protected $_between_style_operators = array('BETWEEN');
327
+
328
+	/**
329
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
+	 * @var array
331
+	 */
332
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
+	/**
334
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
+	 * on a join table.
336
+	 *
337
+	 * @var array
338
+	 */
339
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
+
341
+	/**
342
+	 * Allowed values for $query_params['order'] for ordering in queries
343
+	 *
344
+	 * @var array
345
+	 */
346
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
+
348
+	/**
349
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
351
+	 *
352
+	 * @var array
353
+	 */
354
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
+
356
+	/**
357
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
359
+	 *
360
+	 * @var array
361
+	 */
362
+	private $_allowed_query_params = array(
363
+		0,
364
+		'limit',
365
+		'order_by',
366
+		'group_by',
367
+		'having',
368
+		'force_join',
369
+		'order',
370
+		'on_join_limit',
371
+		'default_where_conditions',
372
+		'caps',
373
+		'extra_selects'
374
+	);
375
+
376
+	/**
377
+	 * All the data types that can be used in $wpdb->prepare statements.
378
+	 *
379
+	 * @var array
380
+	 */
381
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
+
383
+	/**
384
+	 * @var EE_Registry $EE
385
+	 */
386
+	protected $EE = null;
387
+
388
+
389
+	/**
390
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
+	 *
392
+	 * @var int
393
+	 */
394
+	protected $_show_next_x_db_queries = 0;
395
+
396
+	/**
397
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
+	 * WHERE, GROUP_BY, etc.
400
+	 *
401
+	 * @var CustomSelects
402
+	 */
403
+	protected $_custom_selections = array();
404
+
405
+	/**
406
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
+	 * caches every model object we've fetched from the DB on this request
408
+	 *
409
+	 * @var array
410
+	 */
411
+	protected $_entity_map;
412
+
413
+	/**
414
+	 * @var LoaderInterface $loader
415
+	 */
416
+	private static $loader;
417
+
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error (
520
+				sprintf(
521
+					__('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.',
522
+						'event_espresso'),
523
+					get_class($this)
524
+				)
525
+			);
526
+		}
527
+		/**
528
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
+		 */
530
+		if (empty(EEM_Base::$_model_query_blog_id)) {
531
+			EEM_Base::set_model_query_blog_id();
532
+		}
533
+		/**
534
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
+		 * just use EE_Register_Model_Extension
536
+		 *
537
+		 * @var EE_Table_Base[] $_tables
538
+		 */
539
+		$this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+		foreach ($this->_tables as $table_alias => $table_obj) {
541
+			/** @var $table_obj EE_Table_Base */
542
+			$table_obj->_construct_finalize_with_alias($table_alias);
543
+			if ($table_obj instanceof EE_Secondary_Table) {
544
+				/** @var $table_obj EE_Secondary_Table */
545
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
+			}
547
+		}
548
+		/**
549
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
+		 * EE_Register_Model_Extension
551
+		 *
552
+		 * @param EE_Model_Field_Base[] $_fields
553
+		 */
554
+		$this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+		$this->_invalidate_field_caches();
556
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
557
+			if (! array_key_exists($table_alias, $this->_tables)) {
558
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
+			}
561
+			foreach ($fields_for_table as $field_name => $field_obj) {
562
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
+				//primary key field base has a slightly different _construct_finalize
564
+				/** @var $field_obj EE_Model_Field_Base */
565
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
+			}
567
+		}
568
+		// everything is related to Extra_Meta
569
+		if (get_class($this) !== 'EEM_Extra_Meta') {
570
+			//make extra meta related to everything, but don't block deleting things just
571
+			//because they have related extra meta info. For now just orphan those extra meta
572
+			//in the future we should automatically delete them
573
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		//and change logs
576
+		if (get_class($this) !== 'EEM_Change_Log') {
577
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		/**
580
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
+		 * EE_Register_Model_Extension
582
+		 *
583
+		 * @param EE_Model_Relation_Base[] $_model_relations
584
+		 */
585
+		$this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+			$this->_model_relations);
587
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
588
+			/** @var $relation_obj EE_Model_Relation_Base */
589
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
+		}
591
+		foreach ($this->_indexes as $index_name => $index_obj) {
592
+			/** @var $index_obj EE_Index */
593
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
+		}
595
+		$this->set_timezone($timezone);
596
+		//finalize default where condition strategy, or set default
597
+		if (! $this->_default_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
602
+		if (! $this->_minimum_where_conditions_strategy) {
603
+			//nothing was set during child constructor, so set default
604
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
+		}
606
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
608
+		//to indicate to NOT set it, set it to the logical default
609
+		if ($this->_caps_slug === null) {
610
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
+		}
612
+		//initialize the standard cap restriction generators if none were specified by the child constructor
613
+		if ($this->_cap_restriction_generators !== false) {
614
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
617
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
+						new EE_Restriction_Generator_Protected(),
619
+						$cap_context,
620
+						$this
621
+					);
622
+				}
623
+			}
624
+		}
625
+		//if there are cap restriction generators, use them to make the default cap restrictions
626
+		if ($this->_cap_restriction_generators !== false) {
627
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
+				if (! $generator_object) {
629
+					continue;
630
+				}
631
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+					throw new EE_Error(
633
+						sprintf(
634
+							__('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.',
635
+								'event_espresso'),
636
+							$context,
637
+							$this->get_this_model_name()
638
+						)
639
+					);
640
+				}
641
+				$action = $this->cap_action_for_context($context);
642
+				if (! $generator_object->construction_finalized()) {
643
+					$generator_object->_construct_finalize($this, $action);
644
+				}
645
+			}
646
+		}
647
+		do_action('AHEE__' . get_class($this) . '__construct__end');
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Used to set the $_model_query_blog_id static property.
654
+	 *
655
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
656
+	 *                      value for get_current_blog_id() will be used.
657
+	 */
658
+	public static function set_model_query_blog_id($blog_id = 0)
659
+	{
660
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
661
+	}
662
+
663
+
664
+
665
+	/**
666
+	 * Returns whatever is set as the internal $model_query_blog_id.
667
+	 *
668
+	 * @return int
669
+	 */
670
+	public static function get_model_query_blog_id()
671
+	{
672
+		return EEM_Base::$_model_query_blog_id;
673
+	}
674
+
675
+
676
+
677
+	/**
678
+	 * This function is a singleton method used to instantiate the Espresso_model object
679
+	 *
680
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
681
+	 *                                (and any incoming timezone data that gets saved).
682
+	 *                                Note this just sends the timezone info to the date time model field objects.
683
+	 *                                Default is NULL
684
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
685
+	 * @return static (as in the concrete child class)
686
+	 * @throws EE_Error
687
+	 * @throws InvalidArgumentException
688
+	 * @throws InvalidDataTypeException
689
+	 * @throws InvalidInterfaceException
690
+	 */
691
+	public static function instance($timezone = null)
692
+	{
693
+		// check if instance of Espresso_model already exists
694
+		if (! static::$_instance instanceof static) {
695
+			// instantiate Espresso_model
696
+			static::$_instance = new static(
697
+				$timezone,
698
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
699
+			);
700
+		}
701
+		//we might have a timezone set, let set_timezone decide what to do with it
702
+		static::$_instance->set_timezone($timezone);
703
+		// Espresso_model object
704
+		return static::$_instance;
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 * resets the model and returns it
711
+	 *
712
+	 * @param null | string $timezone
713
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
714
+	 * all its properties reset; if it wasn't instantiated, returns null)
715
+	 * @throws EE_Error
716
+	 * @throws ReflectionException
717
+	 * @throws InvalidArgumentException
718
+	 * @throws InvalidDataTypeException
719
+	 * @throws InvalidInterfaceException
720
+	 */
721
+	public static function reset($timezone = null)
722
+	{
723
+		if (static::$_instance instanceof EEM_Base) {
724
+			//let's try to NOT swap out the current instance for a new one
725
+			//because if someone has a reference to it, we can't remove their reference
726
+			//so it's best to keep using the same reference, but change the original object
727
+			//reset all its properties to their original values as defined in the class
728
+			$r = new ReflectionClass(get_class(static::$_instance));
729
+			$static_properties = $r->getStaticProperties();
730
+			foreach ($r->getDefaultProperties() as $property => $value) {
731
+				//don't set instance to null like it was originally,
732
+				//but it's static anyways, and we're ignoring static properties (for now at least)
733
+				if (! isset($static_properties[$property])) {
734
+					static::$_instance->{$property} = $value;
735
+				}
736
+			}
737
+			//and then directly call its constructor again, like we would if we were creating a new one
738
+			static::$_instance->__construct(
739
+				$timezone,
740
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
741
+			);
742
+			return self::instance();
743
+		}
744
+		return null;
745
+	}
746
+
747
+
748
+
749
+	/**
750
+	 * @return LoaderInterface
751
+	 * @throws InvalidArgumentException
752
+	 * @throws InvalidDataTypeException
753
+	 * @throws InvalidInterfaceException
754
+	 */
755
+	private static function getLoader()
756
+	{
757
+		if(! EEM_Base::$loader instanceof LoaderInterface) {
758
+			EEM_Base::$loader = LoaderFactory::getLoader();
759
+		}
760
+		return EEM_Base::$loader;
761
+	}
762
+
763
+
764
+
765
+	/**
766
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
767
+	 *
768
+	 * @param  boolean $translated return localized strings or JUST the array.
769
+	 * @return array
770
+	 * @throws EE_Error
771
+	 * @throws InvalidArgumentException
772
+	 * @throws InvalidDataTypeException
773
+	 * @throws InvalidInterfaceException
774
+	 */
775
+	public function status_array($translated = false)
776
+	{
777
+		if (! array_key_exists('Status', $this->_model_relations)) {
778
+			return array();
779
+		}
780
+		$model_name = $this->get_this_model_name();
781
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
782
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
783
+		$status_array = array();
784
+		foreach ($stati as $status) {
785
+			$status_array[$status->ID()] = $status->get('STS_code');
786
+		}
787
+		return $translated
788
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
789
+			: $status_array;
790
+	}
791
+
792
+
793
+
794
+	/**
795
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
796
+	 *
797
+	 * @param array $query_params             {
798
+	 * @var array $0 (where) array {
799
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
800
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
801
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
802
+	 *                                        conditions based on related models (and even
803
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
804
+	 *                                        name. Eg,
805
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
806
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
807
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
808
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
809
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
810
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
811
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
812
+	 *                                        to Venues (even when each of those models actually consisted of two
813
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
814
+	 *                                        just having
815
+	 *                                        "Venue.VNU_ID", you could have
816
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
817
+	 *                                        events are related to Registrations, which are related to Attendees). You
818
+	 *                                        can take it even further with
819
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
820
+	 *                                        (from the default of '='), change the value to an numerically-indexed
821
+	 *                                        array, where the first item in the list is the operator. eg: array(
822
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
823
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
824
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
825
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
826
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
827
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
828
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
829
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
830
+	 *                                        the value is a field, simply provide a third array item (true) to the
831
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
832
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
833
+	 *                                        Note: you can also use related model field names like you would any other
834
+	 *                                        field name. eg:
835
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
836
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
837
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
838
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
839
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
840
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
841
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
842
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
843
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
844
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
845
+	 *                                        "stick" until you specify an AND. eg
846
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
847
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
848
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
849
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
850
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
851
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
852
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
853
+	 *                                        too, eg:
854
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
855
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
856
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
857
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
858
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
859
+	 *                                        the OFFSET, the 2nd is the LIMIT
860
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
861
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
862
+	 *                                        following format array('on_join_limit'
863
+	 *                                        => array( 'table_alias', array(1,2) ) ).
864
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
865
+	 *                                        values are either 'ASC' or 'DESC'.
866
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
867
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
868
+	 *                                        DESC..." respectively. Like the
869
+	 *                                        'where' conditions, these fields can be on related models. Eg
870
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
871
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
872
+	 *                                        Attendee, Price, Datetime, etc.)
873
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
874
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
875
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
876
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
877
+	 *                                        order by the primary key. Eg,
878
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
879
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
880
+	 *                                        DTT_EVT_start) or
881
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
882
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
883
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
884
+	 *                                        'group_by'=>'VNU_ID', or
885
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
886
+	 *                                        if no
887
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
888
+	 *                                        model's primary key (or combined primary keys). This avoids some
889
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
890
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
891
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
892
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
893
+	 *                                        results)
894
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
895
+	 *                                        array where values are models to be joined in the query.Eg
896
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
897
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
898
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
899
+	 *                                        related models which belongs to the current model
900
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
901
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
902
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
903
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
904
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
905
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
906
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
907
+	 *                                        this model's default where conditions added to the query, use
908
+	 *                                        'this_model_only'. If you want to use all default where conditions
909
+	 *                                        (default), set to 'all'.
910
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
911
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
912
+	 *                                        everything? Or should we only show the current user items they should be
913
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
914
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
915
+	 *                                        }
916
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
917
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
918
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
919
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
920
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
921
+	 *                                        array( array(
922
+	 *                                        'OR'=>array(
923
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
924
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
925
+	 *                                        )
926
+	 *                                        ),
927
+	 *                                        'limit'=>10,
928
+	 *                                        'group_by'=>'TXN_ID'
929
+	 *                                        ));
930
+	 *                                        get all the answers to the question titled "shirt size" for event with id
931
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
932
+	 *                                        'Question.QST_display_text'=>'shirt size',
933
+	 *                                        'Registration.Event.EVT_ID'=>12
934
+	 *                                        ),
935
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
936
+	 *                                        ));
937
+	 * @throws EE_Error
938
+	 */
939
+	public function get_all($query_params = array())
940
+	{
941
+		if (isset($query_params['limit'])
942
+			&& ! isset($query_params['group_by'])
943
+		) {
944
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
945
+		}
946
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
947
+	}
948
+
949
+
950
+
951
+	/**
952
+	 * Modifies the query parameters so we only get back model objects
953
+	 * that "belong" to the current user
954
+	 *
955
+	 * @param array $query_params @see EEM_Base::get_all()
956
+	 * @return array like EEM_Base::get_all
957
+	 */
958
+	public function alter_query_params_to_only_include_mine($query_params = array())
959
+	{
960
+		$wp_user_field_name = $this->wp_user_field_name();
961
+		if ($wp_user_field_name) {
962
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
963
+		}
964
+		return $query_params;
965
+	}
966
+
967
+
968
+
969
+	/**
970
+	 * Returns the name of the field's name that points to the WP_User table
971
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
972
+	 * foreign key to the WP_User table)
973
+	 *
974
+	 * @return string|boolean string on success, boolean false when there is no
975
+	 * foreign key to the WP_User table
976
+	 */
977
+	public function wp_user_field_name()
978
+	{
979
+		try {
980
+			if (! empty($this->_model_chain_to_wp_user)) {
981
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982
+				$last_model_name = end($models_to_follow_to_wp_users);
983
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
985
+			} else {
986
+				$model_with_fk_to_wp_users = $this;
987
+				$model_chain_to_wp_user = '';
988
+			}
989
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
991
+		} catch (EE_Error $e) {
992
+			return false;
993
+		}
994
+	}
995
+
996
+
997
+
998
+	/**
999
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
1000
+	 * (or transiently-related model) has a foreign key to the wp_users table;
1001
+	 * useful for finding if model objects of this type are 'owned' by the current user.
1002
+	 * This is an empty string when the foreign key is on this model and when it isn't,
1003
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
1004
+	 * (or transiently-related model)
1005
+	 *
1006
+	 * @return string
1007
+	 */
1008
+	public function model_chain_to_wp_user()
1009
+	{
1010
+		return $this->_model_chain_to_wp_user;
1011
+	}
1012
+
1013
+
1014
+
1015
+	/**
1016
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1017
+	 * like how registrations don't have a foreign key to wp_users, but the
1018
+	 * events they are for are), or is unrelated to wp users.
1019
+	 * generally available
1020
+	 *
1021
+	 * @return boolean
1022
+	 */
1023
+	public function is_owned()
1024
+	{
1025
+		if ($this->model_chain_to_wp_user()) {
1026
+			return true;
1027
+		}
1028
+		try {
1029
+			$this->get_foreign_key_to('WP_User');
1030
+			return true;
1031
+		} catch (EE_Error $e) {
1032
+			return false;
1033
+		}
1034
+	}
1035
+
1036
+
1037
+	/**
1038
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1039
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1040
+	 * the model)
1041
+	 *
1042
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1043
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1044
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1045
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1046
+	 *                                  override this and set the select to "*", or a specific column name, like
1047
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1048
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1049
+	 *                                  the aliases used to refer to this selection, and values are to be
1050
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1051
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1052
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1053
+	 * @throws EE_Error
1054
+	 * @throws InvalidArgumentException
1055
+	 */
1056
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057
+	{
1058
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1059
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1060
+		$select_expressions = $columns_to_select === null
1061
+			? $this->_construct_default_select_sql($model_query_info)
1062
+			: '';
1063
+		if ($this->_custom_selections instanceof CustomSelects) {
1064
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065
+			$select_expressions .= $select_expressions
1066
+				? ', ' . $custom_expressions
1067
+				: $custom_expressions;
1068
+		}
1069
+
1070
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1071
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072
+	}
1073
+
1074
+
1075
+	/**
1076
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1077
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1078
+	 * method of including extra select information.
1079
+	 *
1080
+	 * @param array             $query_params
1081
+	 * @param null|array|string $columns_to_select
1082
+	 * @return null|CustomSelects
1083
+	 * @throws InvalidArgumentException
1084
+	 */
1085
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086
+	{
1087
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088
+			return null;
1089
+		}
1090
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1091
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1092
+		return new CustomSelects($selects);
1093
+	}
1094
+
1095
+
1096
+
1097
+	/**
1098
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1099
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1100
+	 * take care of joins, field preparation etc.
1101
+	 *
1102
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1103
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1104
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1105
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1106
+	 *                                  override this and set the select to "*", or a specific column name, like
1107
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1108
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1109
+	 *                                  the aliases used to refer to this selection, and values are to be
1110
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1111
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1112
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1113
+	 * @throws EE_Error
1114
+	 */
1115
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1116
+	{
1117
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1118
+	}
1119
+
1120
+
1121
+
1122
+	/**
1123
+	 * For creating a custom select statement
1124
+	 *
1125
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1126
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1127
+	 *                                 SQL, and 1=>is the datatype
1128
+	 * @throws EE_Error
1129
+	 * @return string
1130
+	 */
1131
+	private function _construct_select_from_input($columns_to_select)
1132
+	{
1133
+		if (is_array($columns_to_select)) {
1134
+			$select_sql_array = array();
1135
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137
+					throw new EE_Error(
1138
+						sprintf(
1139
+							__(
1140
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1141
+								'event_espresso'
1142
+							),
1143
+							$selection_and_datatype,
1144
+							$alias
1145
+						)
1146
+					);
1147
+				}
1148
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149
+					throw new EE_Error(
1150
+						sprintf(
1151
+							esc_html__(
1152
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1153
+								'event_espresso'
1154
+							),
1155
+							$selection_and_datatype[1],
1156
+							$selection_and_datatype[0],
1157
+							$alias,
1158
+							implode(', ', $this->_valid_wpdb_data_types)
1159
+						)
1160
+					);
1161
+				}
1162
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1163
+			}
1164
+			$columns_to_select_string = implode(', ', $select_sql_array);
1165
+		} else {
1166
+			$columns_to_select_string = $columns_to_select;
1167
+		}
1168
+		return $columns_to_select_string;
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1175
+	 *
1176
+	 * @return string
1177
+	 * @throws EE_Error
1178
+	 */
1179
+	public function primary_key_name()
1180
+	{
1181
+		return $this->get_primary_key_field()->get_name();
1182
+	}
1183
+
1184
+
1185
+
1186
+	/**
1187
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1188
+	 * If there is no primary key on this model, $id is treated as primary key string
1189
+	 *
1190
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1191
+	 * @return EE_Base_Class
1192
+	 */
1193
+	public function get_one_by_ID($id)
1194
+	{
1195
+		if ($this->get_from_entity_map($id)) {
1196
+			return $this->get_from_entity_map($id);
1197
+		}
1198
+		return $this->get_one(
1199
+			$this->alter_query_params_to_restrict_by_ID(
1200
+				$id,
1201
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1202
+			)
1203
+		);
1204
+	}
1205
+
1206
+
1207
+
1208
+	/**
1209
+	 * Alters query parameters to only get items with this ID are returned.
1210
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1211
+	 * or could just be a simple primary key ID
1212
+	 *
1213
+	 * @param int   $id
1214
+	 * @param array $query_params
1215
+	 * @return array of normal query params, @see EEM_Base::get_all
1216
+	 * @throws EE_Error
1217
+	 */
1218
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219
+	{
1220
+		if (! isset($query_params[0])) {
1221
+			$query_params[0] = array();
1222
+		}
1223
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1224
+		if ($conditions_from_id === null) {
1225
+			$query_params[0][$this->primary_key_name()] = $id;
1226
+		} else {
1227
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1228
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
+		}
1230
+		return $query_params;
1231
+	}
1232
+
1233
+
1234
+
1235
+	/**
1236
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1237
+	 * array. If no item is found, null is returned.
1238
+	 *
1239
+	 * @param array $query_params like EEM_Base's $query_params variable.
1240
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1241
+	 * @throws EE_Error
1242
+	 */
1243
+	public function get_one($query_params = array())
1244
+	{
1245
+		if (! is_array($query_params)) {
1246
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1247
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248
+					gettype($query_params)), '4.6.0');
1249
+			$query_params = array();
1250
+		}
1251
+		$query_params['limit'] = 1;
1252
+		$items = $this->get_all($query_params);
1253
+		if (empty($items)) {
1254
+			return null;
1255
+		}
1256
+		return array_shift($items);
1257
+	}
1258
+
1259
+
1260
+
1261
+	/**
1262
+	 * Returns the next x number of items in sequence from the given value as
1263
+	 * found in the database matching the given query conditions.
1264
+	 *
1265
+	 * @param mixed $current_field_value    Value used for the reference point.
1266
+	 * @param null  $field_to_order_by      What field is used for the
1267
+	 *                                      reference point.
1268
+	 * @param int   $limit                  How many to return.
1269
+	 * @param array $query_params           Extra conditions on the query.
1270
+	 * @param null  $columns_to_select      If left null, then an array of
1271
+	 *                                      EE_Base_Class objects is returned,
1272
+	 *                                      otherwise you can indicate just the
1273
+	 *                                      columns you want returned.
1274
+	 * @return EE_Base_Class[]|array
1275
+	 * @throws EE_Error
1276
+	 */
1277
+	public function next_x(
1278
+		$current_field_value,
1279
+		$field_to_order_by = null,
1280
+		$limit = 1,
1281
+		$query_params = array(),
1282
+		$columns_to_select = null
1283
+	) {
1284
+		return $this->_get_consecutive(
1285
+			$current_field_value,
1286
+			'>',
1287
+			$field_to_order_by,
1288
+			$limit,
1289
+			$query_params,
1290
+			$columns_to_select
1291
+		);
1292
+	}
1293
+
1294
+
1295
+
1296
+	/**
1297
+	 * Returns the previous x number of items in sequence from the given value
1298
+	 * as found in the database matching the given query conditions.
1299
+	 *
1300
+	 * @param mixed $current_field_value    Value used for the reference point.
1301
+	 * @param null  $field_to_order_by      What field is used for the
1302
+	 *                                      reference point.
1303
+	 * @param int   $limit                  How many to return.
1304
+	 * @param array $query_params           Extra conditions on the query.
1305
+	 * @param null  $columns_to_select      If left null, then an array of
1306
+	 *                                      EE_Base_Class objects is returned,
1307
+	 *                                      otherwise you can indicate just the
1308
+	 *                                      columns you want returned.
1309
+	 * @return EE_Base_Class[]|array
1310
+	 * @throws EE_Error
1311
+	 */
1312
+	public function previous_x(
1313
+		$current_field_value,
1314
+		$field_to_order_by = null,
1315
+		$limit = 1,
1316
+		$query_params = array(),
1317
+		$columns_to_select = null
1318
+	) {
1319
+		return $this->_get_consecutive(
1320
+			$current_field_value,
1321
+			'<',
1322
+			$field_to_order_by,
1323
+			$limit,
1324
+			$query_params,
1325
+			$columns_to_select
1326
+		);
1327
+	}
1328
+
1329
+
1330
+
1331
+	/**
1332
+	 * Returns the next item in sequence from the given value as found in the
1333
+	 * database matching the given query conditions.
1334
+	 *
1335
+	 * @param mixed $current_field_value    Value used for the reference point.
1336
+	 * @param null  $field_to_order_by      What field is used for the
1337
+	 *                                      reference point.
1338
+	 * @param array $query_params           Extra conditions on the query.
1339
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1340
+	 *                                      object is returned, otherwise you
1341
+	 *                                      can indicate just the columns you
1342
+	 *                                      want and a single array indexed by
1343
+	 *                                      the columns will be returned.
1344
+	 * @return EE_Base_Class|null|array()
1345
+	 * @throws EE_Error
1346
+	 */
1347
+	public function next(
1348
+		$current_field_value,
1349
+		$field_to_order_by = null,
1350
+		$query_params = array(),
1351
+		$columns_to_select = null
1352
+	) {
1353
+		$results = $this->_get_consecutive(
1354
+			$current_field_value,
1355
+			'>',
1356
+			$field_to_order_by,
1357
+			1,
1358
+			$query_params,
1359
+			$columns_to_select
1360
+		);
1361
+		return empty($results) ? null : reset($results);
1362
+	}
1363
+
1364
+
1365
+
1366
+	/**
1367
+	 * Returns the previous item in sequence from the given value as found in
1368
+	 * the database matching the given query conditions.
1369
+	 *
1370
+	 * @param mixed $current_field_value    Value used for the reference point.
1371
+	 * @param null  $field_to_order_by      What field is used for the
1372
+	 *                                      reference point.
1373
+	 * @param array $query_params           Extra conditions on the query.
1374
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1375
+	 *                                      object is returned, otherwise you
1376
+	 *                                      can indicate just the columns you
1377
+	 *                                      want and a single array indexed by
1378
+	 *                                      the columns will be returned.
1379
+	 * @return EE_Base_Class|null|array()
1380
+	 * @throws EE_Error
1381
+	 */
1382
+	public function previous(
1383
+		$current_field_value,
1384
+		$field_to_order_by = null,
1385
+		$query_params = array(),
1386
+		$columns_to_select = null
1387
+	) {
1388
+		$results = $this->_get_consecutive(
1389
+			$current_field_value,
1390
+			'<',
1391
+			$field_to_order_by,
1392
+			1,
1393
+			$query_params,
1394
+			$columns_to_select
1395
+		);
1396
+		return empty($results) ? null : reset($results);
1397
+	}
1398
+
1399
+
1400
+
1401
+	/**
1402
+	 * Returns the a consecutive number of items in sequence from the given
1403
+	 * value as found in the database matching the given query conditions.
1404
+	 *
1405
+	 * @param mixed  $current_field_value   Value used for the reference point.
1406
+	 * @param string $operand               What operand is used for the sequence.
1407
+	 * @param string $field_to_order_by     What field is used for the reference point.
1408
+	 * @param int    $limit                 How many to return.
1409
+	 * @param array  $query_params          Extra conditions on the query.
1410
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1411
+	 *                                      otherwise you can indicate just the columns you want returned.
1412
+	 * @return EE_Base_Class[]|array
1413
+	 * @throws EE_Error
1414
+	 */
1415
+	protected function _get_consecutive(
1416
+		$current_field_value,
1417
+		$operand = '>',
1418
+		$field_to_order_by = null,
1419
+		$limit = 1,
1420
+		$query_params = array(),
1421
+		$columns_to_select = null
1422
+	) {
1423
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1424
+		if (empty($field_to_order_by)) {
1425
+			if ($this->has_primary_key_field()) {
1426
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1427
+			} else {
1428
+				if (WP_DEBUG) {
1429
+					throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1430
+						'event_espresso'));
1431
+				}
1432
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1433
+				return array();
1434
+			}
1435
+		}
1436
+		if (! is_array($query_params)) {
1437
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439
+					gettype($query_params)), '4.6.0');
1440
+			$query_params = array();
1441
+		}
1442
+		//let's add the where query param for consecutive look up.
1443
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444
+		$query_params['limit'] = $limit;
1445
+		//set direction
1446
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1447
+		$query_params['order_by'] = $operand === '>'
1448
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1449
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1450
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
+		if (empty($columns_to_select)) {
1452
+			return $this->get_all($query_params);
1453
+		}
1454
+		//getting just the fields
1455
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
+	}
1457
+
1458
+
1459
+
1460
+	/**
1461
+	 * This sets the _timezone property after model object has been instantiated.
1462
+	 *
1463
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1464
+	 */
1465
+	public function set_timezone($timezone)
1466
+	{
1467
+		if ($timezone !== null) {
1468
+			$this->_timezone = $timezone;
1469
+		}
1470
+		//note we need to loop through relations and set the timezone on those objects as well.
1471
+		foreach ($this->_model_relations as $relation) {
1472
+			$relation->set_timezone($timezone);
1473
+		}
1474
+		//and finally we do the same for any datetime fields
1475
+		foreach ($this->_fields as $field) {
1476
+			if ($field instanceof EE_Datetime_Field) {
1477
+				$field->set_timezone($timezone);
1478
+			}
1479
+		}
1480
+	}
1481
+
1482
+
1483
+
1484
+	/**
1485
+	 * This just returns whatever is set for the current timezone.
1486
+	 *
1487
+	 * @access public
1488
+	 * @return string
1489
+	 */
1490
+	public function get_timezone()
1491
+	{
1492
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1493
+		if (empty($this->_timezone)) {
1494
+			foreach ($this->_fields as $field) {
1495
+				if ($field instanceof EE_Datetime_Field) {
1496
+					$this->set_timezone($field->get_timezone());
1497
+					break;
1498
+				}
1499
+			}
1500
+		}
1501
+		//if timezone STILL empty then return the default timezone for the site.
1502
+		if (empty($this->_timezone)) {
1503
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1504
+		}
1505
+		return $this->_timezone;
1506
+	}
1507
+
1508
+
1509
+
1510
+	/**
1511
+	 * This returns the date formats set for the given field name and also ensures that
1512
+	 * $this->_timezone property is set correctly.
1513
+	 *
1514
+	 * @since 4.6.x
1515
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1516
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1517
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1518
+	 * @return array formats in an array with the date format first, and the time format last.
1519
+	 */
1520
+	public function get_formats_for($field_name, $pretty = false)
1521
+	{
1522
+		$field_settings = $this->field_settings_for($field_name);
1523
+		//if not a valid EE_Datetime_Field then throw error
1524
+		if (! $field_settings instanceof EE_Datetime_Field) {
1525
+			throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1526
+				'event_espresso'), $field_name));
1527
+		}
1528
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1529
+		//the field.
1530
+		$this->_timezone = $field_settings->get_timezone();
1531
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1532
+	}
1533
+
1534
+
1535
+
1536
+	/**
1537
+	 * This returns the current time in a format setup for a query on this model.
1538
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
+	 * it will return:
1540
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
+	 *  NOW
1542
+	 *  - or a unix timestamp (equivalent to time())
1543
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
+	 * @since 4.6.x
1547
+	 * @param string $field_name       The field the current time is needed for.
1548
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
+	 *                                 formatted string matching the set format for the field in the set timezone will
1550
+	 *                                 be returned.
1551
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1553
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1554
+	 *                                 exception is triggered.
1555
+	 */
1556
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1557
+	{
1558
+		$formats = $this->get_formats_for($field_name);
1559
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1560
+		if ($timestamp) {
1561
+			return $DateTime->format('U');
1562
+		}
1563
+		//not returning timestamp, so return formatted string in timezone.
1564
+		switch ($what) {
1565
+			case 'time' :
1566
+				return $DateTime->format($formats[1]);
1567
+				break;
1568
+			case 'date' :
1569
+				return $DateTime->format($formats[0]);
1570
+				break;
1571
+			default :
1572
+				return $DateTime->format(implode(' ', $formats));
1573
+				break;
1574
+		}
1575
+	}
1576
+
1577
+
1578
+
1579
+	/**
1580
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
+	 * for the model are.  Returns a DateTime object.
1582
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
+	 * ignored.
1585
+	 *
1586
+	 * @param string $field_name      The field being setup.
1587
+	 * @param string $timestring      The date time string being used.
1588
+	 * @param string $incoming_format The format for the time string.
1589
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
+	 *                                format is
1592
+	 *                                'U', this is ignored.
1593
+	 * @return DateTime
1594
+	 * @throws EE_Error
1595
+	 */
1596
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
+	{
1598
+		//just using this to ensure the timezone is set correctly internally
1599
+		$this->get_formats_for($field_name);
1600
+		//load EEH_DTT_Helper
1601
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
+		$incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1604
+		// workaround for php datetime bug
1605
+		// @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
1606
+		$incomingDateTime->getTimestamp();
1607
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1608
+	}
1609
+
1610
+
1611
+
1612
+	/**
1613
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1614
+	 *
1615
+	 * @return EE_Table_Base[]
1616
+	 */
1617
+	public function get_tables()
1618
+	{
1619
+		return $this->_tables;
1620
+	}
1621
+
1622
+
1623
+
1624
+	/**
1625
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1626
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1627
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1628
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1629
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1630
+	 * model object with EVT_ID = 1
1631
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1632
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1633
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1634
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1635
+	 * are not specified)
1636
+	 *
1637
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1638
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1639
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1640
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1641
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1642
+	 *                                         ID=34, we'd use this method as follows:
1643
+	 *                                         EEM_Transaction::instance()->update(
1644
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1645
+	 *                                         array(array('TXN_ID'=>34)));
1646
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1647
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1648
+	 *                                         consider updating Question's QST_admin_label field is of type
1649
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1650
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1651
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1652
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1653
+	 *                                         TRUE, it is assumed that you've already called
1654
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1655
+	 *                                         malicious javascript. However, if
1656
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1657
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1658
+	 *                                         and every other field, before insertion. We provide this parameter
1659
+	 *                                         because model objects perform their prepare_for_set function on all
1660
+	 *                                         their values, and so don't need to be called again (and in many cases,
1661
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1662
+	 *                                         prepare_for_set method...)
1663
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1664
+	 *                                         in this model's entity map according to $fields_n_values that match
1665
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1666
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1667
+	 *                                         could get out-of-sync with the database
1668
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1669
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1670
+	 *                                         bad)
1671
+	 * @throws EE_Error
1672
+	 */
1673
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1674
+	{
1675
+		if (! is_array($query_params)) {
1676
+			EE_Error::doing_it_wrong('EEM_Base::update',
1677
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1678
+					gettype($query_params)), '4.6.0');
1679
+			$query_params = array();
1680
+		}
1681
+		/**
1682
+		 * Action called before a model update call has been made.
1683
+		 *
1684
+		 * @param EEM_Base $model
1685
+		 * @param array    $fields_n_values the updated fields and their new values
1686
+		 * @param array    $query_params    @see EEM_Base::get_all()
1687
+		 */
1688
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1689
+		/**
1690
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1691
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1692
+		 *
1693
+		 * @param array    $fields_n_values fields and their new values
1694
+		 * @param EEM_Base $model           the model being queried
1695
+		 * @param array    $query_params    see EEM_Base::get_all()
1696
+		 */
1697
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1698
+			$query_params);
1699
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1700
+		//to do that, for each table, verify that it's PK isn't null.
1701
+		$tables = $this->get_tables();
1702
+		//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
1703
+		//NOTE: we should make this code more efficient by NOT querying twice
1704
+		//before the real update, but that needs to first go through ALPHA testing
1705
+		//as it's dangerous. says Mike August 8 2014
1706
+		//we want to make sure the default_where strategy is ignored
1707
+		$this->_ignore_where_strategy = true;
1708
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1709
+		foreach ($wpdb_select_results as $wpdb_result) {
1710
+			// type cast stdClass as array
1711
+			$wpdb_result = (array)$wpdb_result;
1712
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1713
+			if ($this->has_primary_key_field()) {
1714
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1715
+			} else {
1716
+				//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)
1717
+				$main_table_pk_value = null;
1718
+			}
1719
+			//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
1720
+			//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
1721
+			if (count($tables) > 1) {
1722
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1723
+				//in that table, and so we'll want to insert one
1724
+				foreach ($tables as $table_obj) {
1725
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1726
+					//if there is no private key for this table on the results, it means there's no entry
1727
+					//in this table, right? so insert a row in the current table, using any fields available
1728
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1729
+						   && $wpdb_result[$this_table_pk_column])
1730
+					) {
1731
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1732
+							$main_table_pk_value);
1733
+						//if we died here, report the error
1734
+						if (! $success) {
1735
+							return false;
1736
+						}
1737
+					}
1738
+				}
1739
+			}
1740
+			//				//and now check that if we have cached any models by that ID on the model, that
1741
+			//				//they also get updated properly
1742
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1743
+			//				if( $model_object ){
1744
+			//					foreach( $fields_n_values as $field => $value ){
1745
+			//						$model_object->set($field, $value);
1746
+			//let's make sure default_where strategy is followed now
1747
+			$this->_ignore_where_strategy = false;
1748
+		}
1749
+		//if we want to keep model objects in sync, AND
1750
+		//if this wasn't called from a model object (to update itself)
1751
+		//then we want to make sure we keep all the existing
1752
+		//model objects in sync with the db
1753
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1754
+			if ($this->has_primary_key_field()) {
1755
+				$model_objs_affected_ids = $this->get_col($query_params);
1756
+			} else {
1757
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1758
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1759
+				$model_objs_affected_ids = array();
1760
+				foreach ($models_affected_key_columns as $row) {
1761
+					$combined_index_key = $this->get_index_primary_key_string($row);
1762
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1763
+				}
1764
+			}
1765
+			if (! $model_objs_affected_ids) {
1766
+				//wait wait wait- if nothing was affected let's stop here
1767
+				return 0;
1768
+			}
1769
+			foreach ($model_objs_affected_ids as $id) {
1770
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1771
+				if ($model_obj_in_entity_map) {
1772
+					foreach ($fields_n_values as $field => $new_value) {
1773
+						$model_obj_in_entity_map->set($field, $new_value);
1774
+					}
1775
+				}
1776
+			}
1777
+			//if there is a primary key on this model, we can now do a slight optimization
1778
+			if ($this->has_primary_key_field()) {
1779
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1780
+				$query_params = array(
1781
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1782
+					'limit'                    => count($model_objs_affected_ids),
1783
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1784
+				);
1785
+			}
1786
+		}
1787
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1788
+		$SQL = "UPDATE "
1789
+			   . $model_query_info->get_full_join_sql()
1790
+			   . " SET "
1791
+			   . $this->_construct_update_sql($fields_n_values)
1792
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1793
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1794
+		/**
1795
+		 * Action called after a model update call has been made.
1796
+		 *
1797
+		 * @param EEM_Base $model
1798
+		 * @param array    $fields_n_values the updated fields and their new values
1799
+		 * @param array    $query_params    @see EEM_Base::get_all()
1800
+		 * @param int      $rows_affected
1801
+		 */
1802
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1803
+		return $rows_affected;//how many supposedly got updated
1804
+	}
1805
+
1806
+
1807
+
1808
+	/**
1809
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1810
+	 * are teh values of the field specified (or by default the primary key field)
1811
+	 * that matched the query params. Note that you should pass the name of the
1812
+	 * model FIELD, not the database table's column name.
1813
+	 *
1814
+	 * @param array  $query_params @see EEM_Base::get_all()
1815
+	 * @param string $field_to_select
1816
+	 * @return array just like $wpdb->get_col()
1817
+	 * @throws EE_Error
1818
+	 */
1819
+	public function get_col($query_params = array(), $field_to_select = null)
1820
+	{
1821
+		if ($field_to_select) {
1822
+			$field = $this->field_settings_for($field_to_select);
1823
+		} elseif ($this->has_primary_key_field()) {
1824
+			$field = $this->get_primary_key_field();
1825
+		} else {
1826
+			//no primary key, just grab the first column
1827
+			$field = reset($this->field_settings());
1828
+		}
1829
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1830
+		$select_expressions = $field->get_qualified_column();
1831
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1832
+		return $this->_do_wpdb_query('get_col', array($SQL));
1833
+	}
1834
+
1835
+
1836
+
1837
+	/**
1838
+	 * Returns a single column value for a single row from the database
1839
+	 *
1840
+	 * @param array  $query_params    @see EEM_Base::get_all()
1841
+	 * @param string $field_to_select @see EEM_Base::get_col()
1842
+	 * @return string
1843
+	 * @throws EE_Error
1844
+	 */
1845
+	public function get_var($query_params = array(), $field_to_select = null)
1846
+	{
1847
+		$query_params['limit'] = 1;
1848
+		$col = $this->get_col($query_params, $field_to_select);
1849
+		if (! empty($col)) {
1850
+			return reset($col);
1851
+		}
1852
+		return null;
1853
+	}
1854
+
1855
+
1856
+
1857
+	/**
1858
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1859
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1860
+	 * injection, but currently no further filtering is done
1861
+	 *
1862
+	 * @global      $wpdb
1863
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1864
+	 *                               be updated to in the DB
1865
+	 * @return string of SQL
1866
+	 * @throws EE_Error
1867
+	 */
1868
+	public function _construct_update_sql($fields_n_values)
1869
+	{
1870
+		/** @type WPDB $wpdb */
1871
+		global $wpdb;
1872
+		$cols_n_values = array();
1873
+		foreach ($fields_n_values as $field_name => $value) {
1874
+			$field_obj = $this->field_settings_for($field_name);
1875
+			//if the value is NULL, we want to assign the value to that.
1876
+			//wpdb->prepare doesn't really handle that properly
1877
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1878
+			$value_sql = $prepared_value === null ? 'NULL'
1879
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1880
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1881
+		}
1882
+		return implode(",", $cols_n_values);
1883
+	}
1884
+
1885
+
1886
+
1887
+	/**
1888
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1889
+	 * Performs a HARD delete, meaning the database row should always be removed,
1890
+	 * not just have a flag field on it switched
1891
+	 * Wrapper for EEM_Base::delete_permanently()
1892
+	 *
1893
+	 * @param mixed $id
1894
+	 * @param boolean $allow_blocking
1895
+	 * @return int the number of rows deleted
1896
+	 * @throws EE_Error
1897
+	 */
1898
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1899
+	{
1900
+		return $this->delete_permanently(
1901
+			array(
1902
+				array($this->get_primary_key_field()->get_name() => $id),
1903
+				'limit' => 1,
1904
+			),
1905
+			$allow_blocking
1906
+		);
1907
+	}
1908
+
1909
+
1910
+
1911
+	/**
1912
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1913
+	 * Wrapper for EEM_Base::delete()
1914
+	 *
1915
+	 * @param mixed $id
1916
+	 * @param boolean $allow_blocking
1917
+	 * @return int the number of rows deleted
1918
+	 * @throws EE_Error
1919
+	 */
1920
+	public function delete_by_ID($id, $allow_blocking = true)
1921
+	{
1922
+		return $this->delete(
1923
+			array(
1924
+				array($this->get_primary_key_field()->get_name() => $id),
1925
+				'limit' => 1,
1926
+			),
1927
+			$allow_blocking
1928
+		);
1929
+	}
1930
+
1931
+
1932
+
1933
+	/**
1934
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1935
+	 * meaning if the model has a field that indicates its been "trashed" or
1936
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1937
+	 *
1938
+	 * @see EEM_Base::delete_permanently
1939
+	 * @param array   $query_params
1940
+	 * @param boolean $allow_blocking
1941
+	 * @return int how many rows got deleted
1942
+	 * @throws EE_Error
1943
+	 */
1944
+	public function delete($query_params, $allow_blocking = true)
1945
+	{
1946
+		return $this->delete_permanently($query_params, $allow_blocking);
1947
+	}
1948
+
1949
+
1950
+
1951
+	/**
1952
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1953
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1954
+	 * as archived, not actually deleted
1955
+	 *
1956
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1957
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1958
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1959
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1960
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1961
+	 *                                DB
1962
+	 * @return int how many rows got deleted
1963
+	 * @throws EE_Error
1964
+	 */
1965
+	public function delete_permanently($query_params, $allow_blocking = true)
1966
+	{
1967
+		/**
1968
+		 * Action called just before performing a real deletion query. You can use the
1969
+		 * model and its $query_params to find exactly which items will be deleted
1970
+		 *
1971
+		 * @param EEM_Base $model
1972
+		 * @param array    $query_params   @see EEM_Base::get_all()
1973
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1974
+		 *                                 to block (prevent) this deletion
1975
+		 */
1976
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1977
+		//some MySQL databases may be running safe mode, which may restrict
1978
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1979
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1980
+		//to delete them
1981
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1982
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1983
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1984
+			$columns_and_ids_for_deleting
1985
+		);
1986
+		/**
1987
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1988
+		 *
1989
+		 * @param EEM_Base $this  The model instance being acted on.
1990
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1991
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1992
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1993
+		 *                                                  derived from the incoming query parameters.
1994
+		 *                                                  @see details on the structure of this array in the phpdocs
1995
+		 *                                                  for the `_get_ids_for_delete_method`
1996
+		 *
1997
+		 */
1998
+		do_action('AHEE__EEM_Base__delete__before_query',
1999
+			$this,
2000
+			$query_params,
2001
+			$allow_blocking,
2002
+			$columns_and_ids_for_deleting
2003
+		);
2004
+		if ($deletion_where_query_part) {
2005
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2006
+			$table_aliases = array_keys($this->_tables);
2007
+			$SQL = "DELETE "
2008
+				   . implode(", ", $table_aliases)
2009
+				   . " FROM "
2010
+				   . $model_query_info->get_full_join_sql()
2011
+				   . " WHERE "
2012
+				   . $deletion_where_query_part;
2013
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2014
+		} else {
2015
+			$rows_deleted = 0;
2016
+		}
2017
+
2018
+		//Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2019
+		//there was no error with the delete query.
2020
+		if ($this->has_primary_key_field()
2021
+			&& $rows_deleted !== false
2022
+			&& isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2023
+		) {
2024
+			$ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2025
+			foreach ($ids_for_removal as $id) {
2026
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2027
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2028
+				}
2029
+			}
2030
+
2031
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2032
+			//`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2033
+			//unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2034
+			// (although it is possible).
2035
+			//Note this can be skipped by using the provided filter and returning false.
2036
+			if (apply_filters(
2037
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2038
+				! $this instanceof EEM_Extra_Meta,
2039
+				$this
2040
+			)) {
2041
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2042
+					0 => array(
2043
+						'EXM_type' => $this->get_this_model_name(),
2044
+						'OBJ_ID'   => array(
2045
+							'IN',
2046
+							$ids_for_removal
2047
+						)
2048
+					)
2049
+				));
2050
+			}
2051
+		}
2052
+
2053
+		/**
2054
+		 * Action called just after performing a real deletion query. Although at this point the
2055
+		 * items should have been deleted
2056
+		 *
2057
+		 * @param EEM_Base $model
2058
+		 * @param array    $query_params @see EEM_Base::get_all()
2059
+		 * @param int      $rows_deleted
2060
+		 */
2061
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2062
+		return $rows_deleted;//how many supposedly got deleted
2063
+	}
2064
+
2065
+
2066
+
2067
+	/**
2068
+	 * Checks all the relations that throw error messages when there are blocking related objects
2069
+	 * for related model objects. If there are any related model objects on those relations,
2070
+	 * adds an EE_Error, and return true
2071
+	 *
2072
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2073
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2074
+	 *                                                 should be ignored when determining whether there are related
2075
+	 *                                                 model objects which block this model object's deletion. Useful
2076
+	 *                                                 if you know A is related to B and are considering deleting A,
2077
+	 *                                                 but want to see if A has any other objects blocking its deletion
2078
+	 *                                                 before removing the relation between A and B
2079
+	 * @return boolean
2080
+	 * @throws EE_Error
2081
+	 */
2082
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2083
+	{
2084
+		//first, if $ignore_this_model_obj was supplied, get its model
2085
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2086
+			$ignored_model = $ignore_this_model_obj->get_model();
2087
+		} else {
2088
+			$ignored_model = null;
2089
+		}
2090
+		//now check all the relations of $this_model_obj_or_id and see if there
2091
+		//are any related model objects blocking it?
2092
+		$is_blocked = false;
2093
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2094
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2095
+				//if $ignore_this_model_obj was supplied, then for the query
2096
+				//on that model needs to be told to ignore $ignore_this_model_obj
2097
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2098
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2099
+						array(
2100
+							$ignored_model->get_primary_key_field()->get_name() => array(
2101
+								'!=',
2102
+								$ignore_this_model_obj->ID(),
2103
+							),
2104
+						),
2105
+					));
2106
+				} else {
2107
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2108
+				}
2109
+				if ($related_model_objects) {
2110
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2111
+					$is_blocked = true;
2112
+				}
2113
+			}
2114
+		}
2115
+		return $is_blocked;
2116
+	}
2117
+
2118
+
2119
+	/**
2120
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2121
+	 * @param array $row_results_for_deleting
2122
+	 * @param bool  $allow_blocking
2123
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2124
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2125
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2126
+	 *                 deleted. Example:
2127
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2128
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2129
+	 *                 where each element is a group of columns and values that get deleted. Example:
2130
+	 *                      array(
2131
+	 *                          0 => array(
2132
+	 *                              'Term_Relationship.object_id' => 1
2133
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2134
+	 *                          ),
2135
+	 *                          1 => array(
2136
+	 *                              'Term_Relationship.object_id' => 1
2137
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2138
+	 *                          )
2139
+	 *                      )
2140
+	 * @throws EE_Error
2141
+	 */
2142
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2143
+	{
2144
+		$ids_to_delete_indexed_by_column = array();
2145
+		if ($this->has_primary_key_field()) {
2146
+			$primary_table = $this->_get_main_table();
2147
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2148
+			$other_tables = $this->_get_other_tables();
2149
+			$ids_to_delete_indexed_by_column = $query = array();
2150
+			foreach ($row_results_for_deleting as $item_to_delete) {
2151
+				//before we mark this item for deletion,
2152
+				//make sure there's no related entities blocking its deletion (if we're checking)
2153
+				if (
2154
+					$allow_blocking
2155
+					&& $this->delete_is_blocked_by_related_models(
2156
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2157
+					)
2158
+				) {
2159
+					continue;
2160
+				}
2161
+				//primary table deletes
2162
+				if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2163
+					$ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2164
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2165
+				}
2166
+			}
2167
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2168
+			$fields = $this->get_combined_primary_key_fields();
2169
+			foreach ($row_results_for_deleting as $item_to_delete) {
2170
+				$ids_to_delete_indexed_by_column_for_row = array();
2171
+				foreach ($fields as $cpk_field) {
2172
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2173
+						$ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2174
+							$item_to_delete[$cpk_field->get_qualified_column()];
2175
+					}
2176
+				}
2177
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2178
+			}
2179
+		} else {
2180
+			//so there's no primary key and no combined key...
2181
+			//sorry, can't help you
2182
+			throw new EE_Error(
2183
+				sprintf(
2184
+					__(
2185
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2186
+						"event_espresso"
2187
+					), get_class($this)
2188
+				)
2189
+			);
2190
+		}
2191
+		return $ids_to_delete_indexed_by_column;
2192
+	}
2193
+
2194
+
2195
+	/**
2196
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2197
+	 * the corresponding query_part for the query performing the delete.
2198
+	 *
2199
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2200
+	 * @return string
2201
+	 * @throws EE_Error
2202
+	 */
2203
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2204
+		$query_part = '';
2205
+		if (empty($ids_to_delete_indexed_by_column)) {
2206
+			return $query_part;
2207
+		} elseif ($this->has_primary_key_field()) {
2208
+			$query = array();
2209
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2210
+				//make sure we have unique $ids
2211
+				$ids = array_unique($ids);
2212
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2213
+			}
2214
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2215
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2216
+			$ways_to_identify_a_row = array();
2217
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2218
+				$values_for_each_combined_primary_key_for_a_row = array();
2219
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2220
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2221
+				}
2222
+				$ways_to_identify_a_row[] = '('
2223
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2224
+											. ')';
2225
+			}
2226
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2227
+		}
2228
+		return $query_part;
2229
+	}
2230
+
2231
+
2232
+
2233
+	/**
2234
+	 * Gets the model field by the fully qualified name
2235
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2236
+	 * @return EE_Model_Field_Base
2237
+	 */
2238
+	public function get_field_by_column($qualified_column_name)
2239
+	{
2240
+	   foreach($this->field_settings(true) as $field_name => $field_obj){
2241
+		   if($field_obj->get_qualified_column() === $qualified_column_name){
2242
+			   return $field_obj;
2243
+		   }
2244
+	   }
2245
+		throw new EE_Error(
2246
+			sprintf(
2247
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2248
+				$this->get_this_model_name(),
2249
+				$qualified_column_name
2250
+			)
2251
+		);
2252
+	}
2253
+
2254
+
2255
+
2256
+	/**
2257
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2258
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2259
+	 * column
2260
+	 *
2261
+	 * @param array  $query_params   like EEM_Base::get_all's
2262
+	 * @param string $field_to_count field on model to count by (not column name)
2263
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2264
+	 *                               that by the setting $distinct to TRUE;
2265
+	 * @return int
2266
+	 * @throws EE_Error
2267
+	 */
2268
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2269
+	{
2270
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2271
+		if ($field_to_count) {
2272
+			$field_obj = $this->field_settings_for($field_to_count);
2273
+			$column_to_count = $field_obj->get_qualified_column();
2274
+		} elseif ($this->has_primary_key_field()) {
2275
+			$pk_field_obj = $this->get_primary_key_field();
2276
+			$column_to_count = $pk_field_obj->get_qualified_column();
2277
+		} else {
2278
+			//there's no primary key
2279
+			//if we're counting distinct items, and there's no primary key,
2280
+			//we need to list out the columns for distinction;
2281
+			//otherwise we can just use star
2282
+			if ($distinct) {
2283
+				$columns_to_use = array();
2284
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2285
+					$columns_to_use[] = $field_obj->get_qualified_column();
2286
+				}
2287
+				$column_to_count = implode(',', $columns_to_use);
2288
+			} else {
2289
+				$column_to_count = '*';
2290
+			}
2291
+		}
2292
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2293
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2294
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2295
+	}
2296
+
2297
+
2298
+
2299
+	/**
2300
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2301
+	 *
2302
+	 * @param array  $query_params like EEM_Base::get_all
2303
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2304
+	 * @return float
2305
+	 * @throws EE_Error
2306
+	 */
2307
+	public function sum($query_params, $field_to_sum = null)
2308
+	{
2309
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2310
+		if ($field_to_sum) {
2311
+			$field_obj = $this->field_settings_for($field_to_sum);
2312
+		} else {
2313
+			$field_obj = $this->get_primary_key_field();
2314
+		}
2315
+		$column_to_count = $field_obj->get_qualified_column();
2316
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2317
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2318
+		$data_type = $field_obj->get_wpdb_data_type();
2319
+		if ($data_type === '%d' || $data_type === '%s') {
2320
+			return (float)$return_value;
2321
+		}
2322
+		//must be %f
2323
+		return (float)$return_value;
2324
+	}
2325
+
2326
+
2327
+
2328
+	/**
2329
+	 * Just calls the specified method on $wpdb with the given arguments
2330
+	 * Consolidates a little extra error handling code
2331
+	 *
2332
+	 * @param string $wpdb_method
2333
+	 * @param array  $arguments_to_provide
2334
+	 * @throws EE_Error
2335
+	 * @global wpdb  $wpdb
2336
+	 * @return mixed
2337
+	 */
2338
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2339
+	{
2340
+		//if we're in maintenance mode level 2, DON'T run any queries
2341
+		//because level 2 indicates the database needs updating and
2342
+		//is probably out of sync with the code
2343
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2344
+			throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2345
+				"event_espresso")));
2346
+		}
2347
+		/** @type WPDB $wpdb */
2348
+		global $wpdb;
2349
+		if (! method_exists($wpdb, $wpdb_method)) {
2350
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2351
+				'event_espresso'), $wpdb_method));
2352
+		}
2353
+		if (WP_DEBUG) {
2354
+			$old_show_errors_value = $wpdb->show_errors;
2355
+			$wpdb->show_errors(false);
2356
+		}
2357
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2358
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2359
+		if (WP_DEBUG) {
2360
+			$wpdb->show_errors($old_show_errors_value);
2361
+			if (! empty($wpdb->last_error)) {
2362
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2363
+			}
2364
+			if ($result === false) {
2365
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2366
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2367
+			}
2368
+		} elseif ($result === false) {
2369
+			EE_Error::add_error(
2370
+				sprintf(
2371
+					__('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"',
2372
+						'event_espresso'),
2373
+					$wpdb_method,
2374
+					var_export($arguments_to_provide, true),
2375
+					$wpdb->last_error
2376
+				),
2377
+				__FILE__,
2378
+				__FUNCTION__,
2379
+				__LINE__
2380
+			);
2381
+		}
2382
+		return $result;
2383
+	}
2384
+
2385
+
2386
+
2387
+	/**
2388
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2389
+	 * and if there's an error tries to verify the DB is correct. Uses
2390
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2391
+	 * we should try to fix the EE core db, the addons, or just give up
2392
+	 *
2393
+	 * @param string $wpdb_method
2394
+	 * @param array  $arguments_to_provide
2395
+	 * @return mixed
2396
+	 */
2397
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2398
+	{
2399
+		/** @type WPDB $wpdb */
2400
+		global $wpdb;
2401
+		$wpdb->last_error = null;
2402
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2403
+		// was there an error running the query? but we don't care on new activations
2404
+		// (we're going to setup the DB anyway on new activations)
2405
+		if (($result === false || ! empty($wpdb->last_error))
2406
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2407
+		) {
2408
+			switch (EEM_Base::$_db_verification_level) {
2409
+				case EEM_Base::db_verified_none :
2410
+					// let's double-check core's DB
2411
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2412
+					break;
2413
+				case EEM_Base::db_verified_core :
2414
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2415
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2416
+					break;
2417
+				case EEM_Base::db_verified_addons :
2418
+					// ummmm... you in trouble
2419
+					return $result;
2420
+					break;
2421
+			}
2422
+			if (! empty($error_message)) {
2423
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2424
+				trigger_error($error_message);
2425
+			}
2426
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2427
+		}
2428
+		return $result;
2429
+	}
2430
+
2431
+
2432
+
2433
+	/**
2434
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2435
+	 * EEM_Base::$_db_verification_level
2436
+	 *
2437
+	 * @param string $wpdb_method
2438
+	 * @param array  $arguments_to_provide
2439
+	 * @return string
2440
+	 */
2441
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2442
+	{
2443
+		/** @type WPDB $wpdb */
2444
+		global $wpdb;
2445
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2446
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2447
+		$error_message = sprintf(
2448
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2449
+				'event_espresso'),
2450
+			$wpdb->last_error,
2451
+			$wpdb_method,
2452
+			wp_json_encode($arguments_to_provide)
2453
+		);
2454
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2455
+		return $error_message;
2456
+	}
2457
+
2458
+
2459
+
2460
+	/**
2461
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2462
+	 * EEM_Base::$_db_verification_level
2463
+	 *
2464
+	 * @param $wpdb_method
2465
+	 * @param $arguments_to_provide
2466
+	 * @return string
2467
+	 */
2468
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2469
+	{
2470
+		/** @type WPDB $wpdb */
2471
+		global $wpdb;
2472
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2473
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2474
+		$error_message = sprintf(
2475
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2476
+				'event_espresso'),
2477
+			$wpdb->last_error,
2478
+			$wpdb_method,
2479
+			wp_json_encode($arguments_to_provide)
2480
+		);
2481
+		EE_System::instance()->initialize_addons();
2482
+		return $error_message;
2483
+	}
2484
+
2485
+
2486
+
2487
+	/**
2488
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2489
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2490
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2491
+	 * ..."
2492
+	 *
2493
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2494
+	 * @return string
2495
+	 */
2496
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2497
+	{
2498
+		return " FROM " . $model_query_info->get_full_join_sql() .
2499
+			   $model_query_info->get_where_sql() .
2500
+			   $model_query_info->get_group_by_sql() .
2501
+			   $model_query_info->get_having_sql() .
2502
+			   $model_query_info->get_order_by_sql() .
2503
+			   $model_query_info->get_limit_sql();
2504
+	}
2505
+
2506
+
2507
+
2508
+	/**
2509
+	 * Set to easily debug the next X queries ran from this model.
2510
+	 *
2511
+	 * @param int $count
2512
+	 */
2513
+	public function show_next_x_db_queries($count = 1)
2514
+	{
2515
+		$this->_show_next_x_db_queries = $count;
2516
+	}
2517
+
2518
+
2519
+
2520
+	/**
2521
+	 * @param $sql_query
2522
+	 */
2523
+	public function show_db_query_if_previously_requested($sql_query)
2524
+	{
2525
+		if ($this->_show_next_x_db_queries > 0) {
2526
+			echo $sql_query;
2527
+			$this->_show_next_x_db_queries--;
2528
+		}
2529
+	}
2530
+
2531
+
2532
+
2533
+	/**
2534
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2535
+	 * There are the 3 cases:
2536
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2537
+	 * $otherModelObject has no ID, it is first saved.
2538
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2539
+	 * has no ID, it is first saved.
2540
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2541
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2542
+	 * join table
2543
+	 *
2544
+	 * @param        EE_Base_Class                     /int $thisModelObject
2545
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2546
+	 * @param string $relationName                     , key in EEM_Base::_relations
2547
+	 *                                                 an attendee to a group, you also want to specify which role they
2548
+	 *                                                 will have in that group. So you would use this parameter to
2549
+	 *                                                 specify array('role-column-name'=>'role-id')
2550
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2551
+	 *                                                 to for relation to methods that allow you to further specify
2552
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2553
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2554
+	 *                                                 because these will be inserted in any new rows created as well.
2555
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2556
+	 * @throws EE_Error
2557
+	 */
2558
+	public function add_relationship_to(
2559
+		$id_or_obj,
2560
+		$other_model_id_or_obj,
2561
+		$relationName,
2562
+		$extra_join_model_fields_n_values = array()
2563
+	) {
2564
+		$relation_obj = $this->related_settings_for($relationName);
2565
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2566
+	}
2567
+
2568
+
2569
+
2570
+	/**
2571
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2572
+	 * There are the 3 cases:
2573
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2574
+	 * error
2575
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2576
+	 * an error
2577
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2578
+	 *
2579
+	 * @param        EE_Base_Class /int $id_or_obj
2580
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2581
+	 * @param string $relationName key in EEM_Base::_relations
2582
+	 * @return boolean of success
2583
+	 * @throws EE_Error
2584
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2585
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2586
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2587
+	 *                             because these will be inserted in any new rows created as well.
2588
+	 */
2589
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2590
+	{
2591
+		$relation_obj = $this->related_settings_for($relationName);
2592
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2593
+	}
2594
+
2595
+
2596
+
2597
+	/**
2598
+	 * @param mixed           $id_or_obj
2599
+	 * @param string          $relationName
2600
+	 * @param array           $where_query_params
2601
+	 * @param EE_Base_Class[] objects to which relations were removed
2602
+	 * @return \EE_Base_Class[]
2603
+	 * @throws EE_Error
2604
+	 */
2605
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2606
+	{
2607
+		$relation_obj = $this->related_settings_for($relationName);
2608
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2609
+	}
2610
+
2611
+
2612
+
2613
+	/**
2614
+	 * Gets all the related items of the specified $model_name, using $query_params.
2615
+	 * Note: by default, we remove the "default query params"
2616
+	 * because we want to get even deleted items etc.
2617
+	 *
2618
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2619
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2620
+	 * @param array  $query_params like EEM_Base::get_all
2621
+	 * @return EE_Base_Class[]
2622
+	 * @throws EE_Error
2623
+	 */
2624
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2625
+	{
2626
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2627
+		$relation_settings = $this->related_settings_for($model_name);
2628
+		return $relation_settings->get_all_related($model_obj, $query_params);
2629
+	}
2630
+
2631
+
2632
+
2633
+	/**
2634
+	 * Deletes all the model objects across the relation indicated by $model_name
2635
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2636
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2637
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2638
+	 *
2639
+	 * @param EE_Base_Class|int|string $id_or_obj
2640
+	 * @param string                   $model_name
2641
+	 * @param array                    $query_params
2642
+	 * @return int how many deleted
2643
+	 * @throws EE_Error
2644
+	 */
2645
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2646
+	{
2647
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2648
+		$relation_settings = $this->related_settings_for($model_name);
2649
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2650
+	}
2651
+
2652
+
2653
+
2654
+	/**
2655
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2656
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2657
+	 * the model objects can't be hard deleted because of blocking related model objects,
2658
+	 * just does a soft-delete on them instead.
2659
+	 *
2660
+	 * @param EE_Base_Class|int|string $id_or_obj
2661
+	 * @param string                   $model_name
2662
+	 * @param array                    $query_params
2663
+	 * @return int how many deleted
2664
+	 * @throws EE_Error
2665
+	 */
2666
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2667
+	{
2668
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2669
+		$relation_settings = $this->related_settings_for($model_name);
2670
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2671
+	}
2672
+
2673
+
2674
+
2675
+	/**
2676
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2677
+	 * unless otherwise specified in the $query_params
2678
+	 *
2679
+	 * @param        int             /EE_Base_Class $id_or_obj
2680
+	 * @param string $model_name     like 'Event', or 'Registration'
2681
+	 * @param array  $query_params   like EEM_Base::get_all's
2682
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2683
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2684
+	 *                               that by the setting $distinct to TRUE;
2685
+	 * @return int
2686
+	 * @throws EE_Error
2687
+	 */
2688
+	public function count_related(
2689
+		$id_or_obj,
2690
+		$model_name,
2691
+		$query_params = array(),
2692
+		$field_to_count = null,
2693
+		$distinct = false
2694
+	) {
2695
+		$related_model = $this->get_related_model_obj($model_name);
2696
+		//we're just going to use the query params on the related model's normal get_all query,
2697
+		//except add a condition to say to match the current mod
2698
+		if (! isset($query_params['default_where_conditions'])) {
2699
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2700
+		}
2701
+		$this_model_name = $this->get_this_model_name();
2702
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2703
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2704
+		return $related_model->count($query_params, $field_to_count, $distinct);
2705
+	}
2706
+
2707
+
2708
+
2709
+	/**
2710
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2711
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2712
+	 *
2713
+	 * @param        int           /EE_Base_Class $id_or_obj
2714
+	 * @param string $model_name   like 'Event', or 'Registration'
2715
+	 * @param array  $query_params like EEM_Base::get_all's
2716
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2717
+	 * @return float
2718
+	 * @throws EE_Error
2719
+	 */
2720
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2721
+	{
2722
+		$related_model = $this->get_related_model_obj($model_name);
2723
+		if (! is_array($query_params)) {
2724
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2725
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2726
+					gettype($query_params)), '4.6.0');
2727
+			$query_params = array();
2728
+		}
2729
+		//we're just going to use the query params on the related model's normal get_all query,
2730
+		//except add a condition to say to match the current mod
2731
+		if (! isset($query_params['default_where_conditions'])) {
2732
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2733
+		}
2734
+		$this_model_name = $this->get_this_model_name();
2735
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2736
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2737
+		return $related_model->sum($query_params, $field_to_sum);
2738
+	}
2739
+
2740
+
2741
+
2742
+	/**
2743
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2744
+	 * $modelObject
2745
+	 *
2746
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2747
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2748
+	 * @param array               $query_params     like EEM_Base::get_all's
2749
+	 * @return EE_Base_Class
2750
+	 * @throws EE_Error
2751
+	 */
2752
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2753
+	{
2754
+		$query_params['limit'] = 1;
2755
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2756
+		if ($results) {
2757
+			return array_shift($results);
2758
+		}
2759
+		return null;
2760
+	}
2761
+
2762
+
2763
+
2764
+	/**
2765
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2766
+	 *
2767
+	 * @return string
2768
+	 */
2769
+	public function get_this_model_name()
2770
+	{
2771
+		return str_replace("EEM_", "", get_class($this));
2772
+	}
2773
+
2774
+
2775
+
2776
+	/**
2777
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2778
+	 *
2779
+	 * @return EE_Any_Foreign_Model_Name_Field
2780
+	 * @throws EE_Error
2781
+	 */
2782
+	public function get_field_containing_related_model_name()
2783
+	{
2784
+		foreach ($this->field_settings(true) as $field) {
2785
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2786
+				$field_with_model_name = $field;
2787
+			}
2788
+		}
2789
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2790
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2791
+				$this->get_this_model_name()));
2792
+		}
2793
+		return $field_with_model_name;
2794
+	}
2795
+
2796
+
2797
+
2798
+	/**
2799
+	 * Inserts a new entry into the database, for each table.
2800
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2801
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2802
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2803
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2804
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2805
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2806
+	 *
2807
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2808
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2809
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2810
+	 *                              of EEM_Base)
2811
+	 * @return int new primary key on main table that got inserted
2812
+	 * @throws EE_Error
2813
+	 */
2814
+	public function insert($field_n_values)
2815
+	{
2816
+		/**
2817
+		 * Filters the fields and their values before inserting an item using the models
2818
+		 *
2819
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2820
+		 * @param EEM_Base $model           the model used
2821
+		 */
2822
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2823
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2824
+			$main_table = $this->_get_main_table();
2825
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2826
+			if ($new_id !== false) {
2827
+				foreach ($this->_get_other_tables() as $other_table) {
2828
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2829
+				}
2830
+			}
2831
+			/**
2832
+			 * Done just after attempting to insert a new model object
2833
+			 *
2834
+			 * @param EEM_Base   $model           used
2835
+			 * @param array      $fields_n_values fields and their values
2836
+			 * @param int|string the              ID of the newly-inserted model object
2837
+			 */
2838
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2839
+			return $new_id;
2840
+		}
2841
+		return false;
2842
+	}
2843
+
2844
+
2845
+
2846
+	/**
2847
+	 * Checks that the result would satisfy the unique indexes on this model
2848
+	 *
2849
+	 * @param array  $field_n_values
2850
+	 * @param string $action
2851
+	 * @return boolean
2852
+	 * @throws EE_Error
2853
+	 */
2854
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2855
+	{
2856
+		foreach ($this->unique_indexes() as $index_name => $index) {
2857
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2858
+			if ($this->exists(array($uniqueness_where_params))) {
2859
+				EE_Error::add_error(
2860
+					sprintf(
2861
+						__(
2862
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2863
+							"event_espresso"
2864
+						),
2865
+						$action,
2866
+						$this->_get_class_name(),
2867
+						$index_name,
2868
+						implode(",", $index->field_names()),
2869
+						http_build_query($uniqueness_where_params)
2870
+					),
2871
+					__FILE__,
2872
+					__FUNCTION__,
2873
+					__LINE__
2874
+				);
2875
+				return false;
2876
+			}
2877
+		}
2878
+		return true;
2879
+	}
2880
+
2881
+
2882
+
2883
+	/**
2884
+	 * Checks the database for an item that conflicts (ie, if this item were
2885
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2886
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2887
+	 * can be either an EE_Base_Class or an array of fields n values
2888
+	 *
2889
+	 * @param EE_Base_Class|array $obj_or_fields_array
2890
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2891
+	 *                                                 when looking for conflicts
2892
+	 *                                                 (ie, if false, we ignore the model object's primary key
2893
+	 *                                                 when finding "conflicts". If true, it's also considered).
2894
+	 *                                                 Only works for INT primary key,
2895
+	 *                                                 STRING primary keys cannot be ignored
2896
+	 * @throws EE_Error
2897
+	 * @return EE_Base_Class|array
2898
+	 */
2899
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2900
+	{
2901
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2902
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2903
+		} elseif (is_array($obj_or_fields_array)) {
2904
+			$fields_n_values = $obj_or_fields_array;
2905
+		} else {
2906
+			throw new EE_Error(
2907
+				sprintf(
2908
+					__(
2909
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2910
+						"event_espresso"
2911
+					),
2912
+					get_class($this),
2913
+					$obj_or_fields_array
2914
+				)
2915
+			);
2916
+		}
2917
+		$query_params = array();
2918
+		if ($this->has_primary_key_field()
2919
+			&& ($include_primary_key
2920
+				|| $this->get_primary_key_field()
2921
+				   instanceof
2922
+				   EE_Primary_Key_String_Field)
2923
+			&& isset($fields_n_values[$this->primary_key_name()])
2924
+		) {
2925
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2926
+		}
2927
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2928
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2929
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2930
+		}
2931
+		//if there is nothing to base this search on, then we shouldn't find anything
2932
+		if (empty($query_params)) {
2933
+			return array();
2934
+		}
2935
+		return $this->get_one($query_params);
2936
+	}
2937
+
2938
+
2939
+
2940
+	/**
2941
+	 * Like count, but is optimized and returns a boolean instead of an int
2942
+	 *
2943
+	 * @param array $query_params
2944
+	 * @return boolean
2945
+	 * @throws EE_Error
2946
+	 */
2947
+	public function exists($query_params)
2948
+	{
2949
+		$query_params['limit'] = 1;
2950
+		return $this->count($query_params) > 0;
2951
+	}
2952
+
2953
+
2954
+
2955
+	/**
2956
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2957
+	 *
2958
+	 * @param int|string $id
2959
+	 * @return boolean
2960
+	 * @throws EE_Error
2961
+	 */
2962
+	public function exists_by_ID($id)
2963
+	{
2964
+		return $this->exists(
2965
+			array(
2966
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2967
+				array(
2968
+					$this->primary_key_name() => $id,
2969
+				),
2970
+			)
2971
+		);
2972
+	}
2973
+
2974
+
2975
+
2976
+	/**
2977
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2978
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2979
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2980
+	 * on the main table)
2981
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2982
+	 * cases where we want to call it directly rather than via insert().
2983
+	 *
2984
+	 * @access   protected
2985
+	 * @param EE_Table_Base $table
2986
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2987
+	 *                                       float
2988
+	 * @param int           $new_id          for now we assume only int keys
2989
+	 * @throws EE_Error
2990
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2991
+	 * @return int ID of new row inserted, or FALSE on failure
2992
+	 */
2993
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2994
+	{
2995
+		global $wpdb;
2996
+		$insertion_col_n_values = array();
2997
+		$format_for_insertion = array();
2998
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2999
+		foreach ($fields_on_table as $field_name => $field_obj) {
3000
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3001
+			if ($field_obj->is_auto_increment()) {
3002
+				continue;
3003
+			}
3004
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3005
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
3006
+			if ($prepared_value !== null) {
3007
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3008
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
3009
+			}
3010
+		}
3011
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3012
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
3013
+			//so add the fk to the main table as a column
3014
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3015
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3016
+		}
3017
+		//insert the new entry
3018
+		$result = $this->_do_wpdb_query('insert',
3019
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
3020
+		if ($result === false) {
3021
+			return false;
3022
+		}
3023
+		//ok, now what do we return for the ID of the newly-inserted thing?
3024
+		if ($this->has_primary_key_field()) {
3025
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3026
+				return $wpdb->insert_id;
3027
+			}
3028
+			//it's not an auto-increment primary key, so
3029
+			//it must have been supplied
3030
+			return $fields_n_values[$this->get_primary_key_field()->get_name()];
3031
+		}
3032
+		//we can't return a  primary key because there is none. instead return
3033
+		//a unique string indicating this model
3034
+		return $this->get_index_primary_key_string($fields_n_values);
3035
+	}
3036
+
3037
+
3038
+
3039
+	/**
3040
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3041
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3042
+	 * and there is no default, we pass it along. WPDB will take care of it)
3043
+	 *
3044
+	 * @param EE_Model_Field_Base $field_obj
3045
+	 * @param array               $fields_n_values
3046
+	 * @return mixed string|int|float depending on what the table column will be expecting
3047
+	 * @throws EE_Error
3048
+	 */
3049
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3050
+	{
3051
+		//if this field doesn't allow nullable, don't allow it
3052
+		if (
3053
+			! $field_obj->is_nullable()
3054
+			&& (
3055
+				! isset($fields_n_values[$field_obj->get_name()])
3056
+				|| $fields_n_values[$field_obj->get_name()] === null
3057
+			)
3058
+		) {
3059
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3060
+		}
3061
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3062
+			? $fields_n_values[$field_obj->get_name()]
3063
+			: null;
3064
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3065
+	}
3066
+
3067
+
3068
+
3069
+	/**
3070
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3071
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3072
+	 * the field's prepare_for_set() method.
3073
+	 *
3074
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3075
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3076
+	 *                                   top of file)
3077
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3078
+	 *                                   $value is a custom selection
3079
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3080
+	 */
3081
+	private function _prepare_value_for_use_in_db($value, $field)
3082
+	{
3083
+		if ($field && $field instanceof EE_Model_Field_Base) {
3084
+			switch ($this->_values_already_prepared_by_model_object) {
3085
+				/** @noinspection PhpMissingBreakStatementInspection */
3086
+				case self::not_prepared_by_model_object:
3087
+					$value = $field->prepare_for_set($value);
3088
+				//purposefully left out "return"
3089
+				case self::prepared_by_model_object:
3090
+					/** @noinspection SuspiciousAssignmentsInspection */
3091
+					$value = $field->prepare_for_use_in_db($value);
3092
+				case self::prepared_for_use_in_db:
3093
+					//leave the value alone
3094
+			}
3095
+			return $value;
3096
+		}
3097
+		return $value;
3098
+	}
3099
+
3100
+
3101
+
3102
+	/**
3103
+	 * Returns the main table on this model
3104
+	 *
3105
+	 * @return EE_Primary_Table
3106
+	 * @throws EE_Error
3107
+	 */
3108
+	protected function _get_main_table()
3109
+	{
3110
+		foreach ($this->_tables as $table) {
3111
+			if ($table instanceof EE_Primary_Table) {
3112
+				return $table;
3113
+			}
3114
+		}
3115
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3116
+			'event_espresso'), get_class($this)));
3117
+	}
3118
+
3119
+
3120
+
3121
+	/**
3122
+	 * table
3123
+	 * returns EE_Primary_Table table name
3124
+	 *
3125
+	 * @return string
3126
+	 * @throws EE_Error
3127
+	 */
3128
+	public function table()
3129
+	{
3130
+		return $this->_get_main_table()->get_table_name();
3131
+	}
3132
+
3133
+
3134
+
3135
+	/**
3136
+	 * table
3137
+	 * returns first EE_Secondary_Table table name
3138
+	 *
3139
+	 * @return string
3140
+	 */
3141
+	public function second_table()
3142
+	{
3143
+		// grab second table from tables array
3144
+		$second_table = end($this->_tables);
3145
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3146
+	}
3147
+
3148
+
3149
+
3150
+	/**
3151
+	 * get_table_obj_by_alias
3152
+	 * returns table name given it's alias
3153
+	 *
3154
+	 * @param string $table_alias
3155
+	 * @return EE_Primary_Table | EE_Secondary_Table
3156
+	 */
3157
+	public function get_table_obj_by_alias($table_alias = '')
3158
+	{
3159
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3160
+	}
3161
+
3162
+
3163
+
3164
+	/**
3165
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3166
+	 *
3167
+	 * @return EE_Secondary_Table[]
3168
+	 */
3169
+	protected function _get_other_tables()
3170
+	{
3171
+		$other_tables = array();
3172
+		foreach ($this->_tables as $table_alias => $table) {
3173
+			if ($table instanceof EE_Secondary_Table) {
3174
+				$other_tables[$table_alias] = $table;
3175
+			}
3176
+		}
3177
+		return $other_tables;
3178
+	}
3179
+
3180
+
3181
+
3182
+	/**
3183
+	 * Finds all the fields that correspond to the given table
3184
+	 *
3185
+	 * @param string $table_alias , array key in EEM_Base::_tables
3186
+	 * @return EE_Model_Field_Base[]
3187
+	 */
3188
+	public function _get_fields_for_table($table_alias)
3189
+	{
3190
+		return $this->_fields[$table_alias];
3191
+	}
3192
+
3193
+
3194
+
3195
+	/**
3196
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3197
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3198
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3199
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3200
+	 * related Registration, Transaction, and Payment models.
3201
+	 *
3202
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3203
+	 * @return EE_Model_Query_Info_Carrier
3204
+	 * @throws EE_Error
3205
+	 */
3206
+	public function _extract_related_models_from_query($query_params)
3207
+	{
3208
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3209
+		if (array_key_exists(0, $query_params)) {
3210
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3211
+		}
3212
+		if (array_key_exists('group_by', $query_params)) {
3213
+			if (is_array($query_params['group_by'])) {
3214
+				$this->_extract_related_models_from_sub_params_array_values(
3215
+					$query_params['group_by'],
3216
+					$query_info_carrier,
3217
+					'group_by'
3218
+				);
3219
+			} elseif (! empty ($query_params['group_by'])) {
3220
+				$this->_extract_related_model_info_from_query_param(
3221
+					$query_params['group_by'],
3222
+					$query_info_carrier,
3223
+					'group_by'
3224
+				);
3225
+			}
3226
+		}
3227
+		if (array_key_exists('having', $query_params)) {
3228
+			$this->_extract_related_models_from_sub_params_array_keys(
3229
+				$query_params[0],
3230
+				$query_info_carrier,
3231
+				'having'
3232
+			);
3233
+		}
3234
+		if (array_key_exists('order_by', $query_params)) {
3235
+			if (is_array($query_params['order_by'])) {
3236
+				$this->_extract_related_models_from_sub_params_array_keys(
3237
+					$query_params['order_by'],
3238
+					$query_info_carrier,
3239
+					'order_by'
3240
+				);
3241
+			} elseif (! empty($query_params['order_by'])) {
3242
+				$this->_extract_related_model_info_from_query_param(
3243
+					$query_params['order_by'],
3244
+					$query_info_carrier,
3245
+					'order_by'
3246
+				);
3247
+			}
3248
+		}
3249
+		if (array_key_exists('force_join', $query_params)) {
3250
+			$this->_extract_related_models_from_sub_params_array_values(
3251
+				$query_params['force_join'],
3252
+				$query_info_carrier,
3253
+				'force_join'
3254
+			);
3255
+		}
3256
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3257
+		return $query_info_carrier;
3258
+	}
3259
+
3260
+
3261
+
3262
+	/**
3263
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3264
+	 *
3265
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3266
+	 *                                                      $query_params['having']
3267
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3268
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3269
+	 * @throws EE_Error
3270
+	 * @return \EE_Model_Query_Info_Carrier
3271
+	 */
3272
+	private function _extract_related_models_from_sub_params_array_keys(
3273
+		$sub_query_params,
3274
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3275
+		$query_param_type
3276
+	) {
3277
+		if (! empty($sub_query_params)) {
3278
+			$sub_query_params = (array)$sub_query_params;
3279
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3280
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3281
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3282
+					$query_param_type);
3283
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3284
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3285
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3286
+				//of array('Registration.TXN_ID'=>23)
3287
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3288
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3289
+					if (! is_array($possibly_array_of_params)) {
3290
+						throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3291
+							"event_espresso"),
3292
+							$param, $possibly_array_of_params));
3293
+					}
3294
+					$this->_extract_related_models_from_sub_params_array_keys(
3295
+						$possibly_array_of_params,
3296
+						$model_query_info_carrier, $query_param_type
3297
+					);
3298
+				} elseif ($query_param_type === 0 //ie WHERE
3299
+						  && is_array($possibly_array_of_params)
3300
+						  && isset($possibly_array_of_params[2])
3301
+						  && $possibly_array_of_params[2] == true
3302
+				) {
3303
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3304
+					//indicating that $possible_array_of_params[1] is actually a field name,
3305
+					//from which we should extract query parameters!
3306
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3307
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3308
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3309
+					}
3310
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3311
+						$model_query_info_carrier, $query_param_type);
3312
+				}
3313
+			}
3314
+		}
3315
+		return $model_query_info_carrier;
3316
+	}
3317
+
3318
+
3319
+
3320
+	/**
3321
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3322
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3323
+	 *
3324
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3325
+	 *                                                      $query_params['having']
3326
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3327
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3328
+	 * @throws EE_Error
3329
+	 * @return \EE_Model_Query_Info_Carrier
3330
+	 */
3331
+	private function _extract_related_models_from_sub_params_array_values(
3332
+		$sub_query_params,
3333
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3334
+		$query_param_type
3335
+	) {
3336
+		if (! empty($sub_query_params)) {
3337
+			if (! is_array($sub_query_params)) {
3338
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3339
+					$sub_query_params));
3340
+			}
3341
+			foreach ($sub_query_params as $param) {
3342
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3343
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3344
+					$query_param_type);
3345
+			}
3346
+		}
3347
+		return $model_query_info_carrier;
3348
+	}
3349
+
3350
+
3351
+
3352
+	/**
3353
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3354
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3355
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3356
+	 * but use them in a different order. Eg, we need to know what models we are querying
3357
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3358
+	 * other models before we can finalize the where clause SQL.
3359
+	 *
3360
+	 * @param array $query_params
3361
+	 * @throws EE_Error
3362
+	 * @return EE_Model_Query_Info_Carrier
3363
+	 */
3364
+	public function _create_model_query_info_carrier($query_params)
3365
+	{
3366
+		if (! is_array($query_params)) {
3367
+			EE_Error::doing_it_wrong(
3368
+				'EEM_Base::_create_model_query_info_carrier',
3369
+				sprintf(
3370
+					__(
3371
+						'$query_params should be an array, you passed a variable of type %s',
3372
+						'event_espresso'
3373
+					),
3374
+					gettype($query_params)
3375
+				),
3376
+				'4.6.0'
3377
+			);
3378
+			$query_params = array();
3379
+		}
3380
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3381
+		//first check if we should alter the query to account for caps or not
3382
+		//because the caps might require us to do extra joins
3383
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3384
+			$query_params[0] = $where_query_params = array_replace_recursive(
3385
+				$where_query_params,
3386
+				$this->caps_where_conditions(
3387
+					$query_params['caps']
3388
+				)
3389
+			);
3390
+		}
3391
+		$query_object = $this->_extract_related_models_from_query($query_params);
3392
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3393
+		foreach ($where_query_params as $key => $value) {
3394
+			if (is_int($key)) {
3395
+				throw new EE_Error(
3396
+					sprintf(
3397
+						__(
3398
+							"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.",
3399
+							"event_espresso"
3400
+						),
3401
+						$key,
3402
+						var_export($value, true),
3403
+						var_export($query_params, true),
3404
+						get_class($this)
3405
+					)
3406
+				);
3407
+			}
3408
+		}
3409
+		if (
3410
+			array_key_exists('default_where_conditions', $query_params)
3411
+			&& ! empty($query_params['default_where_conditions'])
3412
+		) {
3413
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3414
+		} else {
3415
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3416
+		}
3417
+		$where_query_params = array_merge(
3418
+			$this->_get_default_where_conditions_for_models_in_query(
3419
+				$query_object,
3420
+				$use_default_where_conditions,
3421
+				$where_query_params
3422
+			),
3423
+			$where_query_params
3424
+		);
3425
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3426
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3427
+		// So we need to setup a subquery and use that for the main join.
3428
+		// Note for now this only works on the primary table for the model.
3429
+		// So for instance, you could set the limit array like this:
3430
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3431
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3432
+			$query_object->set_main_model_join_sql(
3433
+				$this->_construct_limit_join_select(
3434
+					$query_params['on_join_limit'][0],
3435
+					$query_params['on_join_limit'][1]
3436
+				)
3437
+			);
3438
+		}
3439
+		//set limit
3440
+		if (array_key_exists('limit', $query_params)) {
3441
+			if (is_array($query_params['limit'])) {
3442
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3443
+					$e = sprintf(
3444
+						__(
3445
+							"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)",
3446
+							"event_espresso"
3447
+						),
3448
+						http_build_query($query_params['limit'])
3449
+					);
3450
+					throw new EE_Error($e . "|" . $e);
3451
+				}
3452
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3453
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3454
+			} elseif (! empty ($query_params['limit'])) {
3455
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3456
+			}
3457
+		}
3458
+		//set order by
3459
+		if (array_key_exists('order_by', $query_params)) {
3460
+			if (is_array($query_params['order_by'])) {
3461
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3462
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3463
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3464
+				if (array_key_exists('order', $query_params)) {
3465
+					throw new EE_Error(
3466
+						sprintf(
3467
+							__(
3468
+								"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 ",
3469
+								"event_espresso"
3470
+							),
3471
+							get_class($this),
3472
+							implode(", ", array_keys($query_params['order_by'])),
3473
+							implode(", ", $query_params['order_by']),
3474
+							$query_params['order']
3475
+						)
3476
+					);
3477
+				}
3478
+				$this->_extract_related_models_from_sub_params_array_keys(
3479
+					$query_params['order_by'],
3480
+					$query_object,
3481
+					'order_by'
3482
+				);
3483
+				//assume it's an array of fields to order by
3484
+				$order_array = array();
3485
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3486
+					$order = $this->_extract_order($order);
3487
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3488
+				}
3489
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3490
+			} elseif (! empty ($query_params['order_by'])) {
3491
+				$this->_extract_related_model_info_from_query_param(
3492
+					$query_params['order_by'],
3493
+					$query_object,
3494
+					'order',
3495
+					$query_params['order_by']
3496
+				);
3497
+				$order = isset($query_params['order'])
3498
+					? $this->_extract_order($query_params['order'])
3499
+					: 'DESC';
3500
+				$query_object->set_order_by_sql(
3501
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3502
+				);
3503
+			}
3504
+		}
3505
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3506
+		if (! array_key_exists('order_by', $query_params)
3507
+			&& array_key_exists('order', $query_params)
3508
+			&& ! empty($query_params['order'])
3509
+		) {
3510
+			$pk_field = $this->get_primary_key_field();
3511
+			$order = $this->_extract_order($query_params['order']);
3512
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3513
+		}
3514
+		//set group by
3515
+		if (array_key_exists('group_by', $query_params)) {
3516
+			if (is_array($query_params['group_by'])) {
3517
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3518
+				$group_by_array = array();
3519
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3520
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3521
+				}
3522
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3523
+			} elseif (! empty ($query_params['group_by'])) {
3524
+				$query_object->set_group_by_sql(
3525
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3526
+				);
3527
+			}
3528
+		}
3529
+		//set having
3530
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3531
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3532
+		}
3533
+		//now, just verify they didn't pass anything wack
3534
+		foreach ($query_params as $query_key => $query_value) {
3535
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3536
+				throw new EE_Error(
3537
+					sprintf(
3538
+						__(
3539
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3540
+							'event_espresso'
3541
+						),
3542
+						$query_key,
3543
+						get_class($this),
3544
+						//						print_r( $this->_allowed_query_params, TRUE )
3545
+						implode(',', $this->_allowed_query_params)
3546
+					)
3547
+				);
3548
+			}
3549
+		}
3550
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3551
+		if (empty($main_model_join_sql)) {
3552
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3553
+		}
3554
+		return $query_object;
3555
+	}
3556
+
3557
+
3558
+
3559
+	/**
3560
+	 * Gets the where conditions that should be imposed on the query based on the
3561
+	 * context (eg reading frontend, backend, edit or delete).
3562
+	 *
3563
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3564
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3565
+	 * @throws EE_Error
3566
+	 */
3567
+	public function caps_where_conditions($context = self::caps_read)
3568
+	{
3569
+		EEM_Base::verify_is_valid_cap_context($context);
3570
+		$cap_where_conditions = array();
3571
+		$cap_restrictions = $this->caps_missing($context);
3572
+		/**
3573
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3574
+		 */
3575
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3576
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3577
+				$restriction_if_no_cap->get_default_where_conditions());
3578
+		}
3579
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3580
+			$cap_restrictions);
3581
+	}
3582
+
3583
+
3584
+
3585
+	/**
3586
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3587
+	 * otherwise throws an exception
3588
+	 *
3589
+	 * @param string $should_be_order_string
3590
+	 * @return string either ASC, asc, DESC or desc
3591
+	 * @throws EE_Error
3592
+	 */
3593
+	private function _extract_order($should_be_order_string)
3594
+	{
3595
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3596
+			return $should_be_order_string;
3597
+		}
3598
+		throw new EE_Error(
3599
+			sprintf(
3600
+				__(
3601
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3602
+					"event_espresso"
3603
+				), get_class($this), $should_be_order_string
3604
+			)
3605
+		);
3606
+	}
3607
+
3608
+
3609
+
3610
+	/**
3611
+	 * Looks at all the models which are included in this query, and asks each
3612
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3613
+	 * so they can be merged
3614
+	 *
3615
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3616
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3617
+	 *                                                                  'none' means NO default where conditions will
3618
+	 *                                                                  be used AT ALL during this query.
3619
+	 *                                                                  'other_models_only' means default where
3620
+	 *                                                                  conditions from other models will be used, but
3621
+	 *                                                                  not for this primary model. 'all', the default,
3622
+	 *                                                                  means default where conditions will apply as
3623
+	 *                                                                  normal
3624
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3625
+	 * @throws EE_Error
3626
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3627
+	 */
3628
+	private function _get_default_where_conditions_for_models_in_query(
3629
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3630
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3631
+		$where_query_params = array()
3632
+	) {
3633
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3634
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3635
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3636
+				"event_espresso"), $use_default_where_conditions,
3637
+				implode(", ", $allowed_used_default_where_conditions_values)));
3638
+		}
3639
+		$universal_query_params = array();
3640
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3641
+			$universal_query_params = $this->_get_default_where_conditions();
3642
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3643
+			$universal_query_params = $this->_get_minimum_where_conditions();
3644
+		}
3645
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3646
+			$related_model = $this->get_related_model_obj($model_name);
3647
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3648
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3649
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3650
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3651
+			} else {
3652
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3653
+				continue;
3654
+			}
3655
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3656
+				$related_model_universal_where_params,
3657
+				$where_query_params,
3658
+				$related_model,
3659
+				$model_relation_path
3660
+			);
3661
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3662
+				$universal_query_params,
3663
+				$overrides
3664
+			);
3665
+		}
3666
+		return $universal_query_params;
3667
+	}
3668
+
3669
+
3670
+
3671
+	/**
3672
+	 * Determines whether or not we should use default where conditions for the model in question
3673
+	 * (this model, or other related models).
3674
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3675
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3676
+	 * We should use default where conditions on related models when they requested to use default where conditions
3677
+	 * on all models, or specifically just on other related models
3678
+	 * @param      $default_where_conditions_value
3679
+	 * @param bool $for_this_model false means this is for OTHER related models
3680
+	 * @return bool
3681
+	 */
3682
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3683
+	{
3684
+		return (
3685
+				   $for_this_model
3686
+				   && in_array(
3687
+					   $default_where_conditions_value,
3688
+					   array(
3689
+						   EEM_Base::default_where_conditions_all,
3690
+						   EEM_Base::default_where_conditions_this_only,
3691
+						   EEM_Base::default_where_conditions_minimum_others,
3692
+					   ),
3693
+					   true
3694
+				   )
3695
+			   )
3696
+			   || (
3697
+				   ! $for_this_model
3698
+				   && in_array(
3699
+					   $default_where_conditions_value,
3700
+					   array(
3701
+						   EEM_Base::default_where_conditions_all,
3702
+						   EEM_Base::default_where_conditions_others_only,
3703
+					   ),
3704
+					   true
3705
+				   )
3706
+			   );
3707
+	}
3708
+
3709
+	/**
3710
+	 * Determines whether or not we should use default minimum conditions for the model in question
3711
+	 * (this model, or other related models).
3712
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3713
+	 * where conditions.
3714
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3715
+	 * on this model or others
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_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3721
+	{
3722
+		return (
3723
+				   $for_this_model
3724
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3725
+			   )
3726
+			   || (
3727
+				   ! $for_this_model
3728
+				   && in_array(
3729
+					   $default_where_conditions_value,
3730
+					   array(
3731
+						   EEM_Base::default_where_conditions_minimum_others,
3732
+						   EEM_Base::default_where_conditions_minimum_all,
3733
+					   ),
3734
+					   true
3735
+				   )
3736
+			   );
3737
+	}
3738
+
3739
+
3740
+	/**
3741
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3742
+	 * then we also add a special where condition which allows for that model's primary key
3743
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3744
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3745
+	 *
3746
+	 * @param array    $default_where_conditions
3747
+	 * @param array    $provided_where_conditions
3748
+	 * @param EEM_Base $model
3749
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3750
+	 * @return array like EEM_Base::get_all's $query_params[0]
3751
+	 * @throws EE_Error
3752
+	 */
3753
+	private function _override_defaults_or_make_null_friendly(
3754
+		$default_where_conditions,
3755
+		$provided_where_conditions,
3756
+		$model,
3757
+		$model_relation_path
3758
+	) {
3759
+		$null_friendly_where_conditions = array();
3760
+		$none_overridden = true;
3761
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3762
+		foreach ($default_where_conditions as $key => $val) {
3763
+			if (isset($provided_where_conditions[$key])) {
3764
+				$none_overridden = false;
3765
+			} else {
3766
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3767
+			}
3768
+		}
3769
+		if ($none_overridden && $default_where_conditions) {
3770
+			if ($model->has_primary_key_field()) {
3771
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3772
+																				. "."
3773
+																				. $model->primary_key_name()] = array('IS NULL');
3774
+			}/*else{
3775 3775
 				//@todo NO PK, use other defaults
3776 3776
 			}*/
3777
-        }
3778
-        return $null_friendly_where_conditions;
3779
-    }
3780
-
3781
-
3782
-
3783
-    /**
3784
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3785
-     * default where conditions on all get_all, update, and delete queries done by this model.
3786
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3787
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3788
-     *
3789
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3790
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3791
-     */
3792
-    private function _get_default_where_conditions($model_relation_path = null)
3793
-    {
3794
-        if ($this->_ignore_where_strategy) {
3795
-            return array();
3796
-        }
3797
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3798
-    }
3799
-
3800
-
3801
-
3802
-    /**
3803
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3804
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3805
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3806
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3807
-     * Similar to _get_default_where_conditions
3808
-     *
3809
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3810
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3811
-     */
3812
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3813
-    {
3814
-        if ($this->_ignore_where_strategy) {
3815
-            return array();
3816
-        }
3817
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3818
-    }
3819
-
3820
-
3821
-
3822
-    /**
3823
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3824
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3825
-     *
3826
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3827
-     * @return string
3828
-     * @throws EE_Error
3829
-     */
3830
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3831
-    {
3832
-        $selects = $this->_get_columns_to_select_for_this_model();
3833
-        foreach (
3834
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3835
-            $name_of_other_model_included
3836
-        ) {
3837
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3838
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3839
-            foreach ($other_model_selects as $key => $value) {
3840
-                $selects[] = $value;
3841
-            }
3842
-        }
3843
-        return implode(", ", $selects);
3844
-    }
3845
-
3846
-
3847
-
3848
-    /**
3849
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3850
-     * So that's going to be the columns for all the fields on the model
3851
-     *
3852
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3853
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3854
-     */
3855
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3856
-    {
3857
-        $fields = $this->field_settings();
3858
-        $selects = array();
3859
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3860
-            $this->get_this_model_name());
3861
-        foreach ($fields as $field_obj) {
3862
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3863
-                         . $field_obj->get_table_alias()
3864
-                         . "."
3865
-                         . $field_obj->get_table_column()
3866
-                         . " AS '"
3867
-                         . $table_alias_with_model_relation_chain_prefix
3868
-                         . $field_obj->get_table_alias()
3869
-                         . "."
3870
-                         . $field_obj->get_table_column()
3871
-                         . "'";
3872
-        }
3873
-        //make sure we are also getting the PKs of each table
3874
-        $tables = $this->get_tables();
3875
-        if (count($tables) > 1) {
3876
-            foreach ($tables as $table_obj) {
3877
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3878
-                                       . $table_obj->get_fully_qualified_pk_column();
3879
-                if (! in_array($qualified_pk_column, $selects)) {
3880
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3881
-                }
3882
-            }
3883
-        }
3884
-        return $selects;
3885
-    }
3886
-
3887
-
3888
-
3889
-    /**
3890
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3891
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3892
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3893
-     * SQL for joining, and the data types
3894
-     *
3895
-     * @param null|string                 $original_query_param
3896
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3897
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3898
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3899
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3900
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3901
-     *                                                          or 'Registration's
3902
-     * @param string                      $original_query_param what it originally was (eg
3903
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3904
-     *                                                          matches $query_param
3905
-     * @throws EE_Error
3906
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3907
-     */
3908
-    private function _extract_related_model_info_from_query_param(
3909
-        $query_param,
3910
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3911
-        $query_param_type,
3912
-        $original_query_param = null
3913
-    ) {
3914
-        if ($original_query_param === null) {
3915
-            $original_query_param = $query_param;
3916
-        }
3917
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3918
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3919
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3920
-        $allow_fields = in_array(
3921
-            $query_param_type,
3922
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3923
-            true
3924
-        );
3925
-        //check to see if we have a field on this model
3926
-        $this_model_fields = $this->field_settings(true);
3927
-        if (array_key_exists($query_param, $this_model_fields)) {
3928
-            if ($allow_fields) {
3929
-                return;
3930
-            }
3931
-            throw new EE_Error(
3932
-                sprintf(
3933
-                    __(
3934
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3935
-                        "event_espresso"
3936
-                    ),
3937
-                    $query_param, get_class($this), $query_param_type, $original_query_param
3938
-                )
3939
-            );
3940
-        }
3941
-        //check if this is a special logic query param
3942
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3943
-            if ($allow_logic_query_params) {
3944
-                return;
3945
-            }
3946
-            throw new EE_Error(
3947
-                sprintf(
3948
-                    __(
3949
-                        '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',
3950
-                        'event_espresso'
3951
-                    ),
3952
-                    implode('", "', $this->_logic_query_param_keys),
3953
-                    $query_param,
3954
-                    get_class($this),
3955
-                    '<br />',
3956
-                    "\t"
3957
-                    . ' $passed_in_query_info = <pre>'
3958
-                    . print_r($passed_in_query_info, true)
3959
-                    . '</pre>'
3960
-                    . "\n\t"
3961
-                    . ' $query_param_type = '
3962
-                    . $query_param_type
3963
-                    . "\n\t"
3964
-                    . ' $original_query_param = '
3965
-                    . $original_query_param
3966
-                )
3967
-            );
3968
-        }
3969
-        //check if it's a custom selection
3970
-        if ($this->_custom_selections instanceof CustomSelects
3971
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
3972
-        ) {
3973
-            return;
3974
-        }
3975
-        //check if has a model name at the beginning
3976
-        //and
3977
-        //check if it's a field on a related model
3978
-        if ($this->extractJoinModelFromQueryParams(
3979
-            $passed_in_query_info,
3980
-            $query_param,
3981
-            $original_query_param,
3982
-            $query_param_type
3983
-        )) {
3984
-            return;
3985
-        }
3986
-
3987
-        //ok so $query_param didn't start with a model name
3988
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3989
-        //it's wack, that's what it is
3990
-        throw new EE_Error(
3991
-            sprintf(
3992
-                esc_html__(
3993
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3994
-                    "event_espresso"
3995
-                ),
3996
-                $query_param,
3997
-                get_class($this),
3998
-                $query_param_type,
3999
-                $original_query_param
4000
-            )
4001
-        );
4002
-    }
4003
-
4004
-
4005
-    /**
4006
-     * Extracts any possible join model information from the provided possible_join_string.
4007
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4008
-     * parts that should be added to the query.
4009
-     *
4010
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4011
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4012
-     * @param null|string                 $original_query_param
4013
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4014
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4015
-     * @return bool  returns true if a join was added and false if not.
4016
-     * @throws EE_Error
4017
-     */
4018
-    private function extractJoinModelFromQueryParams(
4019
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4020
-        $possible_join_string,
4021
-        $original_query_param,
4022
-        $query_parameter_type
4023
-    ) {
4024
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4025
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4026
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4027
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4028
-                if ($possible_join_string === '') {
4029
-                    //nothing left to $query_param
4030
-                    //we should actually end in a field name, not a model like this!
4031
-                    throw new EE_Error(
4032
-                        sprintf(
4033
-                            esc_html__(
4034
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4035
-                                "event_espresso"
4036
-                            ),
4037
-                            $possible_join_string,
4038
-                            $query_parameter_type,
4039
-                            get_class($this),
4040
-                            $valid_related_model_name
4041
-                        )
4042
-                    );
4043
-                }
4044
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4045
-                $related_model_obj->_extract_related_model_info_from_query_param(
4046
-                    $possible_join_string,
4047
-                    $query_info_carrier,
4048
-                    $query_parameter_type,
4049
-                    $original_query_param
4050
-                );
4051
-                return true;
4052
-            }
4053
-            if ($possible_join_string === $valid_related_model_name) {
4054
-                $this->_add_join_to_model(
4055
-                    $valid_related_model_name,
4056
-                    $query_info_carrier,
4057
-                    $original_query_param
4058
-                );
4059
-                return true;
4060
-            }
4061
-        }
4062
-        return false;
4063
-    }
4064
-
4065
-
4066
-    /**
4067
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4068
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4069
-     * @throws EE_Error
4070
-     */
4071
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4072
-    {
4073
-        if ($this->_custom_selections instanceof CustomSelects
4074
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4075
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4076
-            )
4077
-        ) {
4078
-            $original_selects = $this->_custom_selections->originalSelects();
4079
-            foreach ($original_selects as $alias => $select_configuration) {
4080
-                $this->extractJoinModelFromQueryParams(
4081
-                    $query_info_carrier,
4082
-                    $select_configuration[0],
4083
-                    $select_configuration[0],
4084
-                    'custom_selects'
4085
-                );
4086
-            }
4087
-        }
4088
-    }
4089
-
4090
-
4091
-
4092
-    /**
4093
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4094
-     * and store it on $passed_in_query_info
4095
-     *
4096
-     * @param string                      $model_name
4097
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4098
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4099
-     *                                                          model and $model_name. Eg, if we are querying Event,
4100
-     *                                                          and are adding a join to 'Payment' with the original
4101
-     *                                                          query param key
4102
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4103
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4104
-     *                                                          Payment wants to add default query params so that it
4105
-     *                                                          will know what models to prepend onto its default query
4106
-     *                                                          params or in case it wants to rename tables (in case
4107
-     *                                                          there are multiple joins to the same table)
4108
-     * @return void
4109
-     * @throws EE_Error
4110
-     */
4111
-    private function _add_join_to_model(
4112
-        $model_name,
4113
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4114
-        $original_query_param
4115
-    ) {
4116
-        $relation_obj = $this->related_settings_for($model_name);
4117
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4118
-        //check if the relation is HABTM, because then we're essentially doing two joins
4119
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
4120
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4121
-            $join_model_obj = $relation_obj->get_join_model();
4122
-            //replace the model specified with the join model for this relation chain, whi
4123
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4124
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
4125
-            $passed_in_query_info->merge(
4126
-                new EE_Model_Query_Info_Carrier(
4127
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4128
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4129
-                )
4130
-            );
4131
-        }
4132
-        //now just join to the other table pointed to by the relation object, and add its data types
4133
-        $passed_in_query_info->merge(
4134
-            new EE_Model_Query_Info_Carrier(
4135
-                array($model_relation_chain => $model_name),
4136
-                $relation_obj->get_join_statement($model_relation_chain)
4137
-            )
4138
-        );
4139
-    }
4140
-
4141
-
4142
-
4143
-    /**
4144
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4145
-     *
4146
-     * @param array $where_params like EEM_Base::get_all
4147
-     * @return string of SQL
4148
-     * @throws EE_Error
4149
-     */
4150
-    private function _construct_where_clause($where_params)
4151
-    {
4152
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4153
-        if ($SQL) {
4154
-            return " WHERE " . $SQL;
4155
-        }
4156
-        return '';
4157
-    }
4158
-
4159
-
4160
-
4161
-    /**
4162
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4163
-     * and should be passed HAVING parameters, not WHERE parameters
4164
-     *
4165
-     * @param array $having_params
4166
-     * @return string
4167
-     * @throws EE_Error
4168
-     */
4169
-    private function _construct_having_clause($having_params)
4170
-    {
4171
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4172
-        if ($SQL) {
4173
-            return " HAVING " . $SQL;
4174
-        }
4175
-        return '';
4176
-    }
4177
-
4178
-
4179
-    /**
4180
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4181
-     * Event_Meta.meta_value = 'foo'))"
4182
-     *
4183
-     * @param array  $where_params see EEM_Base::get_all for documentation
4184
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4185
-     * @throws EE_Error
4186
-     * @return string of SQL
4187
-     */
4188
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4189
-    {
4190
-        $where_clauses = array();
4191
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4192
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4193
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4194
-                switch ($query_param) {
4195
-                    case 'not':
4196
-                    case 'NOT':
4197
-                        $where_clauses[] = "! ("
4198
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4199
-                                $glue)
4200
-                                           . ")";
4201
-                        break;
4202
-                    case 'and':
4203
-                    case 'AND':
4204
-                        $where_clauses[] = " ("
4205
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4206
-                                ' AND ')
4207
-                                           . ")";
4208
-                        break;
4209
-                    case 'or':
4210
-                    case 'OR':
4211
-                        $where_clauses[] = " ("
4212
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4213
-                                ' OR ')
4214
-                                           . ")";
4215
-                        break;
4216
-                }
4217
-            } else {
4218
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4219
-                //if it's not a normal field, maybe it's a custom selection?
4220
-                if (! $field_obj) {
4221
-                    if ($this->_custom_selections instanceof CustomSelects) {
4222
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4223
-                    } else {
4224
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4225
-                            "event_espresso"), $query_param));
4226
-                    }
4227
-                }
4228
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4229
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4230
-            }
4231
-        }
4232
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4233
-    }
4234
-
4235
-
4236
-
4237
-    /**
4238
-     * Takes the input parameter and extract the table name (alias) and column name
4239
-     *
4240
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4241
-     * @throws EE_Error
4242
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4243
-     */
4244
-    private function _deduce_column_name_from_query_param($query_param)
4245
-    {
4246
-        $field = $this->_deduce_field_from_query_param($query_param);
4247
-        if ($field) {
4248
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4249
-                $query_param);
4250
-            return $table_alias_prefix . $field->get_qualified_column();
4251
-        }
4252
-        if ($this->_custom_selections instanceof CustomSelects
4253
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4254
-        ) {
4255
-            //maybe it's custom selection item?
4256
-            //if so, just use it as the "column name"
4257
-            return $query_param;
4258
-        }
4259
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4260
-            ? implode(',', $this->_custom_selections->columnAliases())
4261
-            : '';
4262
-        throw new EE_Error(
4263
-            sprintf(
4264
-                __(
4265
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4266
-                    "event_espresso"
4267
-                ), $query_param, $custom_select_aliases
4268
-            )
4269
-        );
4270
-    }
4271
-
4272
-
4273
-
4274
-    /**
4275
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4276
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4277
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4278
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4279
-     *
4280
-     * @param string $condition_query_param_key
4281
-     * @return string
4282
-     */
4283
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4284
-    {
4285
-        $pos_of_star = strpos($condition_query_param_key, '*');
4286
-        if ($pos_of_star === false) {
4287
-            return $condition_query_param_key;
4288
-        }
4289
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4290
-        return $condition_query_param_sans_star;
4291
-    }
4292
-
4293
-
4294
-
4295
-    /**
4296
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4297
-     *
4298
-     * @param                            mixed      array | string    $op_and_value
4299
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4300
-     * @throws EE_Error
4301
-     * @return string
4302
-     */
4303
-    private function _construct_op_and_value($op_and_value, $field_obj)
4304
-    {
4305
-        if (is_array($op_and_value)) {
4306
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4307
-            if (! $operator) {
4308
-                $php_array_like_string = array();
4309
-                foreach ($op_and_value as $key => $value) {
4310
-                    $php_array_like_string[] = "$key=>$value";
4311
-                }
4312
-                throw new EE_Error(
4313
-                    sprintf(
4314
-                        __(
4315
-                            "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))",
4316
-                            "event_espresso"
4317
-                        ),
4318
-                        implode(",", $php_array_like_string)
4319
-                    )
4320
-                );
4321
-            }
4322
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4323
-        } else {
4324
-            $operator = '=';
4325
-            $value = $op_and_value;
4326
-        }
4327
-        //check to see if the value is actually another field
4328
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4329
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4330
-        }
4331
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4332
-            //in this case, the value should be an array, or at least a comma-separated list
4333
-            //it will need to handle a little differently
4334
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4335
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4336
-            return $operator . SP . $cleaned_value;
4337
-        }
4338
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4339
-            //the value should be an array with count of two.
4340
-            if (count($value) !== 2) {
4341
-                throw new EE_Error(
4342
-                    sprintf(
4343
-                        __(
4344
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4345
-                            'event_espresso'
4346
-                        ),
4347
-                        "BETWEEN"
4348
-                    )
4349
-                );
4350
-            }
4351
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4352
-            return $operator . SP . $cleaned_value;
4353
-        }
4354
-        if (in_array($operator, $this->valid_null_style_operators())) {
4355
-            if ($value !== null) {
4356
-                throw new EE_Error(
4357
-                    sprintf(
4358
-                        __(
4359
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4360
-                            "event_espresso"
4361
-                        ),
4362
-                        $value,
4363
-                        $operator
4364
-                    )
4365
-                );
4366
-            }
4367
-            return $operator;
4368
-        }
4369
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4370
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4371
-            //remove other junk. So just treat it as a string.
4372
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4373
-        }
4374
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4375
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4376
-        }
4377
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4378
-            throw new EE_Error(
4379
-                sprintf(
4380
-                    __(
4381
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4382
-                        'event_espresso'
4383
-                    ),
4384
-                    $operator,
4385
-                    $operator
4386
-                )
4387
-            );
4388
-        }
4389
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4390
-            throw new EE_Error(
4391
-                sprintf(
4392
-                    __(
4393
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4394
-                        'event_espresso'
4395
-                    ),
4396
-                    $operator,
4397
-                    $operator
4398
-                )
4399
-            );
4400
-        }
4401
-        throw new EE_Error(
4402
-            sprintf(
4403
-                __(
4404
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4405
-                    "event_espresso"
4406
-                ),
4407
-                http_build_query($op_and_value)
4408
-            )
4409
-        );
4410
-    }
4411
-
4412
-
4413
-
4414
-    /**
4415
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4416
-     *
4417
-     * @param array                      $values
4418
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4419
-     *                                              '%s'
4420
-     * @return string
4421
-     * @throws EE_Error
4422
-     */
4423
-    public function _construct_between_value($values, $field_obj)
4424
-    {
4425
-        $cleaned_values = array();
4426
-        foreach ($values as $value) {
4427
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4428
-        }
4429
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4430
-    }
4431
-
4432
-
4433
-
4434
-    /**
4435
-     * Takes an array or a comma-separated list of $values and cleans them
4436
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4437
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4438
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4439
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4440
-     *
4441
-     * @param mixed                      $values    array or comma-separated string
4442
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4443
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4444
-     * @throws EE_Error
4445
-     */
4446
-    public function _construct_in_value($values, $field_obj)
4447
-    {
4448
-        //check if the value is a CSV list
4449
-        if (is_string($values)) {
4450
-            //in which case, turn it into an array
4451
-            $values = explode(",", $values);
4452
-        }
4453
-        $cleaned_values = array();
4454
-        foreach ($values as $value) {
4455
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4456
-        }
4457
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4458
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4459
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4460
-        if (empty($cleaned_values)) {
4461
-            $all_fields = $this->field_settings();
4462
-            $a_field = array_shift($all_fields);
4463
-            $main_table = $this->_get_main_table();
4464
-            $cleaned_values[] = "SELECT "
4465
-                                . $a_field->get_table_column()
4466
-                                . " FROM "
4467
-                                . $main_table->get_table_name()
4468
-                                . " WHERE FALSE";
4469
-        }
4470
-        return "(" . implode(",", $cleaned_values) . ")";
4471
-    }
4472
-
4473
-
4474
-
4475
-    /**
4476
-     * @param mixed                      $value
4477
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4478
-     * @throws EE_Error
4479
-     * @return false|null|string
4480
-     */
4481
-    private function _wpdb_prepare_using_field($value, $field_obj)
4482
-    {
4483
-        /** @type WPDB $wpdb */
4484
-        global $wpdb;
4485
-        if ($field_obj instanceof EE_Model_Field_Base) {
4486
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4487
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4488
-        } //$field_obj should really just be a data type
4489
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4490
-            throw new EE_Error(
4491
-                sprintf(
4492
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4493
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4494
-                )
4495
-            );
4496
-        }
4497
-        return $wpdb->prepare($field_obj, $value);
4498
-    }
4499
-
4500
-
4501
-
4502
-    /**
4503
-     * Takes the input parameter and finds the model field that it indicates.
4504
-     *
4505
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4506
-     * @throws EE_Error
4507
-     * @return EE_Model_Field_Base
4508
-     */
4509
-    protected function _deduce_field_from_query_param($query_param_name)
4510
-    {
4511
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4512
-        //which will help us find the database table and column
4513
-        $query_param_parts = explode(".", $query_param_name);
4514
-        if (empty($query_param_parts)) {
4515
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4516
-                'event_espresso'), $query_param_name));
4517
-        }
4518
-        $number_of_parts = count($query_param_parts);
4519
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4520
-        if ($number_of_parts === 1) {
4521
-            $field_name = $last_query_param_part;
4522
-            $model_obj = $this;
4523
-        } else {// $number_of_parts >= 2
4524
-            //the last part is the column name, and there are only 2parts. therefore...
4525
-            $field_name = $last_query_param_part;
4526
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4527
-        }
4528
-        try {
4529
-            return $model_obj->field_settings_for($field_name);
4530
-        } catch (EE_Error $e) {
4531
-            return null;
4532
-        }
4533
-    }
4534
-
4535
-
4536
-
4537
-    /**
4538
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4539
-     * alias and column which corresponds to it
4540
-     *
4541
-     * @param string $field_name
4542
-     * @throws EE_Error
4543
-     * @return string
4544
-     */
4545
-    public function _get_qualified_column_for_field($field_name)
4546
-    {
4547
-        $all_fields = $this->field_settings();
4548
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4549
-        if ($field) {
4550
-            return $field->get_qualified_column();
4551
-        }
4552
-        throw new EE_Error(
4553
-            sprintf(
4554
-                __(
4555
-                    "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.",
4556
-                    'event_espresso'
4557
-                ), $field_name, get_class($this)
4558
-            )
4559
-        );
4560
-    }
4561
-
4562
-
4563
-
4564
-    /**
4565
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4566
-     * Example usage:
4567
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4568
-     *      array(),
4569
-     *      ARRAY_A,
4570
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4571
-     *  );
4572
-     * is equivalent to
4573
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4574
-     * and
4575
-     *  EEM_Event::instance()->get_all_wpdb_results(
4576
-     *      array(
4577
-     *          array(
4578
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4579
-     *          ),
4580
-     *          ARRAY_A,
4581
-     *          implode(
4582
-     *              ', ',
4583
-     *              array_merge(
4584
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4585
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4586
-     *              )
4587
-     *          )
4588
-     *      )
4589
-     *  );
4590
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4591
-     *
4592
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4593
-     *                                            and the one whose fields you are selecting for example: when querying
4594
-     *                                            tickets model and selecting fields from the tickets model you would
4595
-     *                                            leave this parameter empty, because no models are needed to join
4596
-     *                                            between the queried model and the selected one. Likewise when
4597
-     *                                            querying the datetime model and selecting fields from the tickets
4598
-     *                                            model, it would also be left empty, because there is a direct
4599
-     *                                            relation from datetimes to tickets, so no model is needed to join
4600
-     *                                            them together. However, when querying from the event model and
4601
-     *                                            selecting fields from the ticket model, you should provide the string
4602
-     *                                            'Datetime', indicating that the event model must first join to the
4603
-     *                                            datetime model in order to find its relation to ticket model.
4604
-     *                                            Also, when querying from the venue model and selecting fields from
4605
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4606
-     *                                            indicating you need to join the venue model to the event model,
4607
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4608
-     *                                            This string is used to deduce the prefix that gets added onto the
4609
-     *                                            models' tables qualified columns
4610
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4611
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4612
-     *                                            qualified column names
4613
-     * @return array|string
4614
-     */
4615
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4616
-    {
4617
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4618
-        $qualified_columns = array();
4619
-        foreach ($this->field_settings() as $field_name => $field) {
4620
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4621
-        }
4622
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4623
-    }
4624
-
4625
-
4626
-
4627
-    /**
4628
-     * constructs the select use on special limit joins
4629
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4630
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4631
-     * (as that is typically where the limits would be set).
4632
-     *
4633
-     * @param  string       $table_alias The table the select is being built for
4634
-     * @param  mixed|string $limit       The limit for this select
4635
-     * @return string                The final select join element for the query.
4636
-     */
4637
-    public function _construct_limit_join_select($table_alias, $limit)
4638
-    {
4639
-        $SQL = '';
4640
-        foreach ($this->_tables as $table_obj) {
4641
-            if ($table_obj instanceof EE_Primary_Table) {
4642
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4643
-                    ? $table_obj->get_select_join_limit($limit)
4644
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4645
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4646
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4647
-                    ? $table_obj->get_select_join_limit_join($limit)
4648
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4649
-            }
4650
-        }
4651
-        return $SQL;
4652
-    }
4653
-
4654
-
4655
-
4656
-    /**
4657
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4658
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4659
-     *
4660
-     * @return string SQL
4661
-     * @throws EE_Error
4662
-     */
4663
-    public function _construct_internal_join()
4664
-    {
4665
-        $SQL = $this->_get_main_table()->get_table_sql();
4666
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4667
-        return $SQL;
4668
-    }
4669
-
4670
-
4671
-
4672
-    /**
4673
-     * Constructs the SQL for joining all the tables on this model.
4674
-     * Normally $alias should be the primary table's alias, but in cases where
4675
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4676
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4677
-     * alias, this will construct SQL like:
4678
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4679
-     * With $alias being a secondary table's alias, this will construct SQL like:
4680
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4681
-     *
4682
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4683
-     * @return string
4684
-     */
4685
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4686
-    {
4687
-        $SQL = '';
4688
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4689
-        foreach ($this->_tables as $table_obj) {
4690
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4691
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4692
-                    //so we're joining to this table, meaning the table is already in
4693
-                    //the FROM statement, BUT the primary table isn't. So we want
4694
-                    //to add the inverse join sql
4695
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4696
-                } else {
4697
-                    //just add a regular JOIN to this table from the primary table
4698
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4699
-                }
4700
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4701
-        }
4702
-        return $SQL;
4703
-    }
4704
-
4705
-
4706
-
4707
-    /**
4708
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4709
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4710
-     * their data type (eg, '%s', '%d', etc)
4711
-     *
4712
-     * @return array
4713
-     */
4714
-    public function _get_data_types()
4715
-    {
4716
-        $data_types = array();
4717
-        foreach ($this->field_settings() as $field_obj) {
4718
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4719
-            /** @var $field_obj EE_Model_Field_Base */
4720
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4721
-        }
4722
-        return $data_types;
4723
-    }
4724
-
4725
-
4726
-
4727
-    /**
4728
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4729
-     *
4730
-     * @param string $model_name
4731
-     * @throws EE_Error
4732
-     * @return EEM_Base
4733
-     */
4734
-    public function get_related_model_obj($model_name)
4735
-    {
4736
-        $model_classname = "EEM_" . $model_name;
4737
-        if (! class_exists($model_classname)) {
4738
-            throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4739
-                'event_espresso'), $model_name, $model_classname));
4740
-        }
4741
-        return call_user_func($model_classname . "::instance");
4742
-    }
4743
-
4744
-
4745
-
4746
-    /**
4747
-     * Returns the array of EE_ModelRelations for this model.
4748
-     *
4749
-     * @return EE_Model_Relation_Base[]
4750
-     */
4751
-    public function relation_settings()
4752
-    {
4753
-        return $this->_model_relations;
4754
-    }
4755
-
4756
-
4757
-
4758
-    /**
4759
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4760
-     * because without THOSE models, this model probably doesn't have much purpose.
4761
-     * (Eg, without an event, datetimes have little purpose.)
4762
-     *
4763
-     * @return EE_Belongs_To_Relation[]
4764
-     */
4765
-    public function belongs_to_relations()
4766
-    {
4767
-        $belongs_to_relations = array();
4768
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4769
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4770
-                $belongs_to_relations[$model_name] = $relation_obj;
4771
-            }
4772
-        }
4773
-        return $belongs_to_relations;
4774
-    }
4775
-
4776
-
4777
-
4778
-    /**
4779
-     * Returns the specified EE_Model_Relation, or throws an exception
4780
-     *
4781
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4782
-     * @throws EE_Error
4783
-     * @return EE_Model_Relation_Base
4784
-     */
4785
-    public function related_settings_for($relation_name)
4786
-    {
4787
-        $relatedModels = $this->relation_settings();
4788
-        if (! array_key_exists($relation_name, $relatedModels)) {
4789
-            throw new EE_Error(
4790
-                sprintf(
4791
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4792
-                        'event_espresso'),
4793
-                    $relation_name,
4794
-                    $this->_get_class_name(),
4795
-                    implode(', ', array_keys($relatedModels))
4796
-                )
4797
-            );
4798
-        }
4799
-        return $relatedModels[$relation_name];
4800
-    }
4801
-
4802
-
4803
-
4804
-    /**
4805
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4806
-     * fields
4807
-     *
4808
-     * @param string $fieldName
4809
-     * @param boolean $include_db_only_fields
4810
-     * @throws EE_Error
4811
-     * @return EE_Model_Field_Base
4812
-     */
4813
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4814
-    {
4815
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4816
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4817
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4818
-                get_class($this)));
4819
-        }
4820
-        return $fieldSettings[$fieldName];
4821
-    }
4822
-
4823
-
4824
-
4825
-    /**
4826
-     * Checks if this field exists on this model
4827
-     *
4828
-     * @param string $fieldName a key in the model's _field_settings array
4829
-     * @return boolean
4830
-     */
4831
-    public function has_field($fieldName)
4832
-    {
4833
-        $fieldSettings = $this->field_settings(true);
4834
-        if (isset($fieldSettings[$fieldName])) {
4835
-            return true;
4836
-        }
4837
-        return false;
4838
-    }
4839
-
4840
-
4841
-
4842
-    /**
4843
-     * Returns whether or not this model has a relation to the specified model
4844
-     *
4845
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4846
-     * @return boolean
4847
-     */
4848
-    public function has_relation($relation_name)
4849
-    {
4850
-        $relations = $this->relation_settings();
4851
-        if (isset($relations[$relation_name])) {
4852
-            return true;
4853
-        }
4854
-        return false;
4855
-    }
4856
-
4857
-
4858
-
4859
-    /**
4860
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4861
-     * Eg, on EE_Answer that would be ANS_ID field object
4862
-     *
4863
-     * @param $field_obj
4864
-     * @return boolean
4865
-     */
4866
-    public function is_primary_key_field($field_obj)
4867
-    {
4868
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4869
-    }
4870
-
4871
-
4872
-
4873
-    /**
4874
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4875
-     * Eg, on EE_Answer that would be ANS_ID field object
4876
-     *
4877
-     * @return EE_Model_Field_Base
4878
-     * @throws EE_Error
4879
-     */
4880
-    public function get_primary_key_field()
4881
-    {
4882
-        if ($this->_primary_key_field === null) {
4883
-            foreach ($this->field_settings(true) as $field_obj) {
4884
-                if ($this->is_primary_key_field($field_obj)) {
4885
-                    $this->_primary_key_field = $field_obj;
4886
-                    break;
4887
-                }
4888
-            }
4889
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4890
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4891
-                    get_class($this)));
4892
-            }
4893
-        }
4894
-        return $this->_primary_key_field;
4895
-    }
4896
-
4897
-
4898
-
4899
-    /**
4900
-     * Returns whether or not not there is a primary key on this model.
4901
-     * Internally does some caching.
4902
-     *
4903
-     * @return boolean
4904
-     */
4905
-    public function has_primary_key_field()
4906
-    {
4907
-        if ($this->_has_primary_key_field === null) {
4908
-            try {
4909
-                $this->get_primary_key_field();
4910
-                $this->_has_primary_key_field = true;
4911
-            } catch (EE_Error $e) {
4912
-                $this->_has_primary_key_field = false;
4913
-            }
4914
-        }
4915
-        return $this->_has_primary_key_field;
4916
-    }
4917
-
4918
-
4919
-
4920
-    /**
4921
-     * Finds the first field of type $field_class_name.
4922
-     *
4923
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4924
-     *                                 EE_Foreign_Key_Field, etc
4925
-     * @return EE_Model_Field_Base or null if none is found
4926
-     */
4927
-    public function get_a_field_of_type($field_class_name)
4928
-    {
4929
-        foreach ($this->field_settings() as $field) {
4930
-            if ($field instanceof $field_class_name) {
4931
-                return $field;
4932
-            }
4933
-        }
4934
-        return null;
4935
-    }
4936
-
4937
-
4938
-
4939
-    /**
4940
-     * Gets a foreign key field pointing to model.
4941
-     *
4942
-     * @param string $model_name eg Event, Registration, not EEM_Event
4943
-     * @return EE_Foreign_Key_Field_Base
4944
-     * @throws EE_Error
4945
-     */
4946
-    public function get_foreign_key_to($model_name)
4947
-    {
4948
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4949
-            foreach ($this->field_settings() as $field) {
4950
-                if (
4951
-                    $field instanceof EE_Foreign_Key_Field_Base
4952
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4953
-                ) {
4954
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4955
-                    break;
4956
-                }
4957
-            }
4958
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4959
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4960
-                    'event_espresso'), $model_name, get_class($this)));
4961
-            }
4962
-        }
4963
-        return $this->_cache_foreign_key_to_fields[$model_name];
4964
-    }
4965
-
4966
-
4967
-
4968
-    /**
4969
-     * Gets the table name (including $wpdb->prefix) for the table alias
4970
-     *
4971
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4972
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4973
-     *                            Either one works
4974
-     * @return string
4975
-     */
4976
-    public function get_table_for_alias($table_alias)
4977
-    {
4978
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4979
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4980
-    }
4981
-
4982
-
4983
-
4984
-    /**
4985
-     * Returns a flat array of all field son this model, instead of organizing them
4986
-     * by table_alias as they are in the constructor.
4987
-     *
4988
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4989
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4990
-     */
4991
-    public function field_settings($include_db_only_fields = false)
4992
-    {
4993
-        if ($include_db_only_fields) {
4994
-            if ($this->_cached_fields === null) {
4995
-                $this->_cached_fields = array();
4996
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4997
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4998
-                        $this->_cached_fields[$field_name] = $field_obj;
4999
-                    }
5000
-                }
5001
-            }
5002
-            return $this->_cached_fields;
5003
-        }
5004
-        if ($this->_cached_fields_non_db_only === null) {
5005
-            $this->_cached_fields_non_db_only = array();
5006
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5007
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5008
-                    /** @var $field_obj EE_Model_Field_Base */
5009
-                    if (! $field_obj->is_db_only_field()) {
5010
-                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5011
-                    }
5012
-                }
5013
-            }
5014
-        }
5015
-        return $this->_cached_fields_non_db_only;
5016
-    }
5017
-
5018
-
5019
-
5020
-    /**
5021
-     *        cycle though array of attendees and create objects out of each item
5022
-     *
5023
-     * @access        private
5024
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5025
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5026
-     *                           numerically indexed)
5027
-     * @throws EE_Error
5028
-     */
5029
-    protected function _create_objects($rows = array())
5030
-    {
5031
-        $array_of_objects = array();
5032
-        if (empty($rows)) {
5033
-            return array();
5034
-        }
5035
-        $count_if_model_has_no_primary_key = 0;
5036
-        $has_primary_key = $this->has_primary_key_field();
5037
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5038
-        foreach ((array)$rows as $row) {
5039
-            if (empty($row)) {
5040
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5041
-                return array();
5042
-            }
5043
-            //check if we've already set this object in the results array,
5044
-            //in which case there's no need to process it further (again)
5045
-            if ($has_primary_key) {
5046
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5047
-                    $row,
5048
-                    $primary_key_field->get_qualified_column(),
5049
-                    $primary_key_field->get_table_column()
5050
-                );
5051
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5052
-                    continue;
5053
-                }
5054
-            }
5055
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5056
-            if (! $classInstance) {
5057
-                throw new EE_Error(
5058
-                    sprintf(
5059
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5060
-                        $this->get_this_model_name(),
5061
-                        http_build_query($row)
5062
-                    )
5063
-                );
5064
-            }
5065
-            //set the timezone on the instantiated objects
5066
-            $classInstance->set_timezone($this->_timezone);
5067
-            //make sure if there is any timezone setting present that we set the timezone for the object
5068
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5069
-            $array_of_objects[$key] = $classInstance;
5070
-            //also, for all the relations of type BelongsTo, see if we can cache
5071
-            //those related models
5072
-            //(we could do this for other relations too, but if there are conditions
5073
-            //that filtered out some fo the results, then we'd be caching an incomplete set
5074
-            //so it requires a little more thought than just caching them immediately...)
5075
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5076
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5077
-                    //check if this model's INFO is present. If so, cache it on the model
5078
-                    $other_model = $relation_obj->get_other_model();
5079
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5080
-                    //if we managed to make a model object from the results, cache it on the main model object
5081
-                    if ($other_model_obj_maybe) {
5082
-                        //set timezone on these other model objects if they are present
5083
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5084
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5085
-                    }
5086
-                }
5087
-            }
5088
-            //also, if this was a custom select query, let's see if there are any results for the custom select fields
5089
-            //and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5090
-            //the field in the CustomSelects object
5091
-            if ($this->_custom_selections instanceof CustomSelects) {
5092
-                $classInstance->setCustomSelectsValues(
5093
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5094
-                );
5095
-            }
5096
-        }
5097
-        return $array_of_objects;
5098
-    }
5099
-
5100
-
5101
-    /**
5102
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5103
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5104
-     *
5105
-     * @param array $db_results_row
5106
-     * @return array
5107
-     */
5108
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5109
-    {
5110
-        $results = array();
5111
-        if ($this->_custom_selections instanceof CustomSelects) {
5112
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5113
-                if (isset($db_results_row[$alias])) {
5114
-                    $results[$alias] = $this->convertValueToDataType(
5115
-                        $db_results_row[$alias],
5116
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5117
-                    );
5118
-                }
5119
-            }
5120
-        }
5121
-        return $results;
5122
-    }
5123
-
5124
-
5125
-    /**
5126
-     * This will set the value for the given alias
5127
-     * @param string $value
5128
-     * @param string $datatype (one of %d, %s, %f)
5129
-     * @return int|string|float (int for %d, string for %s, float for %f)
5130
-     */
5131
-    protected function convertValueToDataType($value, $datatype)
5132
-    {
5133
-        switch ($datatype) {
5134
-            case '%f':
5135
-                return (float) $value;
5136
-            case '%d':
5137
-                return (int) $value;
5138
-            default:
5139
-                return (string) $value;
5140
-        }
5141
-    }
5142
-
5143
-
5144
-    /**
5145
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5146
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5147
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5148
-     * object (as set in the model_field!).
5149
-     *
5150
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5151
-     */
5152
-    public function create_default_object()
5153
-    {
5154
-        $this_model_fields_and_values = array();
5155
-        //setup the row using default values;
5156
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5157
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5158
-        }
5159
-        $className = $this->_get_class_name();
5160
-        $classInstance = EE_Registry::instance()
5161
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5162
-        return $classInstance;
5163
-    }
5164
-
5165
-
5166
-
5167
-    /**
5168
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5169
-     *                             or an stdClass where each property is the name of a column,
5170
-     * @return EE_Base_Class
5171
-     * @throws EE_Error
5172
-     */
5173
-    public function instantiate_class_from_array_or_object($cols_n_values)
5174
-    {
5175
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5176
-            $cols_n_values = get_object_vars($cols_n_values);
5177
-        }
5178
-        $primary_key = null;
5179
-        //make sure the array only has keys that are fields/columns on this model
5180
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5181
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5182
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5183
-        }
5184
-        $className = $this->_get_class_name();
5185
-        //check we actually found results that we can use to build our model object
5186
-        //if not, return null
5187
-        if ($this->has_primary_key_field()) {
5188
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5189
-                return null;
5190
-            }
5191
-        } else if ($this->unique_indexes()) {
5192
-            $first_column = reset($this_model_fields_n_values);
5193
-            if (empty($first_column)) {
5194
-                return null;
5195
-            }
5196
-        }
5197
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5198
-        if ($primary_key) {
5199
-            $classInstance = $this->get_from_entity_map($primary_key);
5200
-            if (! $classInstance) {
5201
-                $classInstance = EE_Registry::instance()
5202
-                                            ->load_class($className,
5203
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
5204
-                // add this new object to the entity map
5205
-                $classInstance = $this->add_to_entity_map($classInstance);
5206
-            }
5207
-        } else {
5208
-            $classInstance = EE_Registry::instance()
5209
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5210
-                                            true, false);
5211
-        }
5212
-        return $classInstance;
5213
-    }
5214
-
5215
-
5216
-
5217
-    /**
5218
-     * Gets the model object from the  entity map if it exists
5219
-     *
5220
-     * @param int|string $id the ID of the model object
5221
-     * @return EE_Base_Class
5222
-     */
5223
-    public function get_from_entity_map($id)
5224
-    {
5225
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5226
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5227
-    }
5228
-
5229
-
5230
-
5231
-    /**
5232
-     * add_to_entity_map
5233
-     * Adds the object to the model's entity mappings
5234
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5235
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5236
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5237
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5238
-     *        then this method should be called immediately after the update query
5239
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5240
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5241
-     *
5242
-     * @param    EE_Base_Class $object
5243
-     * @throws EE_Error
5244
-     * @return \EE_Base_Class
5245
-     */
5246
-    public function add_to_entity_map(EE_Base_Class $object)
5247
-    {
5248
-        $className = $this->_get_class_name();
5249
-        if (! $object instanceof $className) {
5250
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5251
-                is_object($object) ? get_class($object) : $object, $className));
5252
-        }
5253
-        /** @var $object EE_Base_Class */
5254
-        if (! $object->ID()) {
5255
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5256
-                "event_espresso"), get_class($this)));
5257
-        }
5258
-        // double check it's not already there
5259
-        $classInstance = $this->get_from_entity_map($object->ID());
5260
-        if ($classInstance) {
5261
-            return $classInstance;
5262
-        }
5263
-        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5264
-        return $object;
5265
-    }
5266
-
5267
-
5268
-
5269
-    /**
5270
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5271
-     * if no identifier is provided, then the entire entity map is emptied
5272
-     *
5273
-     * @param int|string $id the ID of the model object
5274
-     * @return boolean
5275
-     */
5276
-    public function clear_entity_map($id = null)
5277
-    {
5278
-        if (empty($id)) {
5279
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5280
-            return true;
5281
-        }
5282
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5283
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5284
-            return true;
5285
-        }
5286
-        return false;
5287
-    }
5288
-
5289
-
5290
-
5291
-    /**
5292
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5293
-     * Given an array where keys are column (or column alias) names and values,
5294
-     * returns an array of their corresponding field names and database values
5295
-     *
5296
-     * @param array $cols_n_values
5297
-     * @return array
5298
-     */
5299
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5300
-    {
5301
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5302
-    }
5303
-
5304
-
5305
-
5306
-    /**
5307
-     * _deduce_fields_n_values_from_cols_n_values
5308
-     * Given an array where keys are column (or column alias) names and values,
5309
-     * returns an array of their corresponding field names and database values
5310
-     *
5311
-     * @param string $cols_n_values
5312
-     * @return array
5313
-     */
5314
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5315
-    {
5316
-        $this_model_fields_n_values = array();
5317
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5318
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5319
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5320
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5321
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5322
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5323
-                    if (! $field_obj->is_db_only_field()) {
5324
-                        //prepare field as if its coming from db
5325
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5326
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5327
-                    }
5328
-                }
5329
-            } else {
5330
-                //the table's rows existed. Use their values
5331
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5332
-                    if (! $field_obj->is_db_only_field()) {
5333
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5334
-                            $cols_n_values, $field_obj->get_qualified_column(),
5335
-                            $field_obj->get_table_column()
5336
-                        );
5337
-                    }
5338
-                }
5339
-            }
5340
-        }
5341
-        return $this_model_fields_n_values;
5342
-    }
5343
-
5344
-
5345
-
5346
-    /**
5347
-     * @param $cols_n_values
5348
-     * @param $qualified_column
5349
-     * @param $regular_column
5350
-     * @return null
5351
-     */
5352
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5353
-    {
5354
-        $value = null;
5355
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5356
-        //does the field on the model relate to this column retrieved from the db?
5357
-        //or is it a db-only field? (not relating to the model)
5358
-        if (isset($cols_n_values[$qualified_column])) {
5359
-            $value = $cols_n_values[$qualified_column];
5360
-        } elseif (isset($cols_n_values[$regular_column])) {
5361
-            $value = $cols_n_values[$regular_column];
5362
-        }
5363
-        return $value;
5364
-    }
5365
-
5366
-
5367
-
5368
-    /**
5369
-     * refresh_entity_map_from_db
5370
-     * Makes sure the model object in the entity map at $id assumes the values
5371
-     * of the database (opposite of EE_base_Class::save())
5372
-     *
5373
-     * @param int|string $id
5374
-     * @return EE_Base_Class
5375
-     * @throws EE_Error
5376
-     */
5377
-    public function refresh_entity_map_from_db($id)
5378
-    {
5379
-        $obj_in_map = $this->get_from_entity_map($id);
5380
-        if ($obj_in_map) {
5381
-            $wpdb_results = $this->_get_all_wpdb_results(
5382
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5383
-            );
5384
-            if ($wpdb_results && is_array($wpdb_results)) {
5385
-                $one_row = reset($wpdb_results);
5386
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5387
-                    $obj_in_map->set_from_db($field_name, $db_value);
5388
-                }
5389
-                //clear the cache of related model objects
5390
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5391
-                    $obj_in_map->clear_cache($relation_name, null, true);
5392
-                }
5393
-            }
5394
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5395
-            return $obj_in_map;
5396
-        }
5397
-        return $this->get_one_by_ID($id);
5398
-    }
5399
-
5400
-
5401
-
5402
-    /**
5403
-     * refresh_entity_map_with
5404
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5405
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5406
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5407
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5408
-     *
5409
-     * @param int|string    $id
5410
-     * @param EE_Base_Class $replacing_model_obj
5411
-     * @return \EE_Base_Class
5412
-     * @throws EE_Error
5413
-     */
5414
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5415
-    {
5416
-        $obj_in_map = $this->get_from_entity_map($id);
5417
-        if ($obj_in_map) {
5418
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5419
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5420
-                    $obj_in_map->set($field_name, $value);
5421
-                }
5422
-                //make the model object in the entity map's cache match the $replacing_model_obj
5423
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5424
-                    $obj_in_map->clear_cache($relation_name, null, true);
5425
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5426
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5427
-                    }
5428
-                }
5429
-            }
5430
-            return $obj_in_map;
5431
-        }
5432
-        $this->add_to_entity_map($replacing_model_obj);
5433
-        return $replacing_model_obj;
5434
-    }
5435
-
5436
-
5437
-
5438
-    /**
5439
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5440
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5441
-     * require_once($this->_getClassName().".class.php");
5442
-     *
5443
-     * @return string
5444
-     */
5445
-    private function _get_class_name()
5446
-    {
5447
-        return "EE_" . $this->get_this_model_name();
5448
-    }
5449
-
5450
-
5451
-
5452
-    /**
5453
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5454
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5455
-     * it would be 'Events'.
5456
-     *
5457
-     * @param int $quantity
5458
-     * @return string
5459
-     */
5460
-    public function item_name($quantity = 1)
5461
-    {
5462
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5463
-    }
5464
-
5465
-
5466
-
5467
-    /**
5468
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5469
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5470
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5471
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5472
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5473
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5474
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5475
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5476
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5477
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5478
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5479
-     *        return $previousReturnValue.$returnString;
5480
-     * }
5481
-     * require('EEM_Answer.model.php');
5482
-     * $answer=EEM_Answer::instance();
5483
-     * echo $answer->my_callback('monkeys',100);
5484
-     * //will output "you called my_callback! and passed args:monkeys,100"
5485
-     *
5486
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5487
-     * @param array  $args       array of original arguments passed to the function
5488
-     * @throws EE_Error
5489
-     * @return mixed whatever the plugin which calls add_filter decides
5490
-     */
5491
-    public function __call($methodName, $args)
5492
-    {
5493
-        $className = get_class($this);
5494
-        $tagName = "FHEE__{$className}__{$methodName}";
5495
-        if (! has_filter($tagName)) {
5496
-            throw new EE_Error(
5497
-                sprintf(
5498
-                    __('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 );',
5499
-                        'event_espresso'),
5500
-                    $methodName,
5501
-                    $className,
5502
-                    $tagName,
5503
-                    '<br />'
5504
-                )
5505
-            );
5506
-        }
5507
-        return apply_filters($tagName, null, $this, $args);
5508
-    }
5509
-
5510
-
5511
-
5512
-    /**
5513
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5514
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5515
-     *
5516
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5517
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5518
-     *                                                       the object's class name
5519
-     *                                                       or object's ID
5520
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5521
-     *                                                       exists in the database. If it does not, we add it
5522
-     * @throws EE_Error
5523
-     * @return EE_Base_Class
5524
-     */
5525
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5526
-    {
5527
-        $className = $this->_get_class_name();
5528
-        if ($base_class_obj_or_id instanceof $className) {
5529
-            $model_object = $base_class_obj_or_id;
5530
-        } else {
5531
-            $primary_key_field = $this->get_primary_key_field();
5532
-            if (
5533
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5534
-                && (
5535
-                    is_int($base_class_obj_or_id)
5536
-                    || is_string($base_class_obj_or_id)
5537
-                )
5538
-            ) {
5539
-                // assume it's an ID.
5540
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5541
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5542
-            } else if (
5543
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5544
-                && is_string($base_class_obj_or_id)
5545
-            ) {
5546
-                // assume its a string representation of the object
5547
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5548
-            } else {
5549
-                throw new EE_Error(
5550
-                    sprintf(
5551
-                        __(
5552
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5553
-                            'event_espresso'
5554
-                        ),
5555
-                        $base_class_obj_or_id,
5556
-                        $this->_get_class_name(),
5557
-                        print_r($base_class_obj_or_id, true)
5558
-                    )
5559
-                );
5560
-            }
5561
-        }
5562
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5563
-            $model_object->save();
5564
-        }
5565
-        return $model_object;
5566
-    }
5567
-
5568
-
5569
-
5570
-    /**
5571
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5572
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5573
-     * returns it ID.
5574
-     *
5575
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5576
-     * @return int|string depending on the type of this model object's ID
5577
-     * @throws EE_Error
5578
-     */
5579
-    public function ensure_is_ID($base_class_obj_or_id)
5580
-    {
5581
-        $className = $this->_get_class_name();
5582
-        if ($base_class_obj_or_id instanceof $className) {
5583
-            /** @var $base_class_obj_or_id EE_Base_Class */
5584
-            $id = $base_class_obj_or_id->ID();
5585
-        } elseif (is_int($base_class_obj_or_id)) {
5586
-            //assume it's an ID
5587
-            $id = $base_class_obj_or_id;
5588
-        } elseif (is_string($base_class_obj_or_id)) {
5589
-            //assume its a string representation of the object
5590
-            $id = $base_class_obj_or_id;
5591
-        } else {
5592
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5593
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5594
-                print_r($base_class_obj_or_id, true)));
5595
-        }
5596
-        return $id;
5597
-    }
5598
-
5599
-
5600
-
5601
-    /**
5602
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5603
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5604
-     * been sanitized and converted into the appropriate domain.
5605
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5606
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5607
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5608
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5609
-     * $EVT = EEM_Event::instance(); $old_setting =
5610
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5611
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5612
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5613
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5614
-     *
5615
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5616
-     * @return void
5617
-     */
5618
-    public function assume_values_already_prepared_by_model_object(
5619
-        $values_already_prepared = self::not_prepared_by_model_object
5620
-    ) {
5621
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5622
-    }
5623
-
5624
-
5625
-
5626
-    /**
5627
-     * Read comments for assume_values_already_prepared_by_model_object()
5628
-     *
5629
-     * @return int
5630
-     */
5631
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5632
-    {
5633
-        return $this->_values_already_prepared_by_model_object;
5634
-    }
5635
-
5636
-
5637
-
5638
-    /**
5639
-     * Gets all the indexes on this model
5640
-     *
5641
-     * @return EE_Index[]
5642
-     */
5643
-    public function indexes()
5644
-    {
5645
-        return $this->_indexes;
5646
-    }
5647
-
5648
-
5649
-
5650
-    /**
5651
-     * Gets all the Unique Indexes on this model
5652
-     *
5653
-     * @return EE_Unique_Index[]
5654
-     */
5655
-    public function unique_indexes()
5656
-    {
5657
-        $unique_indexes = array();
5658
-        foreach ($this->_indexes as $name => $index) {
5659
-            if ($index instanceof EE_Unique_Index) {
5660
-                $unique_indexes [$name] = $index;
5661
-            }
5662
-        }
5663
-        return $unique_indexes;
5664
-    }
5665
-
5666
-
5667
-
5668
-    /**
5669
-     * Gets all the fields which, when combined, make the primary key.
5670
-     * This is usually just an array with 1 element (the primary key), but in cases
5671
-     * where there is no primary key, it's a combination of fields as defined
5672
-     * on a primary index
5673
-     *
5674
-     * @return EE_Model_Field_Base[] indexed by the field's name
5675
-     * @throws EE_Error
5676
-     */
5677
-    public function get_combined_primary_key_fields()
5678
-    {
5679
-        foreach ($this->indexes() as $index) {
5680
-            if ($index instanceof EE_Primary_Key_Index) {
5681
-                return $index->fields();
5682
-            }
5683
-        }
5684
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5685
-    }
5686
-
5687
-
5688
-
5689
-    /**
5690
-     * Used to build a primary key string (when the model has no primary key),
5691
-     * which can be used a unique string to identify this model object.
5692
-     *
5693
-     * @param array $cols_n_values keys are field names, values are their values
5694
-     * @return string
5695
-     * @throws EE_Error
5696
-     */
5697
-    public function get_index_primary_key_string($cols_n_values)
5698
-    {
5699
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5700
-            $this->get_combined_primary_key_fields());
5701
-        return http_build_query($cols_n_values_for_primary_key_index);
5702
-    }
5703
-
5704
-
5705
-
5706
-    /**
5707
-     * Gets the field values from the primary key string
5708
-     *
5709
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5710
-     * @param string $index_primary_key_string
5711
-     * @return null|array
5712
-     * @throws EE_Error
5713
-     */
5714
-    public function parse_index_primary_key_string($index_primary_key_string)
5715
-    {
5716
-        $key_fields = $this->get_combined_primary_key_fields();
5717
-        //check all of them are in the $id
5718
-        $key_vals_in_combined_pk = array();
5719
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5720
-        foreach ($key_fields as $key_field_name => $field_obj) {
5721
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5722
-                return null;
5723
-            }
5724
-        }
5725
-        return $key_vals_in_combined_pk;
5726
-    }
5727
-
5728
-
5729
-
5730
-    /**
5731
-     * verifies that an array of key-value pairs for model fields has a key
5732
-     * for each field comprising the primary key index
5733
-     *
5734
-     * @param array $key_vals
5735
-     * @return boolean
5736
-     * @throws EE_Error
5737
-     */
5738
-    public function has_all_combined_primary_key_fields($key_vals)
5739
-    {
5740
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5741
-        foreach ($keys_it_should_have as $key) {
5742
-            if (! isset($key_vals[$key])) {
5743
-                return false;
5744
-            }
5745
-        }
5746
-        return true;
5747
-    }
5748
-
5749
-
5750
-
5751
-    /**
5752
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5753
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5754
-     *
5755
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5756
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5757
-     * @throws EE_Error
5758
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5759
-     *                                                              indexed)
5760
-     */
5761
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5762
-    {
5763
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5764
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5765
-        } elseif (is_array($model_object_or_attributes_array)) {
5766
-            $attributes_array = $model_object_or_attributes_array;
5767
-        } else {
5768
-            throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5769
-                "event_espresso"), $model_object_or_attributes_array));
5770
-        }
5771
-        //even copies obviously won't have the same ID, so remove the primary key
5772
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5773
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5774
-            unset($attributes_array[$this->primary_key_name()]);
5775
-        }
5776
-        if (isset($query_params[0])) {
5777
-            $query_params[0] = array_merge($attributes_array, $query_params);
5778
-        } else {
5779
-            $query_params[0] = $attributes_array;
5780
-        }
5781
-        return $this->get_all($query_params);
5782
-    }
5783
-
5784
-
5785
-
5786
-    /**
5787
-     * Gets the first copy we find. See get_all_copies for more details
5788
-     *
5789
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5790
-     * @param array $query_params
5791
-     * @return EE_Base_Class
5792
-     * @throws EE_Error
5793
-     */
5794
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5795
-    {
5796
-        if (! is_array($query_params)) {
5797
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5798
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5799
-                    gettype($query_params)), '4.6.0');
5800
-            $query_params = array();
5801
-        }
5802
-        $query_params['limit'] = 1;
5803
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5804
-        if (is_array($copies)) {
5805
-            return array_shift($copies);
5806
-        }
5807
-        return null;
5808
-    }
5809
-
5810
-
5811
-
5812
-    /**
5813
-     * Updates the item with the specified id. Ignores default query parameters because
5814
-     * we have specified the ID, and its assumed we KNOW what we're doing
5815
-     *
5816
-     * @param array      $fields_n_values keys are field names, values are their new values
5817
-     * @param int|string $id              the value of the primary key to update
5818
-     * @return int number of rows updated
5819
-     * @throws EE_Error
5820
-     */
5821
-    public function update_by_ID($fields_n_values, $id)
5822
-    {
5823
-        $query_params = array(
5824
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5825
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5826
-        );
5827
-        return $this->update($fields_n_values, $query_params);
5828
-    }
5829
-
5830
-
5831
-
5832
-    /**
5833
-     * Changes an operator which was supplied to the models into one usable in SQL
5834
-     *
5835
-     * @param string $operator_supplied
5836
-     * @return string an operator which can be used in SQL
5837
-     * @throws EE_Error
5838
-     */
5839
-    private function _prepare_operator_for_sql($operator_supplied)
5840
-    {
5841
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5842
-            : null;
5843
-        if ($sql_operator) {
5844
-            return $sql_operator;
5845
-        }
5846
-        throw new EE_Error(
5847
-            sprintf(
5848
-                __(
5849
-                    "The operator '%s' is not in the list of valid operators: %s",
5850
-                    "event_espresso"
5851
-                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5852
-            )
5853
-        );
5854
-    }
5855
-
5856
-
5857
-
5858
-    /**
5859
-     * Gets the valid operators
5860
-     * @return array keys are accepted strings, values are the SQL they are converted to
5861
-     */
5862
-    public function valid_operators(){
5863
-        return $this->_valid_operators;
5864
-    }
5865
-
5866
-
5867
-
5868
-    /**
5869
-     * Gets the between-style operators (take 2 arguments).
5870
-     * @return array keys are accepted strings, values are the SQL they are converted to
5871
-     */
5872
-    public function valid_between_style_operators()
5873
-    {
5874
-        return array_intersect(
5875
-            $this->valid_operators(),
5876
-            $this->_between_style_operators
5877
-        );
5878
-    }
5879
-
5880
-    /**
5881
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5882
-     * @return array keys are accepted strings, values are the SQL they are converted to
5883
-     */
5884
-    public function valid_like_style_operators()
5885
-    {
5886
-        return array_intersect(
5887
-            $this->valid_operators(),
5888
-            $this->_like_style_operators
5889
-        );
5890
-    }
5891
-
5892
-    /**
5893
-     * Gets the "in"-style operators
5894
-     * @return array keys are accepted strings, values are the SQL they are converted to
5895
-     */
5896
-    public function valid_in_style_operators()
5897
-    {
5898
-        return array_intersect(
5899
-            $this->valid_operators(),
5900
-            $this->_in_style_operators
5901
-        );
5902
-    }
5903
-
5904
-    /**
5905
-     * Gets the "null"-style operators (accept no arguments)
5906
-     * @return array keys are accepted strings, values are the SQL they are converted to
5907
-     */
5908
-    public function valid_null_style_operators()
5909
-    {
5910
-        return array_intersect(
5911
-            $this->valid_operators(),
5912
-            $this->_null_style_operators
5913
-        );
5914
-    }
5915
-
5916
-    /**
5917
-     * Gets an array where keys are the primary keys and values are their 'names'
5918
-     * (as determined by the model object's name() function, which is often overridden)
5919
-     *
5920
-     * @param array $query_params like get_all's
5921
-     * @return string[]
5922
-     * @throws EE_Error
5923
-     */
5924
-    public function get_all_names($query_params = array())
5925
-    {
5926
-        $objs = $this->get_all($query_params);
5927
-        $names = array();
5928
-        foreach ($objs as $obj) {
5929
-            $names[$obj->ID()] = $obj->name();
5930
-        }
5931
-        return $names;
5932
-    }
5933
-
5934
-
5935
-
5936
-    /**
5937
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5938
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5939
-     * this is duplicated effort and reduces efficiency) you would be better to use
5940
-     * array_keys() on $model_objects.
5941
-     *
5942
-     * @param \EE_Base_Class[] $model_objects
5943
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5944
-     *                                               in the returned array
5945
-     * @return array
5946
-     * @throws EE_Error
5947
-     */
5948
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5949
-    {
5950
-        if (! $this->has_primary_key_field()) {
5951
-            if (WP_DEBUG) {
5952
-                EE_Error::add_error(
5953
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5954
-                    __FILE__,
5955
-                    __FUNCTION__,
5956
-                    __LINE__
5957
-                );
5958
-            }
5959
-        }
5960
-        $IDs = array();
5961
-        foreach ($model_objects as $model_object) {
5962
-            $id = $model_object->ID();
5963
-            if (! $id) {
5964
-                if ($filter_out_empty_ids) {
5965
-                    continue;
5966
-                }
5967
-                if (WP_DEBUG) {
5968
-                    EE_Error::add_error(
5969
-                        __(
5970
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5971
-                            'event_espresso'
5972
-                        ),
5973
-                        __FILE__,
5974
-                        __FUNCTION__,
5975
-                        __LINE__
5976
-                    );
5977
-                }
5978
-            }
5979
-            $IDs[] = $id;
5980
-        }
5981
-        return $IDs;
5982
-    }
5983
-
5984
-
5985
-
5986
-    /**
5987
-     * Returns the string used in capabilities relating to this model. If there
5988
-     * are no capabilities that relate to this model returns false
5989
-     *
5990
-     * @return string|false
5991
-     */
5992
-    public function cap_slug()
5993
-    {
5994
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5995
-    }
5996
-
5997
-
5998
-
5999
-    /**
6000
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6001
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6002
-     * only returns the cap restrictions array in that context (ie, the array
6003
-     * at that key)
6004
-     *
6005
-     * @param string $context
6006
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6007
-     * @throws EE_Error
6008
-     */
6009
-    public function cap_restrictions($context = EEM_Base::caps_read)
6010
-    {
6011
-        EEM_Base::verify_is_valid_cap_context($context);
6012
-        //check if we ought to run the restriction generator first
6013
-        if (
6014
-            isset($this->_cap_restriction_generators[$context])
6015
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6016
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6017
-        ) {
6018
-            $this->_cap_restrictions[$context] = array_merge(
6019
-                $this->_cap_restrictions[$context],
6020
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
6021
-            );
6022
-        }
6023
-        //and make sure we've finalized the construction of each restriction
6024
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6025
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6026
-                $where_conditions_obj->_finalize_construct($this);
6027
-            }
6028
-        }
6029
-        return $this->_cap_restrictions[$context];
6030
-    }
6031
-
6032
-
6033
-
6034
-    /**
6035
-     * Indicating whether or not this model thinks its a wp core model
6036
-     *
6037
-     * @return boolean
6038
-     */
6039
-    public function is_wp_core_model()
6040
-    {
6041
-        return $this->_wp_core_model;
6042
-    }
6043
-
6044
-
6045
-
6046
-    /**
6047
-     * Gets all the caps that are missing which impose a restriction on
6048
-     * queries made in this context
6049
-     *
6050
-     * @param string $context one of EEM_Base::caps_ constants
6051
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6052
-     * @throws EE_Error
6053
-     */
6054
-    public function caps_missing($context = EEM_Base::caps_read)
6055
-    {
6056
-        $missing_caps = array();
6057
-        $cap_restrictions = $this->cap_restrictions($context);
6058
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6059
-            if (! EE_Capabilities::instance()
6060
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6061
-            ) {
6062
-                $missing_caps[$cap] = $restriction_if_no_cap;
6063
-            }
6064
-        }
6065
-        return $missing_caps;
6066
-    }
6067
-
6068
-
6069
-
6070
-    /**
6071
-     * Gets the mapping from capability contexts to action strings used in capability names
6072
-     *
6073
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6074
-     * one of 'read', 'edit', or 'delete'
6075
-     */
6076
-    public function cap_contexts_to_cap_action_map()
6077
-    {
6078
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
6079
-            $this);
6080
-    }
6081
-
6082
-
6083
-
6084
-    /**
6085
-     * Gets the action string for the specified capability context
6086
-     *
6087
-     * @param string $context
6088
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6089
-     * @throws EE_Error
6090
-     */
6091
-    public function cap_action_for_context($context)
6092
-    {
6093
-        $mapping = $this->cap_contexts_to_cap_action_map();
6094
-        if (isset($mapping[$context])) {
6095
-            return $mapping[$context];
6096
-        }
6097
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6098
-            return $action;
6099
-        }
6100
-        throw new EE_Error(
6101
-            sprintf(
6102
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6103
-                $context,
6104
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6105
-            )
6106
-        );
6107
-    }
6108
-
6109
-
6110
-
6111
-    /**
6112
-     * Returns all the capability contexts which are valid when querying models
6113
-     *
6114
-     * @return array
6115
-     */
6116
-    public static function valid_cap_contexts()
6117
-    {
6118
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6119
-            self::caps_read,
6120
-            self::caps_read_admin,
6121
-            self::caps_edit,
6122
-            self::caps_delete,
6123
-        ));
6124
-    }
6125
-
6126
-
6127
-
6128
-    /**
6129
-     * Returns all valid options for 'default_where_conditions'
6130
-     *
6131
-     * @return array
6132
-     */
6133
-    public static function valid_default_where_conditions()
6134
-    {
6135
-        return array(
6136
-            EEM_Base::default_where_conditions_all,
6137
-            EEM_Base::default_where_conditions_this_only,
6138
-            EEM_Base::default_where_conditions_others_only,
6139
-            EEM_Base::default_where_conditions_minimum_all,
6140
-            EEM_Base::default_where_conditions_minimum_others,
6141
-            EEM_Base::default_where_conditions_none
6142
-        );
6143
-    }
6144
-
6145
-    // public static function default_where_conditions_full
6146
-    /**
6147
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6148
-     *
6149
-     * @param string $context
6150
-     * @return bool
6151
-     * @throws EE_Error
6152
-     */
6153
-    static public function verify_is_valid_cap_context($context)
6154
-    {
6155
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6156
-        if (in_array($context, $valid_cap_contexts)) {
6157
-            return true;
6158
-        }
6159
-        throw new EE_Error(
6160
-            sprintf(
6161
-                __(
6162
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6163
-                    'event_espresso'
6164
-                ),
6165
-                $context,
6166
-                'EEM_Base',
6167
-                implode(',', $valid_cap_contexts)
6168
-            )
6169
-        );
6170
-    }
6171
-
6172
-
6173
-
6174
-    /**
6175
-     * Clears all the models field caches. This is only useful when a sub-class
6176
-     * might have added a field or something and these caches might be invalidated
6177
-     */
6178
-    protected function _invalidate_field_caches()
6179
-    {
6180
-        $this->_cache_foreign_key_to_fields = array();
6181
-        $this->_cached_fields = null;
6182
-        $this->_cached_fields_non_db_only = null;
6183
-    }
6184
-
6185
-
6186
-
6187
-    /**
6188
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6189
-     * (eg "and", "or", "not").
6190
-     *
6191
-     * @return array
6192
-     */
6193
-    public function logic_query_param_keys()
6194
-    {
6195
-        return $this->_logic_query_param_keys;
6196
-    }
6197
-
6198
-
6199
-
6200
-    /**
6201
-     * Determines whether or not the where query param array key is for a logic query param.
6202
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6203
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6204
-     *
6205
-     * @param $query_param_key
6206
-     * @return bool
6207
-     */
6208
-    public function is_logic_query_param_key($query_param_key)
6209
-    {
6210
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6211
-            if ($query_param_key === $logic_query_param_key
6212
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6213
-            ) {
6214
-                return true;
6215
-            }
6216
-        }
6217
-        return false;
6218
-    }
3777
+		}
3778
+		return $null_friendly_where_conditions;
3779
+	}
3780
+
3781
+
3782
+
3783
+	/**
3784
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3785
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3786
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3787
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3788
+	 *
3789
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3790
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3791
+	 */
3792
+	private function _get_default_where_conditions($model_relation_path = null)
3793
+	{
3794
+		if ($this->_ignore_where_strategy) {
3795
+			return array();
3796
+		}
3797
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3798
+	}
3799
+
3800
+
3801
+
3802
+	/**
3803
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3804
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3805
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3806
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3807
+	 * Similar to _get_default_where_conditions
3808
+	 *
3809
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3810
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3811
+	 */
3812
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3813
+	{
3814
+		if ($this->_ignore_where_strategy) {
3815
+			return array();
3816
+		}
3817
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3818
+	}
3819
+
3820
+
3821
+
3822
+	/**
3823
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3824
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3825
+	 *
3826
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3827
+	 * @return string
3828
+	 * @throws EE_Error
3829
+	 */
3830
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3831
+	{
3832
+		$selects = $this->_get_columns_to_select_for_this_model();
3833
+		foreach (
3834
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3835
+			$name_of_other_model_included
3836
+		) {
3837
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3838
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3839
+			foreach ($other_model_selects as $key => $value) {
3840
+				$selects[] = $value;
3841
+			}
3842
+		}
3843
+		return implode(", ", $selects);
3844
+	}
3845
+
3846
+
3847
+
3848
+	/**
3849
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3850
+	 * So that's going to be the columns for all the fields on the model
3851
+	 *
3852
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3853
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3854
+	 */
3855
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3856
+	{
3857
+		$fields = $this->field_settings();
3858
+		$selects = array();
3859
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3860
+			$this->get_this_model_name());
3861
+		foreach ($fields as $field_obj) {
3862
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3863
+						 . $field_obj->get_table_alias()
3864
+						 . "."
3865
+						 . $field_obj->get_table_column()
3866
+						 . " AS '"
3867
+						 . $table_alias_with_model_relation_chain_prefix
3868
+						 . $field_obj->get_table_alias()
3869
+						 . "."
3870
+						 . $field_obj->get_table_column()
3871
+						 . "'";
3872
+		}
3873
+		//make sure we are also getting the PKs of each table
3874
+		$tables = $this->get_tables();
3875
+		if (count($tables) > 1) {
3876
+			foreach ($tables as $table_obj) {
3877
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3878
+									   . $table_obj->get_fully_qualified_pk_column();
3879
+				if (! in_array($qualified_pk_column, $selects)) {
3880
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3881
+				}
3882
+			}
3883
+		}
3884
+		return $selects;
3885
+	}
3886
+
3887
+
3888
+
3889
+	/**
3890
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3891
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3892
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3893
+	 * SQL for joining, and the data types
3894
+	 *
3895
+	 * @param null|string                 $original_query_param
3896
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3897
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3898
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3899
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3900
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3901
+	 *                                                          or 'Registration's
3902
+	 * @param string                      $original_query_param what it originally was (eg
3903
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3904
+	 *                                                          matches $query_param
3905
+	 * @throws EE_Error
3906
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3907
+	 */
3908
+	private function _extract_related_model_info_from_query_param(
3909
+		$query_param,
3910
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3911
+		$query_param_type,
3912
+		$original_query_param = null
3913
+	) {
3914
+		if ($original_query_param === null) {
3915
+			$original_query_param = $query_param;
3916
+		}
3917
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3918
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3919
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3920
+		$allow_fields = in_array(
3921
+			$query_param_type,
3922
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3923
+			true
3924
+		);
3925
+		//check to see if we have a field on this model
3926
+		$this_model_fields = $this->field_settings(true);
3927
+		if (array_key_exists($query_param, $this_model_fields)) {
3928
+			if ($allow_fields) {
3929
+				return;
3930
+			}
3931
+			throw new EE_Error(
3932
+				sprintf(
3933
+					__(
3934
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3935
+						"event_espresso"
3936
+					),
3937
+					$query_param, get_class($this), $query_param_type, $original_query_param
3938
+				)
3939
+			);
3940
+		}
3941
+		//check if this is a special logic query param
3942
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3943
+			if ($allow_logic_query_params) {
3944
+				return;
3945
+			}
3946
+			throw new EE_Error(
3947
+				sprintf(
3948
+					__(
3949
+						'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',
3950
+						'event_espresso'
3951
+					),
3952
+					implode('", "', $this->_logic_query_param_keys),
3953
+					$query_param,
3954
+					get_class($this),
3955
+					'<br />',
3956
+					"\t"
3957
+					. ' $passed_in_query_info = <pre>'
3958
+					. print_r($passed_in_query_info, true)
3959
+					. '</pre>'
3960
+					. "\n\t"
3961
+					. ' $query_param_type = '
3962
+					. $query_param_type
3963
+					. "\n\t"
3964
+					. ' $original_query_param = '
3965
+					. $original_query_param
3966
+				)
3967
+			);
3968
+		}
3969
+		//check if it's a custom selection
3970
+		if ($this->_custom_selections instanceof CustomSelects
3971
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
3972
+		) {
3973
+			return;
3974
+		}
3975
+		//check if has a model name at the beginning
3976
+		//and
3977
+		//check if it's a field on a related model
3978
+		if ($this->extractJoinModelFromQueryParams(
3979
+			$passed_in_query_info,
3980
+			$query_param,
3981
+			$original_query_param,
3982
+			$query_param_type
3983
+		)) {
3984
+			return;
3985
+		}
3986
+
3987
+		//ok so $query_param didn't start with a model name
3988
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3989
+		//it's wack, that's what it is
3990
+		throw new EE_Error(
3991
+			sprintf(
3992
+				esc_html__(
3993
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3994
+					"event_espresso"
3995
+				),
3996
+				$query_param,
3997
+				get_class($this),
3998
+				$query_param_type,
3999
+				$original_query_param
4000
+			)
4001
+		);
4002
+	}
4003
+
4004
+
4005
+	/**
4006
+	 * Extracts any possible join model information from the provided possible_join_string.
4007
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4008
+	 * parts that should be added to the query.
4009
+	 *
4010
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4011
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4012
+	 * @param null|string                 $original_query_param
4013
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4014
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4015
+	 * @return bool  returns true if a join was added and false if not.
4016
+	 * @throws EE_Error
4017
+	 */
4018
+	private function extractJoinModelFromQueryParams(
4019
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4020
+		$possible_join_string,
4021
+		$original_query_param,
4022
+		$query_parameter_type
4023
+	) {
4024
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4025
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4026
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4027
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4028
+				if ($possible_join_string === '') {
4029
+					//nothing left to $query_param
4030
+					//we should actually end in a field name, not a model like this!
4031
+					throw new EE_Error(
4032
+						sprintf(
4033
+							esc_html__(
4034
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4035
+								"event_espresso"
4036
+							),
4037
+							$possible_join_string,
4038
+							$query_parameter_type,
4039
+							get_class($this),
4040
+							$valid_related_model_name
4041
+						)
4042
+					);
4043
+				}
4044
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4045
+				$related_model_obj->_extract_related_model_info_from_query_param(
4046
+					$possible_join_string,
4047
+					$query_info_carrier,
4048
+					$query_parameter_type,
4049
+					$original_query_param
4050
+				);
4051
+				return true;
4052
+			}
4053
+			if ($possible_join_string === $valid_related_model_name) {
4054
+				$this->_add_join_to_model(
4055
+					$valid_related_model_name,
4056
+					$query_info_carrier,
4057
+					$original_query_param
4058
+				);
4059
+				return true;
4060
+			}
4061
+		}
4062
+		return false;
4063
+	}
4064
+
4065
+
4066
+	/**
4067
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4068
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4069
+	 * @throws EE_Error
4070
+	 */
4071
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4072
+	{
4073
+		if ($this->_custom_selections instanceof CustomSelects
4074
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4075
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4076
+			)
4077
+		) {
4078
+			$original_selects = $this->_custom_selections->originalSelects();
4079
+			foreach ($original_selects as $alias => $select_configuration) {
4080
+				$this->extractJoinModelFromQueryParams(
4081
+					$query_info_carrier,
4082
+					$select_configuration[0],
4083
+					$select_configuration[0],
4084
+					'custom_selects'
4085
+				);
4086
+			}
4087
+		}
4088
+	}
4089
+
4090
+
4091
+
4092
+	/**
4093
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4094
+	 * and store it on $passed_in_query_info
4095
+	 *
4096
+	 * @param string                      $model_name
4097
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4098
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4099
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4100
+	 *                                                          and are adding a join to 'Payment' with the original
4101
+	 *                                                          query param key
4102
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4103
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4104
+	 *                                                          Payment wants to add default query params so that it
4105
+	 *                                                          will know what models to prepend onto its default query
4106
+	 *                                                          params or in case it wants to rename tables (in case
4107
+	 *                                                          there are multiple joins to the same table)
4108
+	 * @return void
4109
+	 * @throws EE_Error
4110
+	 */
4111
+	private function _add_join_to_model(
4112
+		$model_name,
4113
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4114
+		$original_query_param
4115
+	) {
4116
+		$relation_obj = $this->related_settings_for($model_name);
4117
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4118
+		//check if the relation is HABTM, because then we're essentially doing two joins
4119
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
4120
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4121
+			$join_model_obj = $relation_obj->get_join_model();
4122
+			//replace the model specified with the join model for this relation chain, whi
4123
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4124
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
4125
+			$passed_in_query_info->merge(
4126
+				new EE_Model_Query_Info_Carrier(
4127
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4128
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4129
+				)
4130
+			);
4131
+		}
4132
+		//now just join to the other table pointed to by the relation object, and add its data types
4133
+		$passed_in_query_info->merge(
4134
+			new EE_Model_Query_Info_Carrier(
4135
+				array($model_relation_chain => $model_name),
4136
+				$relation_obj->get_join_statement($model_relation_chain)
4137
+			)
4138
+		);
4139
+	}
4140
+
4141
+
4142
+
4143
+	/**
4144
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4145
+	 *
4146
+	 * @param array $where_params like EEM_Base::get_all
4147
+	 * @return string of SQL
4148
+	 * @throws EE_Error
4149
+	 */
4150
+	private function _construct_where_clause($where_params)
4151
+	{
4152
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4153
+		if ($SQL) {
4154
+			return " WHERE " . $SQL;
4155
+		}
4156
+		return '';
4157
+	}
4158
+
4159
+
4160
+
4161
+	/**
4162
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4163
+	 * and should be passed HAVING parameters, not WHERE parameters
4164
+	 *
4165
+	 * @param array $having_params
4166
+	 * @return string
4167
+	 * @throws EE_Error
4168
+	 */
4169
+	private function _construct_having_clause($having_params)
4170
+	{
4171
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4172
+		if ($SQL) {
4173
+			return " HAVING " . $SQL;
4174
+		}
4175
+		return '';
4176
+	}
4177
+
4178
+
4179
+	/**
4180
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4181
+	 * Event_Meta.meta_value = 'foo'))"
4182
+	 *
4183
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4184
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4185
+	 * @throws EE_Error
4186
+	 * @return string of SQL
4187
+	 */
4188
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4189
+	{
4190
+		$where_clauses = array();
4191
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4192
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4193
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4194
+				switch ($query_param) {
4195
+					case 'not':
4196
+					case 'NOT':
4197
+						$where_clauses[] = "! ("
4198
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4199
+								$glue)
4200
+										   . ")";
4201
+						break;
4202
+					case 'and':
4203
+					case 'AND':
4204
+						$where_clauses[] = " ("
4205
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4206
+								' AND ')
4207
+										   . ")";
4208
+						break;
4209
+					case 'or':
4210
+					case 'OR':
4211
+						$where_clauses[] = " ("
4212
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4213
+								' OR ')
4214
+										   . ")";
4215
+						break;
4216
+				}
4217
+			} else {
4218
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4219
+				//if it's not a normal field, maybe it's a custom selection?
4220
+				if (! $field_obj) {
4221
+					if ($this->_custom_selections instanceof CustomSelects) {
4222
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4223
+					} else {
4224
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4225
+							"event_espresso"), $query_param));
4226
+					}
4227
+				}
4228
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4229
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4230
+			}
4231
+		}
4232
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4233
+	}
4234
+
4235
+
4236
+
4237
+	/**
4238
+	 * Takes the input parameter and extract the table name (alias) and column name
4239
+	 *
4240
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4241
+	 * @throws EE_Error
4242
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4243
+	 */
4244
+	private function _deduce_column_name_from_query_param($query_param)
4245
+	{
4246
+		$field = $this->_deduce_field_from_query_param($query_param);
4247
+		if ($field) {
4248
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4249
+				$query_param);
4250
+			return $table_alias_prefix . $field->get_qualified_column();
4251
+		}
4252
+		if ($this->_custom_selections instanceof CustomSelects
4253
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4254
+		) {
4255
+			//maybe it's custom selection item?
4256
+			//if so, just use it as the "column name"
4257
+			return $query_param;
4258
+		}
4259
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4260
+			? implode(',', $this->_custom_selections->columnAliases())
4261
+			: '';
4262
+		throw new EE_Error(
4263
+			sprintf(
4264
+				__(
4265
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4266
+					"event_espresso"
4267
+				), $query_param, $custom_select_aliases
4268
+			)
4269
+		);
4270
+	}
4271
+
4272
+
4273
+
4274
+	/**
4275
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4276
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4277
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4278
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4279
+	 *
4280
+	 * @param string $condition_query_param_key
4281
+	 * @return string
4282
+	 */
4283
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4284
+	{
4285
+		$pos_of_star = strpos($condition_query_param_key, '*');
4286
+		if ($pos_of_star === false) {
4287
+			return $condition_query_param_key;
4288
+		}
4289
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4290
+		return $condition_query_param_sans_star;
4291
+	}
4292
+
4293
+
4294
+
4295
+	/**
4296
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4297
+	 *
4298
+	 * @param                            mixed      array | string    $op_and_value
4299
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4300
+	 * @throws EE_Error
4301
+	 * @return string
4302
+	 */
4303
+	private function _construct_op_and_value($op_and_value, $field_obj)
4304
+	{
4305
+		if (is_array($op_and_value)) {
4306
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4307
+			if (! $operator) {
4308
+				$php_array_like_string = array();
4309
+				foreach ($op_and_value as $key => $value) {
4310
+					$php_array_like_string[] = "$key=>$value";
4311
+				}
4312
+				throw new EE_Error(
4313
+					sprintf(
4314
+						__(
4315
+							"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))",
4316
+							"event_espresso"
4317
+						),
4318
+						implode(",", $php_array_like_string)
4319
+					)
4320
+				);
4321
+			}
4322
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4323
+		} else {
4324
+			$operator = '=';
4325
+			$value = $op_and_value;
4326
+		}
4327
+		//check to see if the value is actually another field
4328
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4329
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4330
+		}
4331
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4332
+			//in this case, the value should be an array, or at least a comma-separated list
4333
+			//it will need to handle a little differently
4334
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4335
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4336
+			return $operator . SP . $cleaned_value;
4337
+		}
4338
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4339
+			//the value should be an array with count of two.
4340
+			if (count($value) !== 2) {
4341
+				throw new EE_Error(
4342
+					sprintf(
4343
+						__(
4344
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4345
+							'event_espresso'
4346
+						),
4347
+						"BETWEEN"
4348
+					)
4349
+				);
4350
+			}
4351
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4352
+			return $operator . SP . $cleaned_value;
4353
+		}
4354
+		if (in_array($operator, $this->valid_null_style_operators())) {
4355
+			if ($value !== null) {
4356
+				throw new EE_Error(
4357
+					sprintf(
4358
+						__(
4359
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4360
+							"event_espresso"
4361
+						),
4362
+						$value,
4363
+						$operator
4364
+					)
4365
+				);
4366
+			}
4367
+			return $operator;
4368
+		}
4369
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4370
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4371
+			//remove other junk. So just treat it as a string.
4372
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4373
+		}
4374
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4375
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4376
+		}
4377
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4378
+			throw new EE_Error(
4379
+				sprintf(
4380
+					__(
4381
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4382
+						'event_espresso'
4383
+					),
4384
+					$operator,
4385
+					$operator
4386
+				)
4387
+			);
4388
+		}
4389
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4390
+			throw new EE_Error(
4391
+				sprintf(
4392
+					__(
4393
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4394
+						'event_espresso'
4395
+					),
4396
+					$operator,
4397
+					$operator
4398
+				)
4399
+			);
4400
+		}
4401
+		throw new EE_Error(
4402
+			sprintf(
4403
+				__(
4404
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4405
+					"event_espresso"
4406
+				),
4407
+				http_build_query($op_and_value)
4408
+			)
4409
+		);
4410
+	}
4411
+
4412
+
4413
+
4414
+	/**
4415
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4416
+	 *
4417
+	 * @param array                      $values
4418
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4419
+	 *                                              '%s'
4420
+	 * @return string
4421
+	 * @throws EE_Error
4422
+	 */
4423
+	public function _construct_between_value($values, $field_obj)
4424
+	{
4425
+		$cleaned_values = array();
4426
+		foreach ($values as $value) {
4427
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4428
+		}
4429
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4430
+	}
4431
+
4432
+
4433
+
4434
+	/**
4435
+	 * Takes an array or a comma-separated list of $values and cleans them
4436
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4437
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4438
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4439
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4440
+	 *
4441
+	 * @param mixed                      $values    array or comma-separated string
4442
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4443
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4444
+	 * @throws EE_Error
4445
+	 */
4446
+	public function _construct_in_value($values, $field_obj)
4447
+	{
4448
+		//check if the value is a CSV list
4449
+		if (is_string($values)) {
4450
+			//in which case, turn it into an array
4451
+			$values = explode(",", $values);
4452
+		}
4453
+		$cleaned_values = array();
4454
+		foreach ($values as $value) {
4455
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4456
+		}
4457
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4458
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4459
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4460
+		if (empty($cleaned_values)) {
4461
+			$all_fields = $this->field_settings();
4462
+			$a_field = array_shift($all_fields);
4463
+			$main_table = $this->_get_main_table();
4464
+			$cleaned_values[] = "SELECT "
4465
+								. $a_field->get_table_column()
4466
+								. " FROM "
4467
+								. $main_table->get_table_name()
4468
+								. " WHERE FALSE";
4469
+		}
4470
+		return "(" . implode(",", $cleaned_values) . ")";
4471
+	}
4472
+
4473
+
4474
+
4475
+	/**
4476
+	 * @param mixed                      $value
4477
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4478
+	 * @throws EE_Error
4479
+	 * @return false|null|string
4480
+	 */
4481
+	private function _wpdb_prepare_using_field($value, $field_obj)
4482
+	{
4483
+		/** @type WPDB $wpdb */
4484
+		global $wpdb;
4485
+		if ($field_obj instanceof EE_Model_Field_Base) {
4486
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4487
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4488
+		} //$field_obj should really just be a data type
4489
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4490
+			throw new EE_Error(
4491
+				sprintf(
4492
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4493
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)
4494
+				)
4495
+			);
4496
+		}
4497
+		return $wpdb->prepare($field_obj, $value);
4498
+	}
4499
+
4500
+
4501
+
4502
+	/**
4503
+	 * Takes the input parameter and finds the model field that it indicates.
4504
+	 *
4505
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4506
+	 * @throws EE_Error
4507
+	 * @return EE_Model_Field_Base
4508
+	 */
4509
+	protected function _deduce_field_from_query_param($query_param_name)
4510
+	{
4511
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4512
+		//which will help us find the database table and column
4513
+		$query_param_parts = explode(".", $query_param_name);
4514
+		if (empty($query_param_parts)) {
4515
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4516
+				'event_espresso'), $query_param_name));
4517
+		}
4518
+		$number_of_parts = count($query_param_parts);
4519
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4520
+		if ($number_of_parts === 1) {
4521
+			$field_name = $last_query_param_part;
4522
+			$model_obj = $this;
4523
+		} else {// $number_of_parts >= 2
4524
+			//the last part is the column name, and there are only 2parts. therefore...
4525
+			$field_name = $last_query_param_part;
4526
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4527
+		}
4528
+		try {
4529
+			return $model_obj->field_settings_for($field_name);
4530
+		} catch (EE_Error $e) {
4531
+			return null;
4532
+		}
4533
+	}
4534
+
4535
+
4536
+
4537
+	/**
4538
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4539
+	 * alias and column which corresponds to it
4540
+	 *
4541
+	 * @param string $field_name
4542
+	 * @throws EE_Error
4543
+	 * @return string
4544
+	 */
4545
+	public function _get_qualified_column_for_field($field_name)
4546
+	{
4547
+		$all_fields = $this->field_settings();
4548
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4549
+		if ($field) {
4550
+			return $field->get_qualified_column();
4551
+		}
4552
+		throw new EE_Error(
4553
+			sprintf(
4554
+				__(
4555
+					"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.",
4556
+					'event_espresso'
4557
+				), $field_name, get_class($this)
4558
+			)
4559
+		);
4560
+	}
4561
+
4562
+
4563
+
4564
+	/**
4565
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4566
+	 * Example usage:
4567
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4568
+	 *      array(),
4569
+	 *      ARRAY_A,
4570
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4571
+	 *  );
4572
+	 * is equivalent to
4573
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4574
+	 * and
4575
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4576
+	 *      array(
4577
+	 *          array(
4578
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4579
+	 *          ),
4580
+	 *          ARRAY_A,
4581
+	 *          implode(
4582
+	 *              ', ',
4583
+	 *              array_merge(
4584
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4585
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4586
+	 *              )
4587
+	 *          )
4588
+	 *      )
4589
+	 *  );
4590
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4591
+	 *
4592
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4593
+	 *                                            and the one whose fields you are selecting for example: when querying
4594
+	 *                                            tickets model and selecting fields from the tickets model you would
4595
+	 *                                            leave this parameter empty, because no models are needed to join
4596
+	 *                                            between the queried model and the selected one. Likewise when
4597
+	 *                                            querying the datetime model and selecting fields from the tickets
4598
+	 *                                            model, it would also be left empty, because there is a direct
4599
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4600
+	 *                                            them together. However, when querying from the event model and
4601
+	 *                                            selecting fields from the ticket model, you should provide the string
4602
+	 *                                            'Datetime', indicating that the event model must first join to the
4603
+	 *                                            datetime model in order to find its relation to ticket model.
4604
+	 *                                            Also, when querying from the venue model and selecting fields from
4605
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4606
+	 *                                            indicating you need to join the venue model to the event model,
4607
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4608
+	 *                                            This string is used to deduce the prefix that gets added onto the
4609
+	 *                                            models' tables qualified columns
4610
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4611
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4612
+	 *                                            qualified column names
4613
+	 * @return array|string
4614
+	 */
4615
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4616
+	{
4617
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4618
+		$qualified_columns = array();
4619
+		foreach ($this->field_settings() as $field_name => $field) {
4620
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4621
+		}
4622
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4623
+	}
4624
+
4625
+
4626
+
4627
+	/**
4628
+	 * constructs the select use on special limit joins
4629
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4630
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4631
+	 * (as that is typically where the limits would be set).
4632
+	 *
4633
+	 * @param  string       $table_alias The table the select is being built for
4634
+	 * @param  mixed|string $limit       The limit for this select
4635
+	 * @return string                The final select join element for the query.
4636
+	 */
4637
+	public function _construct_limit_join_select($table_alias, $limit)
4638
+	{
4639
+		$SQL = '';
4640
+		foreach ($this->_tables as $table_obj) {
4641
+			if ($table_obj instanceof EE_Primary_Table) {
4642
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4643
+					? $table_obj->get_select_join_limit($limit)
4644
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4645
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4646
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4647
+					? $table_obj->get_select_join_limit_join($limit)
4648
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4649
+			}
4650
+		}
4651
+		return $SQL;
4652
+	}
4653
+
4654
+
4655
+
4656
+	/**
4657
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4658
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4659
+	 *
4660
+	 * @return string SQL
4661
+	 * @throws EE_Error
4662
+	 */
4663
+	public function _construct_internal_join()
4664
+	{
4665
+		$SQL = $this->_get_main_table()->get_table_sql();
4666
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4667
+		return $SQL;
4668
+	}
4669
+
4670
+
4671
+
4672
+	/**
4673
+	 * Constructs the SQL for joining all the tables on this model.
4674
+	 * Normally $alias should be the primary table's alias, but in cases where
4675
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4676
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4677
+	 * alias, this will construct SQL like:
4678
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4679
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4680
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4681
+	 *
4682
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4683
+	 * @return string
4684
+	 */
4685
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4686
+	{
4687
+		$SQL = '';
4688
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4689
+		foreach ($this->_tables as $table_obj) {
4690
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4691
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4692
+					//so we're joining to this table, meaning the table is already in
4693
+					//the FROM statement, BUT the primary table isn't. So we want
4694
+					//to add the inverse join sql
4695
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4696
+				} else {
4697
+					//just add a regular JOIN to this table from the primary table
4698
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4699
+				}
4700
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4701
+		}
4702
+		return $SQL;
4703
+	}
4704
+
4705
+
4706
+
4707
+	/**
4708
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4709
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4710
+	 * their data type (eg, '%s', '%d', etc)
4711
+	 *
4712
+	 * @return array
4713
+	 */
4714
+	public function _get_data_types()
4715
+	{
4716
+		$data_types = array();
4717
+		foreach ($this->field_settings() as $field_obj) {
4718
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4719
+			/** @var $field_obj EE_Model_Field_Base */
4720
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4721
+		}
4722
+		return $data_types;
4723
+	}
4724
+
4725
+
4726
+
4727
+	/**
4728
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4729
+	 *
4730
+	 * @param string $model_name
4731
+	 * @throws EE_Error
4732
+	 * @return EEM_Base
4733
+	 */
4734
+	public function get_related_model_obj($model_name)
4735
+	{
4736
+		$model_classname = "EEM_" . $model_name;
4737
+		if (! class_exists($model_classname)) {
4738
+			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4739
+				'event_espresso'), $model_name, $model_classname));
4740
+		}
4741
+		return call_user_func($model_classname . "::instance");
4742
+	}
4743
+
4744
+
4745
+
4746
+	/**
4747
+	 * Returns the array of EE_ModelRelations for this model.
4748
+	 *
4749
+	 * @return EE_Model_Relation_Base[]
4750
+	 */
4751
+	public function relation_settings()
4752
+	{
4753
+		return $this->_model_relations;
4754
+	}
4755
+
4756
+
4757
+
4758
+	/**
4759
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4760
+	 * because without THOSE models, this model probably doesn't have much purpose.
4761
+	 * (Eg, without an event, datetimes have little purpose.)
4762
+	 *
4763
+	 * @return EE_Belongs_To_Relation[]
4764
+	 */
4765
+	public function belongs_to_relations()
4766
+	{
4767
+		$belongs_to_relations = array();
4768
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4769
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4770
+				$belongs_to_relations[$model_name] = $relation_obj;
4771
+			}
4772
+		}
4773
+		return $belongs_to_relations;
4774
+	}
4775
+
4776
+
4777
+
4778
+	/**
4779
+	 * Returns the specified EE_Model_Relation, or throws an exception
4780
+	 *
4781
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4782
+	 * @throws EE_Error
4783
+	 * @return EE_Model_Relation_Base
4784
+	 */
4785
+	public function related_settings_for($relation_name)
4786
+	{
4787
+		$relatedModels = $this->relation_settings();
4788
+		if (! array_key_exists($relation_name, $relatedModels)) {
4789
+			throw new EE_Error(
4790
+				sprintf(
4791
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4792
+						'event_espresso'),
4793
+					$relation_name,
4794
+					$this->_get_class_name(),
4795
+					implode(', ', array_keys($relatedModels))
4796
+				)
4797
+			);
4798
+		}
4799
+		return $relatedModels[$relation_name];
4800
+	}
4801
+
4802
+
4803
+
4804
+	/**
4805
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4806
+	 * fields
4807
+	 *
4808
+	 * @param string $fieldName
4809
+	 * @param boolean $include_db_only_fields
4810
+	 * @throws EE_Error
4811
+	 * @return EE_Model_Field_Base
4812
+	 */
4813
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4814
+	{
4815
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4816
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4817
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4818
+				get_class($this)));
4819
+		}
4820
+		return $fieldSettings[$fieldName];
4821
+	}
4822
+
4823
+
4824
+
4825
+	/**
4826
+	 * Checks if this field exists on this model
4827
+	 *
4828
+	 * @param string $fieldName a key in the model's _field_settings array
4829
+	 * @return boolean
4830
+	 */
4831
+	public function has_field($fieldName)
4832
+	{
4833
+		$fieldSettings = $this->field_settings(true);
4834
+		if (isset($fieldSettings[$fieldName])) {
4835
+			return true;
4836
+		}
4837
+		return false;
4838
+	}
4839
+
4840
+
4841
+
4842
+	/**
4843
+	 * Returns whether or not this model has a relation to the specified model
4844
+	 *
4845
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4846
+	 * @return boolean
4847
+	 */
4848
+	public function has_relation($relation_name)
4849
+	{
4850
+		$relations = $this->relation_settings();
4851
+		if (isset($relations[$relation_name])) {
4852
+			return true;
4853
+		}
4854
+		return false;
4855
+	}
4856
+
4857
+
4858
+
4859
+	/**
4860
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4861
+	 * Eg, on EE_Answer that would be ANS_ID field object
4862
+	 *
4863
+	 * @param $field_obj
4864
+	 * @return boolean
4865
+	 */
4866
+	public function is_primary_key_field($field_obj)
4867
+	{
4868
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4869
+	}
4870
+
4871
+
4872
+
4873
+	/**
4874
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4875
+	 * Eg, on EE_Answer that would be ANS_ID field object
4876
+	 *
4877
+	 * @return EE_Model_Field_Base
4878
+	 * @throws EE_Error
4879
+	 */
4880
+	public function get_primary_key_field()
4881
+	{
4882
+		if ($this->_primary_key_field === null) {
4883
+			foreach ($this->field_settings(true) as $field_obj) {
4884
+				if ($this->is_primary_key_field($field_obj)) {
4885
+					$this->_primary_key_field = $field_obj;
4886
+					break;
4887
+				}
4888
+			}
4889
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4890
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4891
+					get_class($this)));
4892
+			}
4893
+		}
4894
+		return $this->_primary_key_field;
4895
+	}
4896
+
4897
+
4898
+
4899
+	/**
4900
+	 * Returns whether or not not there is a primary key on this model.
4901
+	 * Internally does some caching.
4902
+	 *
4903
+	 * @return boolean
4904
+	 */
4905
+	public function has_primary_key_field()
4906
+	{
4907
+		if ($this->_has_primary_key_field === null) {
4908
+			try {
4909
+				$this->get_primary_key_field();
4910
+				$this->_has_primary_key_field = true;
4911
+			} catch (EE_Error $e) {
4912
+				$this->_has_primary_key_field = false;
4913
+			}
4914
+		}
4915
+		return $this->_has_primary_key_field;
4916
+	}
4917
+
4918
+
4919
+
4920
+	/**
4921
+	 * Finds the first field of type $field_class_name.
4922
+	 *
4923
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4924
+	 *                                 EE_Foreign_Key_Field, etc
4925
+	 * @return EE_Model_Field_Base or null if none is found
4926
+	 */
4927
+	public function get_a_field_of_type($field_class_name)
4928
+	{
4929
+		foreach ($this->field_settings() as $field) {
4930
+			if ($field instanceof $field_class_name) {
4931
+				return $field;
4932
+			}
4933
+		}
4934
+		return null;
4935
+	}
4936
+
4937
+
4938
+
4939
+	/**
4940
+	 * Gets a foreign key field pointing to model.
4941
+	 *
4942
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4943
+	 * @return EE_Foreign_Key_Field_Base
4944
+	 * @throws EE_Error
4945
+	 */
4946
+	public function get_foreign_key_to($model_name)
4947
+	{
4948
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4949
+			foreach ($this->field_settings() as $field) {
4950
+				if (
4951
+					$field instanceof EE_Foreign_Key_Field_Base
4952
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4953
+				) {
4954
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4955
+					break;
4956
+				}
4957
+			}
4958
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4959
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4960
+					'event_espresso'), $model_name, get_class($this)));
4961
+			}
4962
+		}
4963
+		return $this->_cache_foreign_key_to_fields[$model_name];
4964
+	}
4965
+
4966
+
4967
+
4968
+	/**
4969
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4970
+	 *
4971
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4972
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4973
+	 *                            Either one works
4974
+	 * @return string
4975
+	 */
4976
+	public function get_table_for_alias($table_alias)
4977
+	{
4978
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4979
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4980
+	}
4981
+
4982
+
4983
+
4984
+	/**
4985
+	 * Returns a flat array of all field son this model, instead of organizing them
4986
+	 * by table_alias as they are in the constructor.
4987
+	 *
4988
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4989
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4990
+	 */
4991
+	public function field_settings($include_db_only_fields = false)
4992
+	{
4993
+		if ($include_db_only_fields) {
4994
+			if ($this->_cached_fields === null) {
4995
+				$this->_cached_fields = array();
4996
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4997
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4998
+						$this->_cached_fields[$field_name] = $field_obj;
4999
+					}
5000
+				}
5001
+			}
5002
+			return $this->_cached_fields;
5003
+		}
5004
+		if ($this->_cached_fields_non_db_only === null) {
5005
+			$this->_cached_fields_non_db_only = array();
5006
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5007
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5008
+					/** @var $field_obj EE_Model_Field_Base */
5009
+					if (! $field_obj->is_db_only_field()) {
5010
+						$this->_cached_fields_non_db_only[$field_name] = $field_obj;
5011
+					}
5012
+				}
5013
+			}
5014
+		}
5015
+		return $this->_cached_fields_non_db_only;
5016
+	}
5017
+
5018
+
5019
+
5020
+	/**
5021
+	 *        cycle though array of attendees and create objects out of each item
5022
+	 *
5023
+	 * @access        private
5024
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5025
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5026
+	 *                           numerically indexed)
5027
+	 * @throws EE_Error
5028
+	 */
5029
+	protected function _create_objects($rows = array())
5030
+	{
5031
+		$array_of_objects = array();
5032
+		if (empty($rows)) {
5033
+			return array();
5034
+		}
5035
+		$count_if_model_has_no_primary_key = 0;
5036
+		$has_primary_key = $this->has_primary_key_field();
5037
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5038
+		foreach ((array)$rows as $row) {
5039
+			if (empty($row)) {
5040
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5041
+				return array();
5042
+			}
5043
+			//check if we've already set this object in the results array,
5044
+			//in which case there's no need to process it further (again)
5045
+			if ($has_primary_key) {
5046
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5047
+					$row,
5048
+					$primary_key_field->get_qualified_column(),
5049
+					$primary_key_field->get_table_column()
5050
+				);
5051
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5052
+					continue;
5053
+				}
5054
+			}
5055
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5056
+			if (! $classInstance) {
5057
+				throw new EE_Error(
5058
+					sprintf(
5059
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5060
+						$this->get_this_model_name(),
5061
+						http_build_query($row)
5062
+					)
5063
+				);
5064
+			}
5065
+			//set the timezone on the instantiated objects
5066
+			$classInstance->set_timezone($this->_timezone);
5067
+			//make sure if there is any timezone setting present that we set the timezone for the object
5068
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5069
+			$array_of_objects[$key] = $classInstance;
5070
+			//also, for all the relations of type BelongsTo, see if we can cache
5071
+			//those related models
5072
+			//(we could do this for other relations too, but if there are conditions
5073
+			//that filtered out some fo the results, then we'd be caching an incomplete set
5074
+			//so it requires a little more thought than just caching them immediately...)
5075
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5076
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5077
+					//check if this model's INFO is present. If so, cache it on the model
5078
+					$other_model = $relation_obj->get_other_model();
5079
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5080
+					//if we managed to make a model object from the results, cache it on the main model object
5081
+					if ($other_model_obj_maybe) {
5082
+						//set timezone on these other model objects if they are present
5083
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5084
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5085
+					}
5086
+				}
5087
+			}
5088
+			//also, if this was a custom select query, let's see if there are any results for the custom select fields
5089
+			//and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5090
+			//the field in the CustomSelects object
5091
+			if ($this->_custom_selections instanceof CustomSelects) {
5092
+				$classInstance->setCustomSelectsValues(
5093
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5094
+				);
5095
+			}
5096
+		}
5097
+		return $array_of_objects;
5098
+	}
5099
+
5100
+
5101
+	/**
5102
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5103
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5104
+	 *
5105
+	 * @param array $db_results_row
5106
+	 * @return array
5107
+	 */
5108
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5109
+	{
5110
+		$results = array();
5111
+		if ($this->_custom_selections instanceof CustomSelects) {
5112
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5113
+				if (isset($db_results_row[$alias])) {
5114
+					$results[$alias] = $this->convertValueToDataType(
5115
+						$db_results_row[$alias],
5116
+						$this->_custom_selections->getDataTypeForAlias($alias)
5117
+					);
5118
+				}
5119
+			}
5120
+		}
5121
+		return $results;
5122
+	}
5123
+
5124
+
5125
+	/**
5126
+	 * This will set the value for the given alias
5127
+	 * @param string $value
5128
+	 * @param string $datatype (one of %d, %s, %f)
5129
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5130
+	 */
5131
+	protected function convertValueToDataType($value, $datatype)
5132
+	{
5133
+		switch ($datatype) {
5134
+			case '%f':
5135
+				return (float) $value;
5136
+			case '%d':
5137
+				return (int) $value;
5138
+			default:
5139
+				return (string) $value;
5140
+		}
5141
+	}
5142
+
5143
+
5144
+	/**
5145
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5146
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5147
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5148
+	 * object (as set in the model_field!).
5149
+	 *
5150
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5151
+	 */
5152
+	public function create_default_object()
5153
+	{
5154
+		$this_model_fields_and_values = array();
5155
+		//setup the row using default values;
5156
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5157
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5158
+		}
5159
+		$className = $this->_get_class_name();
5160
+		$classInstance = EE_Registry::instance()
5161
+									->load_class($className, array($this_model_fields_and_values), false, false);
5162
+		return $classInstance;
5163
+	}
5164
+
5165
+
5166
+
5167
+	/**
5168
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5169
+	 *                             or an stdClass where each property is the name of a column,
5170
+	 * @return EE_Base_Class
5171
+	 * @throws EE_Error
5172
+	 */
5173
+	public function instantiate_class_from_array_or_object($cols_n_values)
5174
+	{
5175
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5176
+			$cols_n_values = get_object_vars($cols_n_values);
5177
+		}
5178
+		$primary_key = null;
5179
+		//make sure the array only has keys that are fields/columns on this model
5180
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5181
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5182
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5183
+		}
5184
+		$className = $this->_get_class_name();
5185
+		//check we actually found results that we can use to build our model object
5186
+		//if not, return null
5187
+		if ($this->has_primary_key_field()) {
5188
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5189
+				return null;
5190
+			}
5191
+		} else if ($this->unique_indexes()) {
5192
+			$first_column = reset($this_model_fields_n_values);
5193
+			if (empty($first_column)) {
5194
+				return null;
5195
+			}
5196
+		}
5197
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5198
+		if ($primary_key) {
5199
+			$classInstance = $this->get_from_entity_map($primary_key);
5200
+			if (! $classInstance) {
5201
+				$classInstance = EE_Registry::instance()
5202
+											->load_class($className,
5203
+												array($this_model_fields_n_values, $this->_timezone), true, false);
5204
+				// add this new object to the entity map
5205
+				$classInstance = $this->add_to_entity_map($classInstance);
5206
+			}
5207
+		} else {
5208
+			$classInstance = EE_Registry::instance()
5209
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5210
+											true, false);
5211
+		}
5212
+		return $classInstance;
5213
+	}
5214
+
5215
+
5216
+
5217
+	/**
5218
+	 * Gets the model object from the  entity map if it exists
5219
+	 *
5220
+	 * @param int|string $id the ID of the model object
5221
+	 * @return EE_Base_Class
5222
+	 */
5223
+	public function get_from_entity_map($id)
5224
+	{
5225
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5226
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5227
+	}
5228
+
5229
+
5230
+
5231
+	/**
5232
+	 * add_to_entity_map
5233
+	 * Adds the object to the model's entity mappings
5234
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5235
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5236
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5237
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5238
+	 *        then this method should be called immediately after the update query
5239
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5240
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5241
+	 *
5242
+	 * @param    EE_Base_Class $object
5243
+	 * @throws EE_Error
5244
+	 * @return \EE_Base_Class
5245
+	 */
5246
+	public function add_to_entity_map(EE_Base_Class $object)
5247
+	{
5248
+		$className = $this->_get_class_name();
5249
+		if (! $object instanceof $className) {
5250
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5251
+				is_object($object) ? get_class($object) : $object, $className));
5252
+		}
5253
+		/** @var $object EE_Base_Class */
5254
+		if (! $object->ID()) {
5255
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5256
+				"event_espresso"), get_class($this)));
5257
+		}
5258
+		// double check it's not already there
5259
+		$classInstance = $this->get_from_entity_map($object->ID());
5260
+		if ($classInstance) {
5261
+			return $classInstance;
5262
+		}
5263
+		$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5264
+		return $object;
5265
+	}
5266
+
5267
+
5268
+
5269
+	/**
5270
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5271
+	 * if no identifier is provided, then the entire entity map is emptied
5272
+	 *
5273
+	 * @param int|string $id the ID of the model object
5274
+	 * @return boolean
5275
+	 */
5276
+	public function clear_entity_map($id = null)
5277
+	{
5278
+		if (empty($id)) {
5279
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5280
+			return true;
5281
+		}
5282
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5283
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5284
+			return true;
5285
+		}
5286
+		return false;
5287
+	}
5288
+
5289
+
5290
+
5291
+	/**
5292
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5293
+	 * Given an array where keys are column (or column alias) names and values,
5294
+	 * returns an array of their corresponding field names and database values
5295
+	 *
5296
+	 * @param array $cols_n_values
5297
+	 * @return array
5298
+	 */
5299
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5300
+	{
5301
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5302
+	}
5303
+
5304
+
5305
+
5306
+	/**
5307
+	 * _deduce_fields_n_values_from_cols_n_values
5308
+	 * Given an array where keys are column (or column alias) names and values,
5309
+	 * returns an array of their corresponding field names and database values
5310
+	 *
5311
+	 * @param string $cols_n_values
5312
+	 * @return array
5313
+	 */
5314
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5315
+	{
5316
+		$this_model_fields_n_values = array();
5317
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5318
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5319
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5320
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5321
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5322
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5323
+					if (! $field_obj->is_db_only_field()) {
5324
+						//prepare field as if its coming from db
5325
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5326
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5327
+					}
5328
+				}
5329
+			} else {
5330
+				//the table's rows existed. Use their values
5331
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5332
+					if (! $field_obj->is_db_only_field()) {
5333
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5334
+							$cols_n_values, $field_obj->get_qualified_column(),
5335
+							$field_obj->get_table_column()
5336
+						);
5337
+					}
5338
+				}
5339
+			}
5340
+		}
5341
+		return $this_model_fields_n_values;
5342
+	}
5343
+
5344
+
5345
+
5346
+	/**
5347
+	 * @param $cols_n_values
5348
+	 * @param $qualified_column
5349
+	 * @param $regular_column
5350
+	 * @return null
5351
+	 */
5352
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5353
+	{
5354
+		$value = null;
5355
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5356
+		//does the field on the model relate to this column retrieved from the db?
5357
+		//or is it a db-only field? (not relating to the model)
5358
+		if (isset($cols_n_values[$qualified_column])) {
5359
+			$value = $cols_n_values[$qualified_column];
5360
+		} elseif (isset($cols_n_values[$regular_column])) {
5361
+			$value = $cols_n_values[$regular_column];
5362
+		}
5363
+		return $value;
5364
+	}
5365
+
5366
+
5367
+
5368
+	/**
5369
+	 * refresh_entity_map_from_db
5370
+	 * Makes sure the model object in the entity map at $id assumes the values
5371
+	 * of the database (opposite of EE_base_Class::save())
5372
+	 *
5373
+	 * @param int|string $id
5374
+	 * @return EE_Base_Class
5375
+	 * @throws EE_Error
5376
+	 */
5377
+	public function refresh_entity_map_from_db($id)
5378
+	{
5379
+		$obj_in_map = $this->get_from_entity_map($id);
5380
+		if ($obj_in_map) {
5381
+			$wpdb_results = $this->_get_all_wpdb_results(
5382
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5383
+			);
5384
+			if ($wpdb_results && is_array($wpdb_results)) {
5385
+				$one_row = reset($wpdb_results);
5386
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5387
+					$obj_in_map->set_from_db($field_name, $db_value);
5388
+				}
5389
+				//clear the cache of related model objects
5390
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5391
+					$obj_in_map->clear_cache($relation_name, null, true);
5392
+				}
5393
+			}
5394
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5395
+			return $obj_in_map;
5396
+		}
5397
+		return $this->get_one_by_ID($id);
5398
+	}
5399
+
5400
+
5401
+
5402
+	/**
5403
+	 * refresh_entity_map_with
5404
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5405
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5406
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5407
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5408
+	 *
5409
+	 * @param int|string    $id
5410
+	 * @param EE_Base_Class $replacing_model_obj
5411
+	 * @return \EE_Base_Class
5412
+	 * @throws EE_Error
5413
+	 */
5414
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5415
+	{
5416
+		$obj_in_map = $this->get_from_entity_map($id);
5417
+		if ($obj_in_map) {
5418
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5419
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5420
+					$obj_in_map->set($field_name, $value);
5421
+				}
5422
+				//make the model object in the entity map's cache match the $replacing_model_obj
5423
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5424
+					$obj_in_map->clear_cache($relation_name, null, true);
5425
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5426
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5427
+					}
5428
+				}
5429
+			}
5430
+			return $obj_in_map;
5431
+		}
5432
+		$this->add_to_entity_map($replacing_model_obj);
5433
+		return $replacing_model_obj;
5434
+	}
5435
+
5436
+
5437
+
5438
+	/**
5439
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5440
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5441
+	 * require_once($this->_getClassName().".class.php");
5442
+	 *
5443
+	 * @return string
5444
+	 */
5445
+	private function _get_class_name()
5446
+	{
5447
+		return "EE_" . $this->get_this_model_name();
5448
+	}
5449
+
5450
+
5451
+
5452
+	/**
5453
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5454
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5455
+	 * it would be 'Events'.
5456
+	 *
5457
+	 * @param int $quantity
5458
+	 * @return string
5459
+	 */
5460
+	public function item_name($quantity = 1)
5461
+	{
5462
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5463
+	}
5464
+
5465
+
5466
+
5467
+	/**
5468
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5469
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5470
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5471
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5472
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5473
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5474
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5475
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5476
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5477
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5478
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5479
+	 *        return $previousReturnValue.$returnString;
5480
+	 * }
5481
+	 * require('EEM_Answer.model.php');
5482
+	 * $answer=EEM_Answer::instance();
5483
+	 * echo $answer->my_callback('monkeys',100);
5484
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5485
+	 *
5486
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5487
+	 * @param array  $args       array of original arguments passed to the function
5488
+	 * @throws EE_Error
5489
+	 * @return mixed whatever the plugin which calls add_filter decides
5490
+	 */
5491
+	public function __call($methodName, $args)
5492
+	{
5493
+		$className = get_class($this);
5494
+		$tagName = "FHEE__{$className}__{$methodName}";
5495
+		if (! has_filter($tagName)) {
5496
+			throw new EE_Error(
5497
+				sprintf(
5498
+					__('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 );',
5499
+						'event_espresso'),
5500
+					$methodName,
5501
+					$className,
5502
+					$tagName,
5503
+					'<br />'
5504
+				)
5505
+			);
5506
+		}
5507
+		return apply_filters($tagName, null, $this, $args);
5508
+	}
5509
+
5510
+
5511
+
5512
+	/**
5513
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5514
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5515
+	 *
5516
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5517
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5518
+	 *                                                       the object's class name
5519
+	 *                                                       or object's ID
5520
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5521
+	 *                                                       exists in the database. If it does not, we add it
5522
+	 * @throws EE_Error
5523
+	 * @return EE_Base_Class
5524
+	 */
5525
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5526
+	{
5527
+		$className = $this->_get_class_name();
5528
+		if ($base_class_obj_or_id instanceof $className) {
5529
+			$model_object = $base_class_obj_or_id;
5530
+		} else {
5531
+			$primary_key_field = $this->get_primary_key_field();
5532
+			if (
5533
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5534
+				&& (
5535
+					is_int($base_class_obj_or_id)
5536
+					|| is_string($base_class_obj_or_id)
5537
+				)
5538
+			) {
5539
+				// assume it's an ID.
5540
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5541
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5542
+			} else if (
5543
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5544
+				&& is_string($base_class_obj_or_id)
5545
+			) {
5546
+				// assume its a string representation of the object
5547
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5548
+			} else {
5549
+				throw new EE_Error(
5550
+					sprintf(
5551
+						__(
5552
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5553
+							'event_espresso'
5554
+						),
5555
+						$base_class_obj_or_id,
5556
+						$this->_get_class_name(),
5557
+						print_r($base_class_obj_or_id, true)
5558
+					)
5559
+				);
5560
+			}
5561
+		}
5562
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5563
+			$model_object->save();
5564
+		}
5565
+		return $model_object;
5566
+	}
5567
+
5568
+
5569
+
5570
+	/**
5571
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5572
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5573
+	 * returns it ID.
5574
+	 *
5575
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5576
+	 * @return int|string depending on the type of this model object's ID
5577
+	 * @throws EE_Error
5578
+	 */
5579
+	public function ensure_is_ID($base_class_obj_or_id)
5580
+	{
5581
+		$className = $this->_get_class_name();
5582
+		if ($base_class_obj_or_id instanceof $className) {
5583
+			/** @var $base_class_obj_or_id EE_Base_Class */
5584
+			$id = $base_class_obj_or_id->ID();
5585
+		} elseif (is_int($base_class_obj_or_id)) {
5586
+			//assume it's an ID
5587
+			$id = $base_class_obj_or_id;
5588
+		} elseif (is_string($base_class_obj_or_id)) {
5589
+			//assume its a string representation of the object
5590
+			$id = $base_class_obj_or_id;
5591
+		} else {
5592
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5593
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5594
+				print_r($base_class_obj_or_id, true)));
5595
+		}
5596
+		return $id;
5597
+	}
5598
+
5599
+
5600
+
5601
+	/**
5602
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5603
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5604
+	 * been sanitized and converted into the appropriate domain.
5605
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5606
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5607
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5608
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5609
+	 * $EVT = EEM_Event::instance(); $old_setting =
5610
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5611
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5612
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5613
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5614
+	 *
5615
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5616
+	 * @return void
5617
+	 */
5618
+	public function assume_values_already_prepared_by_model_object(
5619
+		$values_already_prepared = self::not_prepared_by_model_object
5620
+	) {
5621
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5622
+	}
5623
+
5624
+
5625
+
5626
+	/**
5627
+	 * Read comments for assume_values_already_prepared_by_model_object()
5628
+	 *
5629
+	 * @return int
5630
+	 */
5631
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5632
+	{
5633
+		return $this->_values_already_prepared_by_model_object;
5634
+	}
5635
+
5636
+
5637
+
5638
+	/**
5639
+	 * Gets all the indexes on this model
5640
+	 *
5641
+	 * @return EE_Index[]
5642
+	 */
5643
+	public function indexes()
5644
+	{
5645
+		return $this->_indexes;
5646
+	}
5647
+
5648
+
5649
+
5650
+	/**
5651
+	 * Gets all the Unique Indexes on this model
5652
+	 *
5653
+	 * @return EE_Unique_Index[]
5654
+	 */
5655
+	public function unique_indexes()
5656
+	{
5657
+		$unique_indexes = array();
5658
+		foreach ($this->_indexes as $name => $index) {
5659
+			if ($index instanceof EE_Unique_Index) {
5660
+				$unique_indexes [$name] = $index;
5661
+			}
5662
+		}
5663
+		return $unique_indexes;
5664
+	}
5665
+
5666
+
5667
+
5668
+	/**
5669
+	 * Gets all the fields which, when combined, make the primary key.
5670
+	 * This is usually just an array with 1 element (the primary key), but in cases
5671
+	 * where there is no primary key, it's a combination of fields as defined
5672
+	 * on a primary index
5673
+	 *
5674
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5675
+	 * @throws EE_Error
5676
+	 */
5677
+	public function get_combined_primary_key_fields()
5678
+	{
5679
+		foreach ($this->indexes() as $index) {
5680
+			if ($index instanceof EE_Primary_Key_Index) {
5681
+				return $index->fields();
5682
+			}
5683
+		}
5684
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5685
+	}
5686
+
5687
+
5688
+
5689
+	/**
5690
+	 * Used to build a primary key string (when the model has no primary key),
5691
+	 * which can be used a unique string to identify this model object.
5692
+	 *
5693
+	 * @param array $cols_n_values keys are field names, values are their values
5694
+	 * @return string
5695
+	 * @throws EE_Error
5696
+	 */
5697
+	public function get_index_primary_key_string($cols_n_values)
5698
+	{
5699
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5700
+			$this->get_combined_primary_key_fields());
5701
+		return http_build_query($cols_n_values_for_primary_key_index);
5702
+	}
5703
+
5704
+
5705
+
5706
+	/**
5707
+	 * Gets the field values from the primary key string
5708
+	 *
5709
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5710
+	 * @param string $index_primary_key_string
5711
+	 * @return null|array
5712
+	 * @throws EE_Error
5713
+	 */
5714
+	public function parse_index_primary_key_string($index_primary_key_string)
5715
+	{
5716
+		$key_fields = $this->get_combined_primary_key_fields();
5717
+		//check all of them are in the $id
5718
+		$key_vals_in_combined_pk = array();
5719
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5720
+		foreach ($key_fields as $key_field_name => $field_obj) {
5721
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5722
+				return null;
5723
+			}
5724
+		}
5725
+		return $key_vals_in_combined_pk;
5726
+	}
5727
+
5728
+
5729
+
5730
+	/**
5731
+	 * verifies that an array of key-value pairs for model fields has a key
5732
+	 * for each field comprising the primary key index
5733
+	 *
5734
+	 * @param array $key_vals
5735
+	 * @return boolean
5736
+	 * @throws EE_Error
5737
+	 */
5738
+	public function has_all_combined_primary_key_fields($key_vals)
5739
+	{
5740
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5741
+		foreach ($keys_it_should_have as $key) {
5742
+			if (! isset($key_vals[$key])) {
5743
+				return false;
5744
+			}
5745
+		}
5746
+		return true;
5747
+	}
5748
+
5749
+
5750
+
5751
+	/**
5752
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5753
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5754
+	 *
5755
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5756
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5757
+	 * @throws EE_Error
5758
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5759
+	 *                                                              indexed)
5760
+	 */
5761
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5762
+	{
5763
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5764
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5765
+		} elseif (is_array($model_object_or_attributes_array)) {
5766
+			$attributes_array = $model_object_or_attributes_array;
5767
+		} else {
5768
+			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5769
+				"event_espresso"), $model_object_or_attributes_array));
5770
+		}
5771
+		//even copies obviously won't have the same ID, so remove the primary key
5772
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5773
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5774
+			unset($attributes_array[$this->primary_key_name()]);
5775
+		}
5776
+		if (isset($query_params[0])) {
5777
+			$query_params[0] = array_merge($attributes_array, $query_params);
5778
+		} else {
5779
+			$query_params[0] = $attributes_array;
5780
+		}
5781
+		return $this->get_all($query_params);
5782
+	}
5783
+
5784
+
5785
+
5786
+	/**
5787
+	 * Gets the first copy we find. See get_all_copies for more details
5788
+	 *
5789
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5790
+	 * @param array $query_params
5791
+	 * @return EE_Base_Class
5792
+	 * @throws EE_Error
5793
+	 */
5794
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5795
+	{
5796
+		if (! is_array($query_params)) {
5797
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5798
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5799
+					gettype($query_params)), '4.6.0');
5800
+			$query_params = array();
5801
+		}
5802
+		$query_params['limit'] = 1;
5803
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5804
+		if (is_array($copies)) {
5805
+			return array_shift($copies);
5806
+		}
5807
+		return null;
5808
+	}
5809
+
5810
+
5811
+
5812
+	/**
5813
+	 * Updates the item with the specified id. Ignores default query parameters because
5814
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5815
+	 *
5816
+	 * @param array      $fields_n_values keys are field names, values are their new values
5817
+	 * @param int|string $id              the value of the primary key to update
5818
+	 * @return int number of rows updated
5819
+	 * @throws EE_Error
5820
+	 */
5821
+	public function update_by_ID($fields_n_values, $id)
5822
+	{
5823
+		$query_params = array(
5824
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5825
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5826
+		);
5827
+		return $this->update($fields_n_values, $query_params);
5828
+	}
5829
+
5830
+
5831
+
5832
+	/**
5833
+	 * Changes an operator which was supplied to the models into one usable in SQL
5834
+	 *
5835
+	 * @param string $operator_supplied
5836
+	 * @return string an operator which can be used in SQL
5837
+	 * @throws EE_Error
5838
+	 */
5839
+	private function _prepare_operator_for_sql($operator_supplied)
5840
+	{
5841
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5842
+			: null;
5843
+		if ($sql_operator) {
5844
+			return $sql_operator;
5845
+		}
5846
+		throw new EE_Error(
5847
+			sprintf(
5848
+				__(
5849
+					"The operator '%s' is not in the list of valid operators: %s",
5850
+					"event_espresso"
5851
+				), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5852
+			)
5853
+		);
5854
+	}
5855
+
5856
+
5857
+
5858
+	/**
5859
+	 * Gets the valid operators
5860
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5861
+	 */
5862
+	public function valid_operators(){
5863
+		return $this->_valid_operators;
5864
+	}
5865
+
5866
+
5867
+
5868
+	/**
5869
+	 * Gets the between-style operators (take 2 arguments).
5870
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5871
+	 */
5872
+	public function valid_between_style_operators()
5873
+	{
5874
+		return array_intersect(
5875
+			$this->valid_operators(),
5876
+			$this->_between_style_operators
5877
+		);
5878
+	}
5879
+
5880
+	/**
5881
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5882
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5883
+	 */
5884
+	public function valid_like_style_operators()
5885
+	{
5886
+		return array_intersect(
5887
+			$this->valid_operators(),
5888
+			$this->_like_style_operators
5889
+		);
5890
+	}
5891
+
5892
+	/**
5893
+	 * Gets the "in"-style operators
5894
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5895
+	 */
5896
+	public function valid_in_style_operators()
5897
+	{
5898
+		return array_intersect(
5899
+			$this->valid_operators(),
5900
+			$this->_in_style_operators
5901
+		);
5902
+	}
5903
+
5904
+	/**
5905
+	 * Gets the "null"-style operators (accept no arguments)
5906
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5907
+	 */
5908
+	public function valid_null_style_operators()
5909
+	{
5910
+		return array_intersect(
5911
+			$this->valid_operators(),
5912
+			$this->_null_style_operators
5913
+		);
5914
+	}
5915
+
5916
+	/**
5917
+	 * Gets an array where keys are the primary keys and values are their 'names'
5918
+	 * (as determined by the model object's name() function, which is often overridden)
5919
+	 *
5920
+	 * @param array $query_params like get_all's
5921
+	 * @return string[]
5922
+	 * @throws EE_Error
5923
+	 */
5924
+	public function get_all_names($query_params = array())
5925
+	{
5926
+		$objs = $this->get_all($query_params);
5927
+		$names = array();
5928
+		foreach ($objs as $obj) {
5929
+			$names[$obj->ID()] = $obj->name();
5930
+		}
5931
+		return $names;
5932
+	}
5933
+
5934
+
5935
+
5936
+	/**
5937
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5938
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5939
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5940
+	 * array_keys() on $model_objects.
5941
+	 *
5942
+	 * @param \EE_Base_Class[] $model_objects
5943
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5944
+	 *                                               in the returned array
5945
+	 * @return array
5946
+	 * @throws EE_Error
5947
+	 */
5948
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5949
+	{
5950
+		if (! $this->has_primary_key_field()) {
5951
+			if (WP_DEBUG) {
5952
+				EE_Error::add_error(
5953
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5954
+					__FILE__,
5955
+					__FUNCTION__,
5956
+					__LINE__
5957
+				);
5958
+			}
5959
+		}
5960
+		$IDs = array();
5961
+		foreach ($model_objects as $model_object) {
5962
+			$id = $model_object->ID();
5963
+			if (! $id) {
5964
+				if ($filter_out_empty_ids) {
5965
+					continue;
5966
+				}
5967
+				if (WP_DEBUG) {
5968
+					EE_Error::add_error(
5969
+						__(
5970
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5971
+							'event_espresso'
5972
+						),
5973
+						__FILE__,
5974
+						__FUNCTION__,
5975
+						__LINE__
5976
+					);
5977
+				}
5978
+			}
5979
+			$IDs[] = $id;
5980
+		}
5981
+		return $IDs;
5982
+	}
5983
+
5984
+
5985
+
5986
+	/**
5987
+	 * Returns the string used in capabilities relating to this model. If there
5988
+	 * are no capabilities that relate to this model returns false
5989
+	 *
5990
+	 * @return string|false
5991
+	 */
5992
+	public function cap_slug()
5993
+	{
5994
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5995
+	}
5996
+
5997
+
5998
+
5999
+	/**
6000
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6001
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6002
+	 * only returns the cap restrictions array in that context (ie, the array
6003
+	 * at that key)
6004
+	 *
6005
+	 * @param string $context
6006
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6007
+	 * @throws EE_Error
6008
+	 */
6009
+	public function cap_restrictions($context = EEM_Base::caps_read)
6010
+	{
6011
+		EEM_Base::verify_is_valid_cap_context($context);
6012
+		//check if we ought to run the restriction generator first
6013
+		if (
6014
+			isset($this->_cap_restriction_generators[$context])
6015
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6016
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6017
+		) {
6018
+			$this->_cap_restrictions[$context] = array_merge(
6019
+				$this->_cap_restrictions[$context],
6020
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
6021
+			);
6022
+		}
6023
+		//and make sure we've finalized the construction of each restriction
6024
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6025
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6026
+				$where_conditions_obj->_finalize_construct($this);
6027
+			}
6028
+		}
6029
+		return $this->_cap_restrictions[$context];
6030
+	}
6031
+
6032
+
6033
+
6034
+	/**
6035
+	 * Indicating whether or not this model thinks its a wp core model
6036
+	 *
6037
+	 * @return boolean
6038
+	 */
6039
+	public function is_wp_core_model()
6040
+	{
6041
+		return $this->_wp_core_model;
6042
+	}
6043
+
6044
+
6045
+
6046
+	/**
6047
+	 * Gets all the caps that are missing which impose a restriction on
6048
+	 * queries made in this context
6049
+	 *
6050
+	 * @param string $context one of EEM_Base::caps_ constants
6051
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6052
+	 * @throws EE_Error
6053
+	 */
6054
+	public function caps_missing($context = EEM_Base::caps_read)
6055
+	{
6056
+		$missing_caps = array();
6057
+		$cap_restrictions = $this->cap_restrictions($context);
6058
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6059
+			if (! EE_Capabilities::instance()
6060
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6061
+			) {
6062
+				$missing_caps[$cap] = $restriction_if_no_cap;
6063
+			}
6064
+		}
6065
+		return $missing_caps;
6066
+	}
6067
+
6068
+
6069
+
6070
+	/**
6071
+	 * Gets the mapping from capability contexts to action strings used in capability names
6072
+	 *
6073
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6074
+	 * one of 'read', 'edit', or 'delete'
6075
+	 */
6076
+	public function cap_contexts_to_cap_action_map()
6077
+	{
6078
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
6079
+			$this);
6080
+	}
6081
+
6082
+
6083
+
6084
+	/**
6085
+	 * Gets the action string for the specified capability context
6086
+	 *
6087
+	 * @param string $context
6088
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6089
+	 * @throws EE_Error
6090
+	 */
6091
+	public function cap_action_for_context($context)
6092
+	{
6093
+		$mapping = $this->cap_contexts_to_cap_action_map();
6094
+		if (isset($mapping[$context])) {
6095
+			return $mapping[$context];
6096
+		}
6097
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6098
+			return $action;
6099
+		}
6100
+		throw new EE_Error(
6101
+			sprintf(
6102
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6103
+				$context,
6104
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6105
+			)
6106
+		);
6107
+	}
6108
+
6109
+
6110
+
6111
+	/**
6112
+	 * Returns all the capability contexts which are valid when querying models
6113
+	 *
6114
+	 * @return array
6115
+	 */
6116
+	public static function valid_cap_contexts()
6117
+	{
6118
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6119
+			self::caps_read,
6120
+			self::caps_read_admin,
6121
+			self::caps_edit,
6122
+			self::caps_delete,
6123
+		));
6124
+	}
6125
+
6126
+
6127
+
6128
+	/**
6129
+	 * Returns all valid options for 'default_where_conditions'
6130
+	 *
6131
+	 * @return array
6132
+	 */
6133
+	public static function valid_default_where_conditions()
6134
+	{
6135
+		return array(
6136
+			EEM_Base::default_where_conditions_all,
6137
+			EEM_Base::default_where_conditions_this_only,
6138
+			EEM_Base::default_where_conditions_others_only,
6139
+			EEM_Base::default_where_conditions_minimum_all,
6140
+			EEM_Base::default_where_conditions_minimum_others,
6141
+			EEM_Base::default_where_conditions_none
6142
+		);
6143
+	}
6144
+
6145
+	// public static function default_where_conditions_full
6146
+	/**
6147
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6148
+	 *
6149
+	 * @param string $context
6150
+	 * @return bool
6151
+	 * @throws EE_Error
6152
+	 */
6153
+	static public function verify_is_valid_cap_context($context)
6154
+	{
6155
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6156
+		if (in_array($context, $valid_cap_contexts)) {
6157
+			return true;
6158
+		}
6159
+		throw new EE_Error(
6160
+			sprintf(
6161
+				__(
6162
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6163
+					'event_espresso'
6164
+				),
6165
+				$context,
6166
+				'EEM_Base',
6167
+				implode(',', $valid_cap_contexts)
6168
+			)
6169
+		);
6170
+	}
6171
+
6172
+
6173
+
6174
+	/**
6175
+	 * Clears all the models field caches. This is only useful when a sub-class
6176
+	 * might have added a field or something and these caches might be invalidated
6177
+	 */
6178
+	protected function _invalidate_field_caches()
6179
+	{
6180
+		$this->_cache_foreign_key_to_fields = array();
6181
+		$this->_cached_fields = null;
6182
+		$this->_cached_fields_non_db_only = null;
6183
+	}
6184
+
6185
+
6186
+
6187
+	/**
6188
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6189
+	 * (eg "and", "or", "not").
6190
+	 *
6191
+	 * @return array
6192
+	 */
6193
+	public function logic_query_param_keys()
6194
+	{
6195
+		return $this->_logic_query_param_keys;
6196
+	}
6197
+
6198
+
6199
+
6200
+	/**
6201
+	 * Determines whether or not the where query param array key is for a logic query param.
6202
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6203
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6204
+	 *
6205
+	 * @param $query_param_key
6206
+	 * @return bool
6207
+	 */
6208
+	public function is_logic_query_param_key($query_param_key)
6209
+	{
6210
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6211
+			if ($query_param_key === $logic_query_param_key
6212
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6213
+			) {
6214
+				return true;
6215
+			}
6216
+		}
6217
+		return false;
6218
+	}
6219 6219
 
6220 6220
 
6221 6221
 
Please login to merge, or discard this patch.
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -515,8 +515,8 @@  discard block
 block discarded – undo
515 515
     protected function __construct($timezone = null)
516 516
     {
517 517
         // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
518
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+            throw new EE_Error(
520 520
                 sprintf(
521 521
                     __('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.',
522 522
                         'event_espresso'),
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
          *
537 537
          * @var EE_Table_Base[] $_tables
538 538
          */
539
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
539
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
540 540
         foreach ($this->_tables as $table_alias => $table_obj) {
541 541
             /** @var $table_obj EE_Table_Base */
542 542
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -551,10 +551,10 @@  discard block
 block discarded – undo
551 551
          *
552 552
          * @param EE_Model_Field_Base[] $_fields
553 553
          */
554
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
554
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
555 555
         $this->_invalidate_field_caches();
556 556
         foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
557
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
558 558
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559 559
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
560 560
             }
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
          *
583 583
          * @param EE_Model_Relation_Base[] $_model_relations
584 584
          */
585
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
585
+        $this->_model_relations = (array) apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
586 586
             $this->_model_relations);
587 587
         foreach ($this->_model_relations as $model_name => $relation_obj) {
588 588
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -594,12 +594,12 @@  discard block
 block discarded – undo
594 594
         }
595 595
         $this->set_timezone($timezone);
596 596
         //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
597
+        if ( ! $this->_default_where_conditions_strategy) {
598 598
             //nothing was set during child constructor, so set default
599 599
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600 600
         }
601 601
         $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
602
+        if ( ! $this->_minimum_where_conditions_strategy) {
603 603
             //nothing was set during child constructor, so set default
604 604
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605 605
         }
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
         //initialize the standard cap restriction generators if none were specified by the child constructor
613 613
         if ($this->_cap_restriction_generators !== false) {
614 614
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
615
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
616 616
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
617 617
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618 618
                         new EE_Restriction_Generator_Protected(),
@@ -625,10 +625,10 @@  discard block
 block discarded – undo
625 625
         //if there are cap restriction generators, use them to make the default cap restrictions
626 626
         if ($this->_cap_restriction_generators !== false) {
627 627
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
628
+                if ( ! $generator_object) {
629 629
                     continue;
630 630
                 }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
631
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
632 632
                     throw new EE_Error(
633 633
                         sprintf(
634 634
                             __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
                     );
640 640
                 }
641 641
                 $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
642
+                if ( ! $generator_object->construction_finalized()) {
643 643
                     $generator_object->_construct_finalize($this, $action);
644 644
                 }
645 645
             }
646 646
         }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
647
+        do_action('AHEE__'.get_class($this).'__construct__end');
648 648
     }
649 649
 
650 650
 
@@ -657,7 +657,7 @@  discard block
 block discarded – undo
657 657
      */
658 658
     public static function set_model_query_blog_id($blog_id = 0)
659 659
     {
660
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
660
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
661 661
     }
662 662
 
663 663
 
@@ -691,7 +691,7 @@  discard block
 block discarded – undo
691 691
     public static function instance($timezone = null)
692 692
     {
693 693
         // check if instance of Espresso_model already exists
694
-        if (! static::$_instance instanceof static) {
694
+        if ( ! static::$_instance instanceof static) {
695 695
             // instantiate Espresso_model
696 696
             static::$_instance = new static(
697 697
                 $timezone,
@@ -730,7 +730,7 @@  discard block
 block discarded – undo
730 730
             foreach ($r->getDefaultProperties() as $property => $value) {
731 731
                 //don't set instance to null like it was originally,
732 732
                 //but it's static anyways, and we're ignoring static properties (for now at least)
733
-                if (! isset($static_properties[$property])) {
733
+                if ( ! isset($static_properties[$property])) {
734 734
                     static::$_instance->{$property} = $value;
735 735
                 }
736 736
             }
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
      */
755 755
     private static function getLoader()
756 756
     {
757
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
757
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
758 758
             EEM_Base::$loader = LoaderFactory::getLoader();
759 759
         }
760 760
         return EEM_Base::$loader;
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
      */
775 775
     public function status_array($translated = false)
776 776
     {
777
-        if (! array_key_exists('Status', $this->_model_relations)) {
777
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
778 778
             return array();
779 779
         }
780 780
         $model_name = $this->get_this_model_name();
@@ -977,17 +977,17 @@  discard block
 block discarded – undo
977 977
     public function wp_user_field_name()
978 978
     {
979 979
         try {
980
-            if (! empty($this->_model_chain_to_wp_user)) {
980
+            if ( ! empty($this->_model_chain_to_wp_user)) {
981 981
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982 982
                 $last_model_name = end($models_to_follow_to_wp_users);
983 983
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
984
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
985 985
             } else {
986 986
                 $model_with_fk_to_wp_users = $this;
987 987
                 $model_chain_to_wp_user = '';
988 988
             }
989 989
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
990
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
991 991
         } catch (EE_Error $e) {
992 992
             return false;
993 993
         }
@@ -1055,7 +1055,7 @@  discard block
 block discarded – undo
1055 1055
      */
1056 1056
     protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057 1057
     {
1058
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1058
+        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select); ;
1059 1059
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1060 1060
         $select_expressions = $columns_to_select === null
1061 1061
             ? $this->_construct_default_select_sql($model_query_info)
@@ -1063,11 +1063,11 @@  discard block
 block discarded – undo
1063 1063
         if ($this->_custom_selections instanceof CustomSelects) {
1064 1064
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065 1065
             $select_expressions .= $select_expressions
1066
-                ? ', ' . $custom_expressions
1066
+                ? ', '.$custom_expressions
1067 1067
                 : $custom_expressions;
1068 1068
         }
1069 1069
 
1070
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1070
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1071 1071
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072 1072
     }
1073 1073
 
@@ -1084,7 +1084,7 @@  discard block
 block discarded – undo
1084 1084
      */
1085 1085
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086 1086
     {
1087
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1087
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088 1088
             return null;
1089 1089
         }
1090 1090
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
         if (is_array($columns_to_select)) {
1134 1134
             $select_sql_array = array();
1135 1135
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1136
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137 1137
                     throw new EE_Error(
1138 1138
                         sprintf(
1139 1139
                             __(
@@ -1145,7 +1145,7 @@  discard block
 block discarded – undo
1145 1145
                         )
1146 1146
                     );
1147 1147
                 }
1148
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1148
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149 1149
                     throw new EE_Error(
1150 1150
                         sprintf(
1151 1151
                             esc_html__(
@@ -1217,7 +1217,7 @@  discard block
 block discarded – undo
1217 1217
      */
1218 1218
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219 1219
     {
1220
-        if (! isset($query_params[0])) {
1220
+        if ( ! isset($query_params[0])) {
1221 1221
             $query_params[0] = array();
1222 1222
         }
1223 1223
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1242,7 +1242,7 @@  discard block
 block discarded – undo
1242 1242
      */
1243 1243
     public function get_one($query_params = array())
1244 1244
     {
1245
-        if (! is_array($query_params)) {
1245
+        if ( ! is_array($query_params)) {
1246 1246
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1247 1247
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248 1248
                     gettype($query_params)), '4.6.0');
@@ -1433,7 +1433,7 @@  discard block
 block discarded – undo
1433 1433
                 return array();
1434 1434
             }
1435 1435
         }
1436
-        if (! is_array($query_params)) {
1436
+        if ( ! is_array($query_params)) {
1437 1437
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438 1438
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439 1439
                     gettype($query_params)), '4.6.0');
@@ -1443,7 +1443,7 @@  discard block
 block discarded – undo
1443 1443
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444 1444
         $query_params['limit'] = $limit;
1445 1445
         //set direction
1446
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1446
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1447 1447
         $query_params['order_by'] = $operand === '>'
1448 1448
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1449 1449
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1521,7 +1521,7 @@  discard block
 block discarded – undo
1521 1521
     {
1522 1522
         $field_settings = $this->field_settings_for($field_name);
1523 1523
         //if not a valid EE_Datetime_Field then throw error
1524
-        if (! $field_settings instanceof EE_Datetime_Field) {
1524
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1525 1525
             throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1526 1526
                 'event_espresso'), $field_name));
1527 1527
         }
@@ -1672,7 +1672,7 @@  discard block
 block discarded – undo
1672 1672
      */
1673 1673
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1674 1674
     {
1675
-        if (! is_array($query_params)) {
1675
+        if ( ! is_array($query_params)) {
1676 1676
             EE_Error::doing_it_wrong('EEM_Base::update',
1677 1677
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1678 1678
                     gettype($query_params)), '4.6.0');
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
          * @param EEM_Base $model           the model being queried
1695 1695
          * @param array    $query_params    see EEM_Base::get_all()
1696 1696
          */
1697
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1697
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1698 1698
             $query_params);
1699 1699
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1700 1700
         //to do that, for each table, verify that it's PK isn't null.
@@ -1708,7 +1708,7 @@  discard block
 block discarded – undo
1708 1708
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1709 1709
         foreach ($wpdb_select_results as $wpdb_result) {
1710 1710
             // type cast stdClass as array
1711
-            $wpdb_result = (array)$wpdb_result;
1711
+            $wpdb_result = (array) $wpdb_result;
1712 1712
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1713 1713
             if ($this->has_primary_key_field()) {
1714 1714
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1725,13 +1725,13 @@  discard block
 block discarded – undo
1725 1725
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1726 1726
                     //if there is no private key for this table on the results, it means there's no entry
1727 1727
                     //in this table, right? so insert a row in the current table, using any fields available
1728
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1728
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1729 1729
                            && $wpdb_result[$this_table_pk_column])
1730 1730
                     ) {
1731 1731
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1732 1732
                             $main_table_pk_value);
1733 1733
                         //if we died here, report the error
1734
-                        if (! $success) {
1734
+                        if ( ! $success) {
1735 1735
                             return false;
1736 1736
                         }
1737 1737
                     }
@@ -1762,7 +1762,7 @@  discard block
 block discarded – undo
1762 1762
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1763 1763
                 }
1764 1764
             }
1765
-            if (! $model_objs_affected_ids) {
1765
+            if ( ! $model_objs_affected_ids) {
1766 1766
                 //wait wait wait- if nothing was affected let's stop here
1767 1767
                 return 0;
1768 1768
             }
@@ -1789,7 +1789,7 @@  discard block
 block discarded – undo
1789 1789
                . $model_query_info->get_full_join_sql()
1790 1790
                . " SET "
1791 1791
                . $this->_construct_update_sql($fields_n_values)
1792
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1792
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1793 1793
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1794 1794
         /**
1795 1795
          * Action called after a model update call has been made.
@@ -1800,7 +1800,7 @@  discard block
 block discarded – undo
1800 1800
          * @param int      $rows_affected
1801 1801
          */
1802 1802
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1803
-        return $rows_affected;//how many supposedly got updated
1803
+        return $rows_affected; //how many supposedly got updated
1804 1804
     }
1805 1805
 
1806 1806
 
@@ -1828,7 +1828,7 @@  discard block
 block discarded – undo
1828 1828
         }
1829 1829
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1830 1830
         $select_expressions = $field->get_qualified_column();
1831
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1831
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1832 1832
         return $this->_do_wpdb_query('get_col', array($SQL));
1833 1833
     }
1834 1834
 
@@ -1846,7 +1846,7 @@  discard block
 block discarded – undo
1846 1846
     {
1847 1847
         $query_params['limit'] = 1;
1848 1848
         $col = $this->get_col($query_params, $field_to_select);
1849
-        if (! empty($col)) {
1849
+        if ( ! empty($col)) {
1850 1850
             return reset($col);
1851 1851
         }
1852 1852
         return null;
@@ -1877,7 +1877,7 @@  discard block
 block discarded – undo
1877 1877
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1878 1878
             $value_sql = $prepared_value === null ? 'NULL'
1879 1879
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1880
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1880
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1881 1881
         }
1882 1882
         return implode(",", $cols_n_values);
1883 1883
     }
@@ -2059,7 +2059,7 @@  discard block
 block discarded – undo
2059 2059
          * @param int      $rows_deleted
2060 2060
          */
2061 2061
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2062
-        return $rows_deleted;//how many supposedly got deleted
2062
+        return $rows_deleted; //how many supposedly got deleted
2063 2063
     }
2064 2064
 
2065 2065
 
@@ -2209,7 +2209,7 @@  discard block
 block discarded – undo
2209 2209
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2210 2210
                 //make sure we have unique $ids
2211 2211
                 $ids = array_unique($ids);
2212
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2212
+                $query[] = $column.' IN('.implode(',', $ids).')';
2213 2213
             }
2214 2214
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2215 2215
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2217,7 +2217,7 @@  discard block
 block discarded – undo
2217 2217
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2218 2218
                 $values_for_each_combined_primary_key_for_a_row = array();
2219 2219
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2220
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2220
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2221 2221
                 }
2222 2222
                 $ways_to_identify_a_row[] = '('
2223 2223
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2237,8 +2237,8 @@  discard block
 block discarded – undo
2237 2237
      */
2238 2238
     public function get_field_by_column($qualified_column_name)
2239 2239
     {
2240
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2241
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2240
+       foreach ($this->field_settings(true) as $field_name => $field_obj) {
2241
+           if ($field_obj->get_qualified_column() === $qualified_column_name) {
2242 2242
                return $field_obj;
2243 2243
            }
2244 2244
        }
@@ -2289,9 +2289,9 @@  discard block
 block discarded – undo
2289 2289
                 $column_to_count = '*';
2290 2290
             }
2291 2291
         }
2292
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2293
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2294
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2292
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2293
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2294
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2295 2295
     }
2296 2296
 
2297 2297
 
@@ -2313,14 +2313,14 @@  discard block
 block discarded – undo
2313 2313
             $field_obj = $this->get_primary_key_field();
2314 2314
         }
2315 2315
         $column_to_count = $field_obj->get_qualified_column();
2316
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2316
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2317 2317
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2318 2318
         $data_type = $field_obj->get_wpdb_data_type();
2319 2319
         if ($data_type === '%d' || $data_type === '%s') {
2320
-            return (float)$return_value;
2320
+            return (float) $return_value;
2321 2321
         }
2322 2322
         //must be %f
2323
-        return (float)$return_value;
2323
+        return (float) $return_value;
2324 2324
     }
2325 2325
 
2326 2326
 
@@ -2340,13 +2340,13 @@  discard block
 block discarded – undo
2340 2340
         //if we're in maintenance mode level 2, DON'T run any queries
2341 2341
         //because level 2 indicates the database needs updating and
2342 2342
         //is probably out of sync with the code
2343
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2343
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2344 2344
             throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2345 2345
                 "event_espresso")));
2346 2346
         }
2347 2347
         /** @type WPDB $wpdb */
2348 2348
         global $wpdb;
2349
-        if (! method_exists($wpdb, $wpdb_method)) {
2349
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2350 2350
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2351 2351
                 'event_espresso'), $wpdb_method));
2352 2352
         }
@@ -2358,7 +2358,7 @@  discard block
 block discarded – undo
2358 2358
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2359 2359
         if (WP_DEBUG) {
2360 2360
             $wpdb->show_errors($old_show_errors_value);
2361
-            if (! empty($wpdb->last_error)) {
2361
+            if ( ! empty($wpdb->last_error)) {
2362 2362
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2363 2363
             }
2364 2364
             if ($result === false) {
@@ -2419,7 +2419,7 @@  discard block
 block discarded – undo
2419 2419
                     return $result;
2420 2420
                     break;
2421 2421
             }
2422
-            if (! empty($error_message)) {
2422
+            if ( ! empty($error_message)) {
2423 2423
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2424 2424
                 trigger_error($error_message);
2425 2425
             }
@@ -2495,11 +2495,11 @@  discard block
 block discarded – undo
2495 2495
      */
2496 2496
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2497 2497
     {
2498
-        return " FROM " . $model_query_info->get_full_join_sql() .
2499
-               $model_query_info->get_where_sql() .
2500
-               $model_query_info->get_group_by_sql() .
2501
-               $model_query_info->get_having_sql() .
2502
-               $model_query_info->get_order_by_sql() .
2498
+        return " FROM ".$model_query_info->get_full_join_sql().
2499
+               $model_query_info->get_where_sql().
2500
+               $model_query_info->get_group_by_sql().
2501
+               $model_query_info->get_having_sql().
2502
+               $model_query_info->get_order_by_sql().
2503 2503
                $model_query_info->get_limit_sql();
2504 2504
     }
2505 2505
 
@@ -2695,12 +2695,12 @@  discard block
 block discarded – undo
2695 2695
         $related_model = $this->get_related_model_obj($model_name);
2696 2696
         //we're just going to use the query params on the related model's normal get_all query,
2697 2697
         //except add a condition to say to match the current mod
2698
-        if (! isset($query_params['default_where_conditions'])) {
2698
+        if ( ! isset($query_params['default_where_conditions'])) {
2699 2699
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2700 2700
         }
2701 2701
         $this_model_name = $this->get_this_model_name();
2702 2702
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2703
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2703
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2704 2704
         return $related_model->count($query_params, $field_to_count, $distinct);
2705 2705
     }
2706 2706
 
@@ -2720,7 +2720,7 @@  discard block
 block discarded – undo
2720 2720
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2721 2721
     {
2722 2722
         $related_model = $this->get_related_model_obj($model_name);
2723
-        if (! is_array($query_params)) {
2723
+        if ( ! is_array($query_params)) {
2724 2724
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2725 2725
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2726 2726
                     gettype($query_params)), '4.6.0');
@@ -2728,12 +2728,12 @@  discard block
 block discarded – undo
2728 2728
         }
2729 2729
         //we're just going to use the query params on the related model's normal get_all query,
2730 2730
         //except add a condition to say to match the current mod
2731
-        if (! isset($query_params['default_where_conditions'])) {
2731
+        if ( ! isset($query_params['default_where_conditions'])) {
2732 2732
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2733 2733
         }
2734 2734
         $this_model_name = $this->get_this_model_name();
2735 2735
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2736
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2736
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2737 2737
         return $related_model->sum($query_params, $field_to_sum);
2738 2738
     }
2739 2739
 
@@ -2786,7 +2786,7 @@  discard block
 block discarded – undo
2786 2786
                 $field_with_model_name = $field;
2787 2787
             }
2788 2788
         }
2789
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2789
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2790 2790
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2791 2791
                 $this->get_this_model_name()));
2792 2792
         }
@@ -2819,7 +2819,7 @@  discard block
 block discarded – undo
2819 2819
          * @param array    $fields_n_values keys are the fields and values are their new values
2820 2820
          * @param EEM_Base $model           the model used
2821 2821
          */
2822
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2822
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2823 2823
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2824 2824
             $main_table = $this->_get_main_table();
2825 2825
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2926,7 +2926,7 @@  discard block
 block discarded – undo
2926 2926
         }
2927 2927
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2928 2928
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2929
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2929
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2930 2930
         }
2931 2931
         //if there is nothing to base this search on, then we shouldn't find anything
2932 2932
         if (empty($query_params)) {
@@ -3012,7 +3012,7 @@  discard block
 block discarded – undo
3012 3012
             //its not the main table, so we should have already saved the main table's PK which we just inserted
3013 3013
             //so add the fk to the main table as a column
3014 3014
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3015
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3015
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
3016 3016
         }
3017 3017
         //insert the new entry
3018 3018
         $result = $this->_do_wpdb_query('insert',
@@ -3216,7 +3216,7 @@  discard block
 block discarded – undo
3216 3216
                     $query_info_carrier,
3217 3217
                     'group_by'
3218 3218
                 );
3219
-            } elseif (! empty ($query_params['group_by'])) {
3219
+            } elseif ( ! empty ($query_params['group_by'])) {
3220 3220
                 $this->_extract_related_model_info_from_query_param(
3221 3221
                     $query_params['group_by'],
3222 3222
                     $query_info_carrier,
@@ -3238,7 +3238,7 @@  discard block
 block discarded – undo
3238 3238
                     $query_info_carrier,
3239 3239
                     'order_by'
3240 3240
                 );
3241
-            } elseif (! empty($query_params['order_by'])) {
3241
+            } elseif ( ! empty($query_params['order_by'])) {
3242 3242
                 $this->_extract_related_model_info_from_query_param(
3243 3243
                     $query_params['order_by'],
3244 3244
                     $query_info_carrier,
@@ -3274,8 +3274,8 @@  discard block
 block discarded – undo
3274 3274
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3275 3275
         $query_param_type
3276 3276
     ) {
3277
-        if (! empty($sub_query_params)) {
3278
-            $sub_query_params = (array)$sub_query_params;
3277
+        if ( ! empty($sub_query_params)) {
3278
+            $sub_query_params = (array) $sub_query_params;
3279 3279
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3280 3280
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3281 3281
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3286,7 +3286,7 @@  discard block
 block discarded – undo
3286 3286
                 //of array('Registration.TXN_ID'=>23)
3287 3287
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3288 3288
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3289
-                    if (! is_array($possibly_array_of_params)) {
3289
+                    if ( ! is_array($possibly_array_of_params)) {
3290 3290
                         throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3291 3291
                             "event_espresso"),
3292 3292
                             $param, $possibly_array_of_params));
@@ -3303,7 +3303,7 @@  discard block
 block discarded – undo
3303 3303
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3304 3304
                     //indicating that $possible_array_of_params[1] is actually a field name,
3305 3305
                     //from which we should extract query parameters!
3306
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3306
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3307 3307
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3308 3308
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3309 3309
                     }
@@ -3333,8 +3333,8 @@  discard block
 block discarded – undo
3333 3333
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3334 3334
         $query_param_type
3335 3335
     ) {
3336
-        if (! empty($sub_query_params)) {
3337
-            if (! is_array($sub_query_params)) {
3336
+        if ( ! empty($sub_query_params)) {
3337
+            if ( ! is_array($sub_query_params)) {
3338 3338
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3339 3339
                     $sub_query_params));
3340 3340
             }
@@ -3363,7 +3363,7 @@  discard block
 block discarded – undo
3363 3363
      */
3364 3364
     public function _create_model_query_info_carrier($query_params)
3365 3365
     {
3366
-        if (! is_array($query_params)) {
3366
+        if ( ! is_array($query_params)) {
3367 3367
             EE_Error::doing_it_wrong(
3368 3368
                 'EEM_Base::_create_model_query_info_carrier',
3369 3369
                 sprintf(
@@ -3439,7 +3439,7 @@  discard block
 block discarded – undo
3439 3439
         //set limit
3440 3440
         if (array_key_exists('limit', $query_params)) {
3441 3441
             if (is_array($query_params['limit'])) {
3442
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3442
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3443 3443
                     $e = sprintf(
3444 3444
                         __(
3445 3445
                             "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)",
@@ -3447,12 +3447,12 @@  discard block
 block discarded – undo
3447 3447
                         ),
3448 3448
                         http_build_query($query_params['limit'])
3449 3449
                     );
3450
-                    throw new EE_Error($e . "|" . $e);
3450
+                    throw new EE_Error($e."|".$e);
3451 3451
                 }
3452 3452
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3453
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3454
-            } elseif (! empty ($query_params['limit'])) {
3455
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3453
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3454
+            } elseif ( ! empty ($query_params['limit'])) {
3455
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3456 3456
             }
3457 3457
         }
3458 3458
         //set order by
@@ -3484,10 +3484,10 @@  discard block
 block discarded – undo
3484 3484
                 $order_array = array();
3485 3485
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3486 3486
                     $order = $this->_extract_order($order);
3487
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3487
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3488 3488
                 }
3489
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3490
-            } elseif (! empty ($query_params['order_by'])) {
3489
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3490
+            } elseif ( ! empty ($query_params['order_by'])) {
3491 3491
                 $this->_extract_related_model_info_from_query_param(
3492 3492
                     $query_params['order_by'],
3493 3493
                     $query_object,
@@ -3498,18 +3498,18 @@  discard block
 block discarded – undo
3498 3498
                     ? $this->_extract_order($query_params['order'])
3499 3499
                     : 'DESC';
3500 3500
                 $query_object->set_order_by_sql(
3501
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3501
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3502 3502
                 );
3503 3503
             }
3504 3504
         }
3505 3505
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3506
-        if (! array_key_exists('order_by', $query_params)
3506
+        if ( ! array_key_exists('order_by', $query_params)
3507 3507
             && array_key_exists('order', $query_params)
3508 3508
             && ! empty($query_params['order'])
3509 3509
         ) {
3510 3510
             $pk_field = $this->get_primary_key_field();
3511 3511
             $order = $this->_extract_order($query_params['order']);
3512
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3512
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3513 3513
         }
3514 3514
         //set group by
3515 3515
         if (array_key_exists('group_by', $query_params)) {
@@ -3519,10 +3519,10 @@  discard block
 block discarded – undo
3519 3519
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3520 3520
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3521 3521
                 }
3522
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3523
-            } elseif (! empty ($query_params['group_by'])) {
3522
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3523
+            } elseif ( ! empty ($query_params['group_by'])) {
3524 3524
                 $query_object->set_group_by_sql(
3525
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3525
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3526 3526
                 );
3527 3527
             }
3528 3528
         }
@@ -3532,7 +3532,7 @@  discard block
 block discarded – undo
3532 3532
         }
3533 3533
         //now, just verify they didn't pass anything wack
3534 3534
         foreach ($query_params as $query_key => $query_value) {
3535
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3535
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3536 3536
                 throw new EE_Error(
3537 3537
                     sprintf(
3538 3538
                         __(
@@ -3631,22 +3631,22 @@  discard block
 block discarded – undo
3631 3631
         $where_query_params = array()
3632 3632
     ) {
3633 3633
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3634
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3634
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3635 3635
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3636 3636
                 "event_espresso"), $use_default_where_conditions,
3637 3637
                 implode(", ", $allowed_used_default_where_conditions_values)));
3638 3638
         }
3639 3639
         $universal_query_params = array();
3640
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3640
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3641 3641
             $universal_query_params = $this->_get_default_where_conditions();
3642
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3642
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3643 3643
             $universal_query_params = $this->_get_minimum_where_conditions();
3644 3644
         }
3645 3645
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3646 3646
             $related_model = $this->get_related_model_obj($model_name);
3647
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3647
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3648 3648
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3649
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3649
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3650 3650
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3651 3651
             } else {
3652 3652
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3679,7 +3679,7 @@  discard block
 block discarded – undo
3679 3679
      * @param bool $for_this_model false means this is for OTHER related models
3680 3680
      * @return bool
3681 3681
      */
3682
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3682
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3683 3683
     {
3684 3684
         return (
3685 3685
                    $for_this_model
@@ -3758,7 +3758,7 @@  discard block
 block discarded – undo
3758 3758
     ) {
3759 3759
         $null_friendly_where_conditions = array();
3760 3760
         $none_overridden = true;
3761
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3761
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3762 3762
         foreach ($default_where_conditions as $key => $val) {
3763 3763
             if (isset($provided_where_conditions[$key])) {
3764 3764
                 $none_overridden = false;
@@ -3876,7 +3876,7 @@  discard block
 block discarded – undo
3876 3876
             foreach ($tables as $table_obj) {
3877 3877
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3878 3878
                                        . $table_obj->get_fully_qualified_pk_column();
3879
-                if (! in_array($qualified_pk_column, $selects)) {
3879
+                if ( ! in_array($qualified_pk_column, $selects)) {
3880 3880
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3881 3881
                 }
3882 3882
             }
@@ -4022,9 +4022,9 @@  discard block
 block discarded – undo
4022 4022
         $query_parameter_type
4023 4023
     ) {
4024 4024
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4025
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4025
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4026 4026
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4027
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4027
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4028 4028
                 if ($possible_join_string === '') {
4029 4029
                     //nothing left to $query_param
4030 4030
                     //we should actually end in a field name, not a model like this!
@@ -4151,7 +4151,7 @@  discard block
 block discarded – undo
4151 4151
     {
4152 4152
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4153 4153
         if ($SQL) {
4154
-            return " WHERE " . $SQL;
4154
+            return " WHERE ".$SQL;
4155 4155
         }
4156 4156
         return '';
4157 4157
     }
@@ -4170,7 +4170,7 @@  discard block
 block discarded – undo
4170 4170
     {
4171 4171
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4172 4172
         if ($SQL) {
4173
-            return " HAVING " . $SQL;
4173
+            return " HAVING ".$SQL;
4174 4174
         }
4175 4175
         return '';
4176 4176
     }
@@ -4189,7 +4189,7 @@  discard block
 block discarded – undo
4189 4189
     {
4190 4190
         $where_clauses = array();
4191 4191
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4192
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4192
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
4193 4193
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4194 4194
                 switch ($query_param) {
4195 4195
                     case 'not':
@@ -4217,7 +4217,7 @@  discard block
 block discarded – undo
4217 4217
             } else {
4218 4218
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4219 4219
                 //if it's not a normal field, maybe it's a custom selection?
4220
-                if (! $field_obj) {
4220
+                if ( ! $field_obj) {
4221 4221
                     if ($this->_custom_selections instanceof CustomSelects) {
4222 4222
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4223 4223
                     } else {
@@ -4226,7 +4226,7 @@  discard block
 block discarded – undo
4226 4226
                     }
4227 4227
                 }
4228 4228
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4229
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4229
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4230 4230
             }
4231 4231
         }
4232 4232
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4247,7 +4247,7 @@  discard block
 block discarded – undo
4247 4247
         if ($field) {
4248 4248
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4249 4249
                 $query_param);
4250
-            return $table_alias_prefix . $field->get_qualified_column();
4250
+            return $table_alias_prefix.$field->get_qualified_column();
4251 4251
         }
4252 4252
         if ($this->_custom_selections instanceof CustomSelects
4253 4253
             && in_array($query_param, $this->_custom_selections->columnAliases(), true)
@@ -4304,7 +4304,7 @@  discard block
 block discarded – undo
4304 4304
     {
4305 4305
         if (is_array($op_and_value)) {
4306 4306
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4307
-            if (! $operator) {
4307
+            if ( ! $operator) {
4308 4308
                 $php_array_like_string = array();
4309 4309
                 foreach ($op_and_value as $key => $value) {
4310 4310
                     $php_array_like_string[] = "$key=>$value";
@@ -4326,14 +4326,14 @@  discard block
 block discarded – undo
4326 4326
         }
4327 4327
         //check to see if the value is actually another field
4328 4328
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4329
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4329
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4330 4330
         }
4331 4331
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4332 4332
             //in this case, the value should be an array, or at least a comma-separated list
4333 4333
             //it will need to handle a little differently
4334 4334
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4335 4335
             //note: $cleaned_value has already been run through $wpdb->prepare()
4336
-            return $operator . SP . $cleaned_value;
4336
+            return $operator.SP.$cleaned_value;
4337 4337
         }
4338 4338
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4339 4339
             //the value should be an array with count of two.
@@ -4349,7 +4349,7 @@  discard block
 block discarded – undo
4349 4349
                 );
4350 4350
             }
4351 4351
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4352
-            return $operator . SP . $cleaned_value;
4352
+            return $operator.SP.$cleaned_value;
4353 4353
         }
4354 4354
         if (in_array($operator, $this->valid_null_style_operators())) {
4355 4355
             if ($value !== null) {
@@ -4369,10 +4369,10 @@  discard block
 block discarded – undo
4369 4369
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4370 4370
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4371 4371
             //remove other junk. So just treat it as a string.
4372
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4372
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4373 4373
         }
4374
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4375
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4374
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4375
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4376 4376
         }
4377 4377
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4378 4378
             throw new EE_Error(
@@ -4386,7 +4386,7 @@  discard block
 block discarded – undo
4386 4386
                 )
4387 4387
             );
4388 4388
         }
4389
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4389
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4390 4390
             throw new EE_Error(
4391 4391
                 sprintf(
4392 4392
                     __(
@@ -4426,7 +4426,7 @@  discard block
 block discarded – undo
4426 4426
         foreach ($values as $value) {
4427 4427
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4428 4428
         }
4429
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4429
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4430 4430
     }
4431 4431
 
4432 4432
 
@@ -4467,7 +4467,7 @@  discard block
 block discarded – undo
4467 4467
                                 . $main_table->get_table_name()
4468 4468
                                 . " WHERE FALSE";
4469 4469
         }
4470
-        return "(" . implode(",", $cleaned_values) . ")";
4470
+        return "(".implode(",", $cleaned_values).")";
4471 4471
     }
4472 4472
 
4473 4473
 
@@ -4486,7 +4486,7 @@  discard block
 block discarded – undo
4486 4486
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4487 4487
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4488 4488
         } //$field_obj should really just be a data type
4489
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4489
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4490 4490
             throw new EE_Error(
4491 4491
                 sprintf(
4492 4492
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4614,10 +4614,10 @@  discard block
 block discarded – undo
4614 4614
      */
4615 4615
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4616 4616
     {
4617
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4617
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4618 4618
         $qualified_columns = array();
4619 4619
         foreach ($this->field_settings() as $field_name => $field) {
4620
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4620
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4621 4621
         }
4622 4622
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4623 4623
     }
@@ -4641,11 +4641,11 @@  discard block
 block discarded – undo
4641 4641
             if ($table_obj instanceof EE_Primary_Table) {
4642 4642
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4643 4643
                     ? $table_obj->get_select_join_limit($limit)
4644
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4644
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4645 4645
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4646 4646
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4647 4647
                     ? $table_obj->get_select_join_limit_join($limit)
4648
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4648
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4649 4649
             }
4650 4650
         }
4651 4651
         return $SQL;
@@ -4733,12 +4733,12 @@  discard block
 block discarded – undo
4733 4733
      */
4734 4734
     public function get_related_model_obj($model_name)
4735 4735
     {
4736
-        $model_classname = "EEM_" . $model_name;
4737
-        if (! class_exists($model_classname)) {
4736
+        $model_classname = "EEM_".$model_name;
4737
+        if ( ! class_exists($model_classname)) {
4738 4738
             throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4739 4739
                 'event_espresso'), $model_name, $model_classname));
4740 4740
         }
4741
-        return call_user_func($model_classname . "::instance");
4741
+        return call_user_func($model_classname."::instance");
4742 4742
     }
4743 4743
 
4744 4744
 
@@ -4785,7 +4785,7 @@  discard block
 block discarded – undo
4785 4785
     public function related_settings_for($relation_name)
4786 4786
     {
4787 4787
         $relatedModels = $this->relation_settings();
4788
-        if (! array_key_exists($relation_name, $relatedModels)) {
4788
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4789 4789
             throw new EE_Error(
4790 4790
                 sprintf(
4791 4791
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4813,7 +4813,7 @@  discard block
 block discarded – undo
4813 4813
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4814 4814
     {
4815 4815
         $fieldSettings = $this->field_settings($include_db_only_fields);
4816
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4816
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4817 4817
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4818 4818
                 get_class($this)));
4819 4819
         }
@@ -4886,7 +4886,7 @@  discard block
 block discarded – undo
4886 4886
                     break;
4887 4887
                 }
4888 4888
             }
4889
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4889
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4890 4890
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4891 4891
                     get_class($this)));
4892 4892
             }
@@ -4945,7 +4945,7 @@  discard block
 block discarded – undo
4945 4945
      */
4946 4946
     public function get_foreign_key_to($model_name)
4947 4947
     {
4948
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4948
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4949 4949
             foreach ($this->field_settings() as $field) {
4950 4950
                 if (
4951 4951
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4955,7 +4955,7 @@  discard block
 block discarded – undo
4955 4955
                     break;
4956 4956
                 }
4957 4957
             }
4958
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4958
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4959 4959
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4960 4960
                     'event_espresso'), $model_name, get_class($this)));
4961 4961
             }
@@ -5006,7 +5006,7 @@  discard block
 block discarded – undo
5006 5006
             foreach ($this->_fields as $fields_corresponding_to_table) {
5007 5007
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5008 5008
                     /** @var $field_obj EE_Model_Field_Base */
5009
-                    if (! $field_obj->is_db_only_field()) {
5009
+                    if ( ! $field_obj->is_db_only_field()) {
5010 5010
                         $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5011 5011
                     }
5012 5012
                 }
@@ -5035,7 +5035,7 @@  discard block
 block discarded – undo
5035 5035
         $count_if_model_has_no_primary_key = 0;
5036 5036
         $has_primary_key = $this->has_primary_key_field();
5037 5037
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5038
-        foreach ((array)$rows as $row) {
5038
+        foreach ((array) $rows as $row) {
5039 5039
             if (empty($row)) {
5040 5040
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5041 5041
                 return array();
@@ -5053,7 +5053,7 @@  discard block
 block discarded – undo
5053 5053
                 }
5054 5054
             }
5055 5055
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5056
-            if (! $classInstance) {
5056
+            if ( ! $classInstance) {
5057 5057
                 throw new EE_Error(
5058 5058
                     sprintf(
5059 5059
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5172,7 +5172,7 @@  discard block
 block discarded – undo
5172 5172
      */
5173 5173
     public function instantiate_class_from_array_or_object($cols_n_values)
5174 5174
     {
5175
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5175
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5176 5176
             $cols_n_values = get_object_vars($cols_n_values);
5177 5177
         }
5178 5178
         $primary_key = null;
@@ -5197,7 +5197,7 @@  discard block
 block discarded – undo
5197 5197
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5198 5198
         if ($primary_key) {
5199 5199
             $classInstance = $this->get_from_entity_map($primary_key);
5200
-            if (! $classInstance) {
5200
+            if ( ! $classInstance) {
5201 5201
                 $classInstance = EE_Registry::instance()
5202 5202
                                             ->load_class($className,
5203 5203
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -5246,12 +5246,12 @@  discard block
 block discarded – undo
5246 5246
     public function add_to_entity_map(EE_Base_Class $object)
5247 5247
     {
5248 5248
         $className = $this->_get_class_name();
5249
-        if (! $object instanceof $className) {
5249
+        if ( ! $object instanceof $className) {
5250 5250
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5251 5251
                 is_object($object) ? get_class($object) : $object, $className));
5252 5252
         }
5253 5253
         /** @var $object EE_Base_Class */
5254
-        if (! $object->ID()) {
5254
+        if ( ! $object->ID()) {
5255 5255
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5256 5256
                 "event_espresso"), get_class($this)));
5257 5257
         }
@@ -5320,7 +5320,7 @@  discard block
 block discarded – undo
5320 5320
             //there is a primary key on this table and its not set. Use defaults for all its columns
5321 5321
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5322 5322
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5323
-                    if (! $field_obj->is_db_only_field()) {
5323
+                    if ( ! $field_obj->is_db_only_field()) {
5324 5324
                         //prepare field as if its coming from db
5325 5325
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5326 5326
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5329,7 +5329,7 @@  discard block
 block discarded – undo
5329 5329
             } else {
5330 5330
                 //the table's rows existed. Use their values
5331 5331
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5332
-                    if (! $field_obj->is_db_only_field()) {
5332
+                    if ( ! $field_obj->is_db_only_field()) {
5333 5333
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5334 5334
                             $cols_n_values, $field_obj->get_qualified_column(),
5335 5335
                             $field_obj->get_table_column()
@@ -5444,7 +5444,7 @@  discard block
 block discarded – undo
5444 5444
      */
5445 5445
     private function _get_class_name()
5446 5446
     {
5447
-        return "EE_" . $this->get_this_model_name();
5447
+        return "EE_".$this->get_this_model_name();
5448 5448
     }
5449 5449
 
5450 5450
 
@@ -5459,7 +5459,7 @@  discard block
 block discarded – undo
5459 5459
      */
5460 5460
     public function item_name($quantity = 1)
5461 5461
     {
5462
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5462
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5463 5463
     }
5464 5464
 
5465 5465
 
@@ -5492,7 +5492,7 @@  discard block
 block discarded – undo
5492 5492
     {
5493 5493
         $className = get_class($this);
5494 5494
         $tagName = "FHEE__{$className}__{$methodName}";
5495
-        if (! has_filter($tagName)) {
5495
+        if ( ! has_filter($tagName)) {
5496 5496
             throw new EE_Error(
5497 5497
                 sprintf(
5498 5498
                     __('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 );',
@@ -5718,7 +5718,7 @@  discard block
 block discarded – undo
5718 5718
         $key_vals_in_combined_pk = array();
5719 5719
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5720 5720
         foreach ($key_fields as $key_field_name => $field_obj) {
5721
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5721
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5722 5722
                 return null;
5723 5723
             }
5724 5724
         }
@@ -5739,7 +5739,7 @@  discard block
 block discarded – undo
5739 5739
     {
5740 5740
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5741 5741
         foreach ($keys_it_should_have as $key) {
5742
-            if (! isset($key_vals[$key])) {
5742
+            if ( ! isset($key_vals[$key])) {
5743 5743
                 return false;
5744 5744
             }
5745 5745
         }
@@ -5793,7 +5793,7 @@  discard block
 block discarded – undo
5793 5793
      */
5794 5794
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5795 5795
     {
5796
-        if (! is_array($query_params)) {
5796
+        if ( ! is_array($query_params)) {
5797 5797
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5798 5798
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5799 5799
                     gettype($query_params)), '4.6.0');
@@ -5859,7 +5859,7 @@  discard block
 block discarded – undo
5859 5859
      * Gets the valid operators
5860 5860
      * @return array keys are accepted strings, values are the SQL they are converted to
5861 5861
      */
5862
-    public function valid_operators(){
5862
+    public function valid_operators() {
5863 5863
         return $this->_valid_operators;
5864 5864
     }
5865 5865
 
@@ -5947,7 +5947,7 @@  discard block
 block discarded – undo
5947 5947
      */
5948 5948
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5949 5949
     {
5950
-        if (! $this->has_primary_key_field()) {
5950
+        if ( ! $this->has_primary_key_field()) {
5951 5951
             if (WP_DEBUG) {
5952 5952
                 EE_Error::add_error(
5953 5953
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5960,7 +5960,7 @@  discard block
 block discarded – undo
5960 5960
         $IDs = array();
5961 5961
         foreach ($model_objects as $model_object) {
5962 5962
             $id = $model_object->ID();
5963
-            if (! $id) {
5963
+            if ( ! $id) {
5964 5964
                 if ($filter_out_empty_ids) {
5965 5965
                     continue;
5966 5966
                 }
@@ -6056,8 +6056,8 @@  discard block
 block discarded – undo
6056 6056
         $missing_caps = array();
6057 6057
         $cap_restrictions = $this->cap_restrictions($context);
6058 6058
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6059
-            if (! EE_Capabilities::instance()
6060
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6059
+            if ( ! EE_Capabilities::instance()
6060
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6061 6061
             ) {
6062 6062
                 $missing_caps[$cap] = $restriction_if_no_cap;
6063 6063
             }
@@ -6209,7 +6209,7 @@  discard block
 block discarded – undo
6209 6209
     {
6210 6210
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6211 6211
             if ($query_param_key === $logic_query_param_key
6212
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6212
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6213 6213
             ) {
6214 6214
                 return true;
6215 6215
             }
Please login to merge, or discard this patch.
core/db_models/EEM_Payment.model.php 2 patches
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -16,8 +16,8 @@  discard block
 block discarded – undo
16 16
 
17 17
 
18 18
 /**
19
-	 * Status id in esp_status table that represents an approved payment
20
-	 */
19
+ * Status id in esp_status table that represents an approved payment
20
+ */
21 21
 	const status_id_approved = 'PAP';
22 22
 
23 23
 
@@ -111,14 +111,14 @@  discard block
 block discarded – undo
111 111
 
112 112
 
113 113
 	/**
114
-	*		retrieve  all payments from db for a particular transaction, optionally with
114
+	 *		retrieve  all payments from db for a particular transaction, optionally with
115 115
 	 *		a particular status
116
-	*
117
-	* 		@access		public
118
-	* 		@param		$TXN_ID
116
+	 *
117
+	 * 		@access		public
118
+	 * 		@param		$TXN_ID
119 119
 	 *		@param	string	$status_of_payment one of EEM_Payment::status_id_*, like 'PAP','PCN',etc. If none is provided, gets payments with any status
120
-	*		@return		EE_Payment[]
121
-	*/
120
+	 *		@return		EE_Payment[]
121
+	 */
122 122
 	public function get_payments_for_transaction( $TXN_ID = FALSE, $status_of_payment = null ) {
123 123
 		// all payments for a TXN ordered chronologically
124 124
 		$query_params = array( array( 'TXN_ID' => $TXN_ID ), 'order_by' => array( 'PAY_timestamp' => 'ASC' ));
@@ -172,17 +172,17 @@  discard block
 block discarded – undo
172 172
 		// setup start date
173 173
 		$start_date = ! empty( $start_date ) ? date_create_from_format( $format, $start_date, $passedDateTimeZone ) : $now;
174 174
 		$start_date->setTimezone( $modelDateTimeZone );
175
-        // workaround for php datetime bug
176
-        // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
177
-        $start_date->getTimestamp();
175
+		// workaround for php datetime bug
176
+		// @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
177
+		$start_date->getTimestamp();
178 178
 		$start_date = $start_date->format( 'Y-m-d' ) . ' 00:00:00';
179 179
 		$start_date = strtotime( $start_date );
180 180
 		// setup end date
181 181
 		$end_date = ! empty( $end_date ) ? date_create_from_format( $format, $end_date, $passedDateTimeZone ) : $now;
182 182
 		$end_date->setTimezone( $modelDateTimeZone );
183
-        // workaround for php datetime bug
184
-        // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
185
-        $end_date->getTimestamp();
183
+		// workaround for php datetime bug
184
+		// @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
185
+		$end_date->getTimestamp();
186 186
 		$end_date = $end_date->format('Y-m-d') . ' 23:59:59';
187 187
 		$end_date = strtotime( $end_date );
188 188
 
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@  discard block
 block discarded – undo
8 8
  * @author				Michael Nelson, Brent Christensen
9 9
  *
10 10
  */
11
-class EEM_Payment extends EEM_Base implements EEMI_Payment{
11
+class EEM_Payment extends EEM_Base implements EEMI_Payment {
12 12
 
13 13
   	// private instance of the Payment object
14 14
 	protected static $_instance = NULL;
@@ -56,28 +56,28 @@  discard block
 block discarded – undo
56 56
 	 *		@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)
57 57
 	 *		@return EEM_Payment
58 58
 	 */
59
-	protected function __construct( $timezone ) {
59
+	protected function __construct($timezone) {
60 60
 
61
-		$this->singular_item = __('Payment','event_espresso');
62
-		$this->plural_item = __('Payments','event_espresso');
61
+		$this->singular_item = __('Payment', 'event_espresso');
62
+		$this->plural_item = __('Payments', 'event_espresso');
63 63
 
64 64
 		$this->_tables = array(
65
-			'Payment'=>new EE_Primary_Table('esp_payment','PAY_ID')
65
+			'Payment'=>new EE_Primary_Table('esp_payment', 'PAY_ID')
66 66
 		);
67 67
 		$this->_fields = array(
68 68
 			'Payment'=>array(
69
-				'PAY_ID'=>new EE_Primary_Key_Int_Field('PAY_ID', __('Payment ID','event_espresso')),
70
-				'TXN_ID'=>new EE_Foreign_Key_Int_Field('TXN_ID', __('Transaction ID','event_espresso'), false, 0, 'Transaction'),
71
-				'STS_ID'=>new EE_Foreign_Key_String_Field('STS_ID', __('Status ID','event_espresso'), false, EEM_Payment::status_id_failed, 'Status'),
72
-				'PAY_timestamp'=> new EE_Datetime_Field('PAY_timestamp', __('Timestamp of when payment was attempted','event_espresso'), false, EE_Datetime_Field::now, $timezone ),
73
-				'PAY_source'=>new EE_All_Caps_Text_Field('PAY_source', __('User-friendly description of payment','event_espresso'), false, 'CART'),
74
-				'PAY_amount'=>new EE_Money_Field('PAY_amount', __('Amount Payment should be for','event_espresso'), false, 0),
69
+				'PAY_ID'=>new EE_Primary_Key_Int_Field('PAY_ID', __('Payment ID', 'event_espresso')),
70
+				'TXN_ID'=>new EE_Foreign_Key_Int_Field('TXN_ID', __('Transaction ID', 'event_espresso'), false, 0, 'Transaction'),
71
+				'STS_ID'=>new EE_Foreign_Key_String_Field('STS_ID', __('Status ID', 'event_espresso'), false, EEM_Payment::status_id_failed, 'Status'),
72
+				'PAY_timestamp'=> new EE_Datetime_Field('PAY_timestamp', __('Timestamp of when payment was attempted', 'event_espresso'), false, EE_Datetime_Field::now, $timezone),
73
+				'PAY_source'=>new EE_All_Caps_Text_Field('PAY_source', __('User-friendly description of payment', 'event_espresso'), false, 'CART'),
74
+				'PAY_amount'=>new EE_Money_Field('PAY_amount', __('Amount Payment should be for', 'event_espresso'), false, 0),
75 75
 				'PMD_ID'=>new EE_Foreign_Key_Int_Field('PMD_ID', __("Payment Method ID", 'event_espresso'), false, NULL, 'Payment_Method'),
76
-				'PAY_gateway_response'=>new EE_Plain_Text_Field('PAY_gateway_response', __('Response from Gateway about the payment','event_espresso'), false, ''),
77
-				'PAY_txn_id_chq_nmbr'=>new EE_Plain_Text_Field('PAY_txn_id_chq_nmbr', __('Gateway Transaction ID or Cheque Number','event_espresso'), true, ''),
78
-				'PAY_po_number'=>new EE_Plain_Text_Field('PAY_po_number', __('Purchase or Sales Number','event_espresso'), true, ''),
79
-				'PAY_extra_accntng'=>new EE_Simple_HTML_Field('PAY_extra_accntng', __('Extra Account Info','event_espresso'), true, ''),
80
-				'PAY_details'=>new EE_Serialized_Text_Field('PAY_details', __('Full Gateway response about payment','event_espresso'), true, ''),
76
+				'PAY_gateway_response'=>new EE_Plain_Text_Field('PAY_gateway_response', __('Response from Gateway about the payment', 'event_espresso'), false, ''),
77
+				'PAY_txn_id_chq_nmbr'=>new EE_Plain_Text_Field('PAY_txn_id_chq_nmbr', __('Gateway Transaction ID or Cheque Number', 'event_espresso'), true, ''),
78
+				'PAY_po_number'=>new EE_Plain_Text_Field('PAY_po_number', __('Purchase or Sales Number', 'event_espresso'), true, ''),
79
+				'PAY_extra_accntng'=>new EE_Simple_HTML_Field('PAY_extra_accntng', __('Extra Account Info', 'event_espresso'), true, ''),
80
+				'PAY_details'=>new EE_Serialized_Text_Field('PAY_details', __('Full Gateway response about payment', 'event_espresso'), true, ''),
81 81
 				'PAY_redirect_url'=>new EE_Plain_Text_Field('PAY_redirect_url', __("Redirect URL", 'event_espresso'), true),
82 82
 				'PAY_redirect_args'=>new EE_Serialized_Text_Field('PAY_redirect_args', __("Key-Value POST vars to send along with redirect", 'event_espresso'), true)
83 83
 			)
@@ -87,11 +87,11 @@  discard block
 block discarded – undo
87 87
 			'Status'=> new EE_Belongs_To_Relation(),
88 88
 			'Payment_Method'=>new EE_Belongs_To_Relation(),
89 89
 			'Registration_Payment' => new EE_Has_Many_Relation(),
90
-			'Registration' => new EE_HABTM_Relation( 'Registration_Payment' ),
90
+			'Registration' => new EE_HABTM_Relation('Registration_Payment'),
91 91
 		);
92 92
 		$this->_model_chain_to_wp_user = 'Payment_Method';
93 93
 		$this->_caps_slug = 'transactions';
94
-		parent::__construct( $timezone );
94
+		parent::__construct($timezone);
95 95
 	}
96 96
 
97 97
 
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 	 * @param string $PAY_txn_id_chq_nmbr
104 104
 	 * @return EE_Payment
105 105
 	 */
106
-	public function get_payment_by_txn_id_chq_nmbr( $PAY_txn_id_chq_nmbr ){
106
+	public function get_payment_by_txn_id_chq_nmbr($PAY_txn_id_chq_nmbr) {
107 107
 		return $this->get_one(array(array('PAY_txn_id_chq_nmbr'=>$PAY_txn_id_chq_nmbr)));
108 108
 	}
109 109
 
@@ -119,15 +119,15 @@  discard block
 block discarded – undo
119 119
 	 *		@param	string	$status_of_payment one of EEM_Payment::status_id_*, like 'PAP','PCN',etc. If none is provided, gets payments with any status
120 120
 	*		@return		EE_Payment[]
121 121
 	*/
122
-	public function get_payments_for_transaction( $TXN_ID = FALSE, $status_of_payment = null ) {
122
+	public function get_payments_for_transaction($TXN_ID = FALSE, $status_of_payment = null) {
123 123
 		// all payments for a TXN ordered chronologically
124
-		$query_params = array( array( 'TXN_ID' => $TXN_ID ), 'order_by' => array( 'PAY_timestamp' => 'ASC' ));
124
+		$query_params = array(array('TXN_ID' => $TXN_ID), 'order_by' => array('PAY_timestamp' => 'ASC'));
125 125
 		// if provided with a status, search specifically for that status. Otherwise get them all
126
-		if ( $status_of_payment ){
126
+		if ($status_of_payment) {
127 127
 			$query_params[0]['STS_ID'] = $status_of_payment;
128 128
 		}
129 129
 		// retrieve payments
130
-		return $this->get_all ( $query_params );
130
+		return $this->get_all($query_params);
131 131
 	}
132 132
 
133 133
 
@@ -137,8 +137,8 @@  discard block
 block discarded – undo
137 137
 	 * @param int $TXN_ID
138 138
 	 * @return EE_Payment[]
139 139
 	 */
140
-	public function get_approved_payments_for_transaction( $TXN_ID = 0 ) {
141
-		return $this->get_payments_for_transaction( $TXN_ID, EEM_Payment::status_id_approved );
140
+	public function get_approved_payments_for_transaction($TXN_ID = 0) {
141
+		return $this->get_payments_for_transaction($TXN_ID, EEM_Payment::status_id_approved);
142 142
 
143 143
 	}
144 144
 
@@ -159,42 +159,42 @@  discard block
 block discarded – undo
159 159
 	 *
160 160
 	 * @return EE_Payment[]
161 161
 	 */
162
-	public function get_payments_made_between_dates( $start_date = '', $end_date = '', $format = '', $timezone = '' ) {
163
-		$timezone = empty( $timezone ) ? EEH_DTT_Helper::get_timezone() : $timezone;
162
+	public function get_payments_made_between_dates($start_date = '', $end_date = '', $format = '', $timezone = '') {
163
+		$timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
164 164
 		//if $start_date or $end date, verify $format is included.
165
-		if ( ( ! empty( $start_date ) || ! empty( $end_date ) ) && empty( $format ) ) {
166
-			throw new EE_Error( __('You included a start date and/or a end date for this method but did not include a format string.  The format string is needed for setting up the query', 'event_espresso' ) );
165
+		if (( ! empty($start_date) || ! empty($end_date)) && empty($format)) {
166
+			throw new EE_Error(__('You included a start date and/or a end date for this method but did not include a format string.  The format string is needed for setting up the query', 'event_espresso'));
167 167
 		}
168
-		$now = new DateTime( 'now' );
168
+		$now = new DateTime('now');
169 169
 		// setup timezone objects once
170
-		$modelDateTimeZone = new DateTimeZone( $this->_timezone );
171
-		$passedDateTimeZone = new DateTimeZone( $timezone );
170
+		$modelDateTimeZone = new DateTimeZone($this->_timezone);
171
+		$passedDateTimeZone = new DateTimeZone($timezone);
172 172
 		// setup start date
173
-		$start_date = ! empty( $start_date ) ? date_create_from_format( $format, $start_date, $passedDateTimeZone ) : $now;
174
-		$start_date->setTimezone( $modelDateTimeZone );
173
+		$start_date = ! empty($start_date) ? date_create_from_format($format, $start_date, $passedDateTimeZone) : $now;
174
+		$start_date->setTimezone($modelDateTimeZone);
175 175
         // workaround for php datetime bug
176 176
         // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
177 177
         $start_date->getTimestamp();
178
-		$start_date = $start_date->format( 'Y-m-d' ) . ' 00:00:00';
179
-		$start_date = strtotime( $start_date );
178
+		$start_date = $start_date->format('Y-m-d').' 00:00:00';
179
+		$start_date = strtotime($start_date);
180 180
 		// setup end date
181
-		$end_date = ! empty( $end_date ) ? date_create_from_format( $format, $end_date, $passedDateTimeZone ) : $now;
182
-		$end_date->setTimezone( $modelDateTimeZone );
181
+		$end_date = ! empty($end_date) ? date_create_from_format($format, $end_date, $passedDateTimeZone) : $now;
182
+		$end_date->setTimezone($modelDateTimeZone);
183 183
         // workaround for php datetime bug
184 184
         // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
185 185
         $end_date->getTimestamp();
186
-		$end_date = $end_date->format('Y-m-d') . ' 23:59:59';
187
-		$end_date = strtotime( $end_date );
186
+		$end_date = $end_date->format('Y-m-d').' 23:59:59';
187
+		$end_date = strtotime($end_date);
188 188
 
189 189
 		// make sure our start date is the lowest value and vice versa
190
-		$start = min( $start_date, $end_date );
191
-		$end = max( $start_date, $end_date );
190
+		$start = min($start_date, $end_date);
191
+		$end = max($start_date, $end_date);
192 192
 
193 193
 		//yes we generated the date and time string in utc but we WANT this start date and time used in the set timezone on the model.
194
-		$start_date = $this->convert_datetime_for_query( 'PAY_timestamp', date( 'Y-m-d', $start ) . ' 00:00:00', 'Y-m-d H:i:s', $this->get_timezone() );
195
-		$end_date = $this->convert_datetime_for_query( 'PAY_timestamp', date( 'Y-m-d', $end) . ' 23:59:59' , 'Y-m-d H:i:s', $this->get_timezone() );
194
+		$start_date = $this->convert_datetime_for_query('PAY_timestamp', date('Y-m-d', $start).' 00:00:00', 'Y-m-d H:i:s', $this->get_timezone());
195
+		$end_date = $this->convert_datetime_for_query('PAY_timestamp', date('Y-m-d', $end).' 23:59:59', 'Y-m-d H:i:s', $this->get_timezone());
196 196
 
197
-		return $this->get_all(array(array('PAY_timestamp'=>array('>=',$start_date),'PAY_timestamp*'=>array('<=',$end_date))));
197
+		return $this->get_all(array(array('PAY_timestamp'=>array('>=', $start_date), 'PAY_timestamp*'=>array('<=', $end_date))));
198 198
 	}
199 199
 
200 200
 	/**
@@ -204,35 +204,35 @@  discard block
 block discarded – undo
204 204
 	 * returns a string for the approved status
205 205
 	 * @return 	string
206 206
 	 */
207
-	function approved_status(){
207
+	function approved_status() {
208 208
 		return self::status_id_approved;
209 209
 	}
210 210
 	/**
211 211
 	 * returns a string for the pending status
212 212
 	 * @return 	string
213 213
 	 */
214
-	function pending_status(){
214
+	function pending_status() {
215 215
 		return self::status_id_pending;
216 216
 	}
217 217
 	/**
218 218
 	 * returns a string for the cancelled status
219 219
 	 * @return 	string
220 220
 	 */
221
-	function cancelled_status(){
221
+	function cancelled_status() {
222 222
 		return self::status_id_cancelled;
223 223
 	}
224 224
 	/**
225 225
 	 * returns a string for the failed status
226 226
 	 * @return 	string
227 227
 	 */
228
-	function failed_status(){
228
+	function failed_status() {
229 229
 		return self::status_id_failed;
230 230
 	}
231 231
 	/**
232 232
 	 * returns a string for the declined status
233 233
 	 * @return 	string
234 234
 	 */
235
-	function declined_status(){
235
+	function declined_status() {
236 236
 		return self::status_id_declined;
237 237
 	}
238 238
 
Please login to merge, or discard this patch.
core/data_migration_scripts/EE_DMS_Core_4_1_0.dms.php 1 patch
Indentation   +1139 added lines, -1139 removed lines patch added patch discarded remove patch
@@ -12,11 +12,11 @@  discard block
 block discarded – undo
12 12
 $stages = glob(EE_CORE . 'data_migration_scripts/4_1_0_stages/*');
13 13
 $class_to_filepath = array();
14 14
 if ( ! empty($stages)) {
15
-    foreach ($stages as $filepath) {
16
-        $matches = array();
17
-        preg_match('~4_1_0_stages/(.*).dmsstage.php~', $filepath, $matches);
18
-        $class_to_filepath[$matches[1]] = $filepath;
19
-    }
15
+	foreach ($stages as $filepath) {
16
+		$matches = array();
17
+		preg_match('~4_1_0_stages/(.*).dmsstage.php~', $filepath, $matches);
18
+		$class_to_filepath[$matches[1]] = $filepath;
19
+	}
20 20
 }
21 21
 //give addons a chance to autoload their stages too
22 22
 $class_to_filepath = apply_filters('FHEE__EE_DMS_4_1_0__autoloaded_stages', $class_to_filepath);
@@ -44,91 +44,91 @@  discard block
 block discarded – undo
44 44
 
45 45
 
46 46
 
47
-    /**
48
-     * EE_DMS_Core_4_1_0 constructor.
49
-     *
50
-     * @param TableManager  $table_manager
51
-     * @param TableAnalysis $table_analysis
52
-     */
53
-    public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
54
-    {
55
-        $this->_pretty_name = esc_html__("Data Migration from Event Espresso 3 to Event Espresso 4.1.0", "event_espresso");
56
-        $this->_priority = 10;
57
-        $this->_migration_stages = array(
58
-                new EE_DMS_4_1_0_org_options(),
59
-                new EE_DMS_4_1_0_shortcodes(),
60
-                new EE_DMS_4_1_0_gateways(),
61
-                new EE_DMS_4_1_0_events(),
62
-                new EE_DMS_4_1_0_prices(),
63
-                new EE_DMS_4_1_0_category_details(),
64
-                new EE_DMS_4_1_0_event_category(),
65
-                new EE_DMS_4_1_0_venues(),
66
-                new EE_DMS_4_1_0_event_venue(),
67
-                new EE_DMS_4_1_0_question_groups(),
68
-                new EE_DMS_4_1_0_questions(),
69
-                new EE_DMS_4_1_0_question_group_question(),
70
-                new EE_DMS_4_1_0_event_question_group(),
71
-                new EE_DMS_4_1_0_attendees(),
72
-                new EE_DMS_4_1_0_line_items(),
73
-                new EE_DMS_4_1_0_answers(),
74
-                new EE_DMS_4_1_0_checkins(),
75
-        );
76
-        parent::__construct($table_manager, $table_analysis);
77
-    }
78
-
79
-
80
-
81
-    /**
82
-     * Checks if this 3.1 Check-in table exists. If it doesn't we can't migrate Check-ins
83
-     *
84
-     * @global wpdb $wpdb
85
-     * @return boolean
86
-     */
87
-    private function _checkin_table_exists()
88
-    {
89
-        global $wpdb;
90
-        $results = $wpdb->get_results("SHOW TABLES LIKE '" . $wpdb->prefix . "events_attendee_checkin" . "'");
91
-        if ($results) {
92
-            return true;
93
-        } else {
94
-            return false;
95
-        }
96
-    }
97
-
98
-
99
-
100
-    public function can_migrate_from_version($version_array)
101
-    {
102
-        $version_string = $version_array['Core'];
103
-        if (version_compare($version_string, '4.0.0', '<=') && version_compare($version_string, '3.1.26', '>=')) {
47
+	/**
48
+	 * EE_DMS_Core_4_1_0 constructor.
49
+	 *
50
+	 * @param TableManager  $table_manager
51
+	 * @param TableAnalysis $table_analysis
52
+	 */
53
+	public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
54
+	{
55
+		$this->_pretty_name = esc_html__("Data Migration from Event Espresso 3 to Event Espresso 4.1.0", "event_espresso");
56
+		$this->_priority = 10;
57
+		$this->_migration_stages = array(
58
+				new EE_DMS_4_1_0_org_options(),
59
+				new EE_DMS_4_1_0_shortcodes(),
60
+				new EE_DMS_4_1_0_gateways(),
61
+				new EE_DMS_4_1_0_events(),
62
+				new EE_DMS_4_1_0_prices(),
63
+				new EE_DMS_4_1_0_category_details(),
64
+				new EE_DMS_4_1_0_event_category(),
65
+				new EE_DMS_4_1_0_venues(),
66
+				new EE_DMS_4_1_0_event_venue(),
67
+				new EE_DMS_4_1_0_question_groups(),
68
+				new EE_DMS_4_1_0_questions(),
69
+				new EE_DMS_4_1_0_question_group_question(),
70
+				new EE_DMS_4_1_0_event_question_group(),
71
+				new EE_DMS_4_1_0_attendees(),
72
+				new EE_DMS_4_1_0_line_items(),
73
+				new EE_DMS_4_1_0_answers(),
74
+				new EE_DMS_4_1_0_checkins(),
75
+		);
76
+		parent::__construct($table_manager, $table_analysis);
77
+	}
78
+
79
+
80
+
81
+	/**
82
+	 * Checks if this 3.1 Check-in table exists. If it doesn't we can't migrate Check-ins
83
+	 *
84
+	 * @global wpdb $wpdb
85
+	 * @return boolean
86
+	 */
87
+	private function _checkin_table_exists()
88
+	{
89
+		global $wpdb;
90
+		$results = $wpdb->get_results("SHOW TABLES LIKE '" . $wpdb->prefix . "events_attendee_checkin" . "'");
91
+		if ($results) {
92
+			return true;
93
+		} else {
94
+			return false;
95
+		}
96
+	}
97
+
98
+
99
+
100
+	public function can_migrate_from_version($version_array)
101
+	{
102
+		$version_string = $version_array['Core'];
103
+		if (version_compare($version_string, '4.0.0', '<=') && version_compare($version_string, '3.1.26', '>=')) {
104 104
 //			echo "$version_string can be migrated fro";
105
-            return true;
106
-        } elseif ( ! $version_string) {
105
+			return true;
106
+		} elseif ( ! $version_string) {
107 107
 //			echo "no version string provided: $version_string";
108
-            //no version string provided... this must be pre 4.1
109
-            //because since 4.1 we're
110
-            return false;//changed mind. dont want people thinking they should migrate yet because they cant
111
-        } else {
108
+			//no version string provided... this must be pre 4.1
109
+			//because since 4.1 we're
110
+			return false;//changed mind. dont want people thinking they should migrate yet because they cant
111
+		} else {
112 112
 //			echo "$version_string doesnt apply";
113
-            return false;
114
-        }
115
-    }
113
+			return false;
114
+		}
115
+	}
116 116
 
117 117
 
118 118
 
119
-    public function schema_changes_before_migration()
120
-    {
121
-        //relies on 4.1's EEH_Activation::create_table
122
-        require_once(EE_HELPERS . 'EEH_Activation.helper.php');
123
-        $table_name = 'esp_answer';
124
-        $sql = " ANS_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
119
+	public function schema_changes_before_migration()
120
+	{
121
+		//relies on 4.1's EEH_Activation::create_table
122
+		require_once(EE_HELPERS . 'EEH_Activation.helper.php');
123
+		$table_name = 'esp_answer';
124
+		$sql = " ANS_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
125 125
 					REG_ID INT UNSIGNED NOT NULL,
126 126
 					QST_ID INT UNSIGNED NOT NULL,
127 127
 					ANS_value TEXT NOT NULL,
128 128
 					PRIMARY KEY  (ANS_ID)";
129
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
130
-        $table_name = 'esp_attendee_meta';
131
-        $sql = "ATTM_ID INT(10) UNSIGNED NOT	NULL AUTO_INCREMENT,
129
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
130
+		$table_name = 'esp_attendee_meta';
131
+		$sql = "ATTM_ID INT(10) UNSIGNED NOT	NULL AUTO_INCREMENT,
132 132
 						ATT_ID BIGINT(20) UNSIGNED NOT NULL,
133 133
 						ATT_fname VARCHAR(45) NOT NULL,
134 134
 						ATT_lname VARCHAR(45) NOT	NULL,
@@ -144,9 +144,9 @@  discard block
 block discarded – undo
144 144
 								KEY ATT_fname (ATT_fname),
145 145
 								KEY ATT_lname (ATT_lname),
146 146
 								KEY ATT_email (ATT_email)";
147
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
148
-        $table_name = 'esp_country';
149
-        $sql = "CNT_ISO VARCHAR(2) COLLATE utf8_bin NOT NULL,
147
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
148
+		$table_name = 'esp_country';
149
+		$sql = "CNT_ISO VARCHAR(2) COLLATE utf8_bin NOT NULL,
150 150
 					  CNT_ISO3 VARCHAR(3) COLLATE utf8_bin NOT NULL,
151 151
 					  RGN_ID TINYINT(3) UNSIGNED DEFAULT NULL,
152 152
 					  CNT_name VARCHAR(45) COLLATE utf8_bin NOT NULL,
@@ -162,9 +162,9 @@  discard block
 block discarded – undo
162 162
 					  CNT_is_EU TINYINT(1) DEFAULT '0',
163 163
 					  CNT_active TINYINT(1) DEFAULT '0',
164 164
 					  PRIMARY KEY  (CNT_ISO)";
165
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
166
-        $table_name = 'esp_datetime';
167
-        $sql = "DTT_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
165
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
166
+		$table_name = 'esp_datetime';
167
+		$sql = "DTT_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
168 168
 				  EVT_ID BIGINT(20) UNSIGNED NOT NULL,
169 169
 				  DTT_EVT_start DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
170 170
 				  DTT_EVT_end DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -177,9 +177,9 @@  discard block
 block discarded – undo
177 177
 						PRIMARY KEY  (DTT_ID),
178 178
 						KEY EVT_ID (EVT_ID),
179 179
 						KEY DTT_is_primary (DTT_is_primary)";
180
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
181
-        $table_name = 'esp_event_meta';
182
-        $sql = "
180
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
181
+		$table_name = 'esp_event_meta';
182
+		$sql = "
183 183
 			EVTM_ID INT NOT NULL AUTO_INCREMENT,
184 184
 			EVT_ID BIGINT(20) UNSIGNED NOT NULL,
185 185
 			EVT_display_desc TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
@@ -194,31 +194,31 @@  discard block
 block discarded – undo
194 194
 			EVT_external_URL VARCHAR(200) NULL,
195 195
 			EVT_donations TINYINT(1) NULL,
196 196
 			PRIMARY KEY  (EVTM_ID)";
197
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
198
-        $table_name = 'esp_event_question_group';
199
-        $sql = "EQG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
197
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
198
+		$table_name = 'esp_event_question_group';
199
+		$sql = "EQG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
200 200
 					EVT_ID BIGINT(20) UNSIGNED NOT NULL,
201 201
 					QSG_ID INT UNSIGNED NOT NULL,
202 202
 					EQG_primary TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
203 203
 					PRIMARY KEY  (EQG_ID)";
204
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
205
-        $table_name = 'esp_event_venue';
206
-        $sql = "EVV_ID INT(11) NOT NULL AUTO_INCREMENT,
204
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
205
+		$table_name = 'esp_event_venue';
206
+		$sql = "EVV_ID INT(11) NOT NULL AUTO_INCREMENT,
207 207
 				EVT_ID BIGINT(20) UNSIGNED NOT NULL,
208 208
 				VNU_ID BIGINT(20) UNSIGNED NOT NULL,
209 209
 				EVV_primary TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
210 210
 				PRIMARY KEY  (EVV_ID)";
211
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
212
-        $table_name = 'esp_extra_meta';
213
-        $sql = "EXM_ID INT(11) NOT NULL AUTO_INCREMENT,
211
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
212
+		$table_name = 'esp_extra_meta';
213
+		$sql = "EXM_ID INT(11) NOT NULL AUTO_INCREMENT,
214 214
 				OBJ_ID INT(11) DEFAULT NULL,
215 215
 				EXM_type VARCHAR(45) DEFAULT NULL,
216 216
 				EXM_key VARCHAR(45) DEFAULT NULL,
217 217
 				EXM_value TEXT,
218 218
 				PRIMARY KEY  (EXM_ID)";
219
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
220
-        $table_name = 'esp_line_item';
221
-        $sql = "LIN_ID INT(11) NOT NULL AUTO_INCREMENT,
219
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
220
+		$table_name = 'esp_line_item';
221
+		$sql = "LIN_ID INT(11) NOT NULL AUTO_INCREMENT,
222 222
 				LIN_code VARCHAR(245) NOT NULL DEFAULT '',
223 223
 				TXN_ID INT(11) DEFAULT NULL,
224 224
 				LIN_name VARCHAR(245) NOT NULL DEFAULT '',
@@ -234,18 +234,18 @@  discard block
 block discarded – undo
234 234
 				OBJ_ID INT(11) DEFAULT NULL,
235 235
 				OBJ_type VARCHAR(45)DEFAULT NULL,
236 236
 				PRIMARY KEY  (LIN_ID)";
237
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
238
-        $table_name = 'esp_message_template';
239
-        $sql = "MTP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
237
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
238
+		$table_name = 'esp_message_template';
239
+		$sql = "MTP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
240 240
 					GRP_ID INT(10) UNSIGNED NOT NULL,
241 241
 					MTP_context VARCHAR(50) NOT NULL,
242 242
 					MTP_template_field VARCHAR(30) NOT NULL,
243 243
 					MTP_content TEXT NOT NULL,
244 244
 					PRIMARY KEY  (MTP_ID),
245 245
 					KEY GRP_ID (GRP_ID)";
246
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
247
-        $table_name = 'esp_message_template_group';
248
-        $sql = "GRP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
246
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
247
+		$table_name = 'esp_message_template_group';
248
+		$sql = "GRP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
249 249
 					EVT_ID BIGINT(20) UNSIGNED DEFAULT NULL,
250 250
 					MTP_user_id INT(10) NOT NULL DEFAULT '1',
251 251
 					MTP_messenger VARCHAR(30) NOT NULL,
@@ -257,9 +257,9 @@  discard block
 block discarded – undo
257 257
 					PRIMARY KEY  (GRP_ID),
258 258
 					KEY EVT_ID (EVT_ID),
259 259
 					KEY MTP_user_id (MTP_user_id)";
260
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
261
-        $table_name = 'esp_payment';
262
-        $sql = "PAY_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
260
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
261
+		$table_name = 'esp_payment';
262
+		$sql = "PAY_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
263 263
 					TXN_ID INT(10) UNSIGNED DEFAULT NULL,
264 264
 					STS_ID VARCHAR(3) COLLATE utf8_bin DEFAULT NULL,
265 265
 					PAY_timestamp DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -275,9 +275,9 @@  discard block
 block discarded – undo
275 275
 					PRIMARY KEY  (PAY_ID),
276 276
 					KEY TXN_ID (TXN_ID),
277 277
 					KEY PAY_timestamp (PAY_timestamp)";
278
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
279
-        $table_name = "esp_ticket";
280
-        $sql = "TKT_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
278
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
279
+		$table_name = "esp_ticket";
280
+		$sql = "TKT_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
281 281
 					  TTM_ID INT(10) UNSIGNED NOT NULL,
282 282
 					  TKT_name VARCHAR(245) NOT NULL DEFAULT '',
283 283
 					  TKT_description TEXT NOT NULL,
@@ -296,28 +296,28 @@  discard block
 block discarded – undo
296 296
 					  TKT_parent INT(10) UNSIGNED DEFAULT '0',
297 297
 					  TKT_deleted TINYINT(1) NOT NULL DEFAULT '0',
298 298
 					  PRIMARY KEY  (TKT_ID)";
299
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
300
-        $table_name = "esp_ticket_price";
301
-        $sql = "TKP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
299
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
300
+		$table_name = "esp_ticket_price";
301
+		$sql = "TKP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
302 302
 					  TKT_ID INT(10) UNSIGNED NOT NULL,
303 303
 					  PRC_ID INT(10) UNSIGNED NOT NULL,
304 304
 					  PRIMARY KEY  (TKP_ID)";
305
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
306
-        $table_name = "esp_datetime_ticket";
307
-        $sql = "DTK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
305
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
306
+		$table_name = "esp_datetime_ticket";
307
+		$sql = "DTK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
308 308
 					  DTT_ID INT(10) UNSIGNED NOT NULL,
309 309
 					  TKT_ID INT(10) UNSIGNED NOT NULL,
310 310
 					  PRIMARY KEY  (DTK_ID)";
311
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
312
-        $table_name = "esp_ticket_template";
313
-        $sql = "TTM_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
311
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
312
+		$table_name = "esp_ticket_template";
313
+		$sql = "TTM_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
314 314
 					  TTM_name VARCHAR(45) NOT NULL,
315 315
 					  TTM_description TEXT,
316 316
 					  TTM_file VARCHAR(45),
317 317
 					  PRIMARY KEY  (TTM_ID)";
318
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
319
-        $table_name = "esp_price";
320
-        $sql = "PRC_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
318
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
319
+		$table_name = "esp_price";
320
+		$sql = "PRC_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
321 321
 					  PRT_ID TINYINT(3) UNSIGNED NOT NULL,
322 322
 					  PRC_amount DECIMAL(10,3) NOT NULL DEFAULT '0.00',
323 323
 					  PRC_name VARCHAR(245) NOT NULL,
@@ -328,9 +328,9 @@  discard block
 block discarded – undo
328 328
 					  PRC_order TINYINT(3) UNSIGNED NOT NULL DEFAULT '0',
329 329
 					  PRC_parent INT(10) UNSIGNED DEFAULT 0,
330 330
 					  PRIMARY KEY  (PRC_ID)";
331
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
332
-        $table_name = "esp_price_type";
333
-        $sql = "PRT_ID TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
331
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
332
+		$table_name = "esp_price_type";
333
+		$sql = "PRT_ID TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
334 334
 				  PRT_name VARCHAR(45) NOT NULL,
335 335
 				  PBT_ID TINYINT(3) UNSIGNED NOT NULL DEFAULT '1',
336 336
 				  PRT_is_percent TINYINT(1) NOT NULL DEFAULT '0',
@@ -338,9 +338,9 @@  discard block
 block discarded – undo
338 338
 				  PRT_deleted TINYINT(1) NOT NULL DEFAULT '0',
339 339
 				  UNIQUE KEY PRT_name_UNIQUE (PRT_name),
340 340
 				  PRIMARY KEY  (PRT_ID)";
341
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
342
-        $table_name = 'esp_question';
343
-        $sql = 'QST_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
341
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
342
+		$table_name = 'esp_question';
343
+		$sql = 'QST_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
344 344
 					QST_display_text TEXT NOT NULL,
345 345
 					QST_admin_label VARCHAR(255) NOT NULL,
346 346
 					QST_system VARCHAR(25) DEFAULT NULL,
@@ -352,10 +352,10 @@  discard block
 block discarded – undo
352 352
 					QST_wp_user BIGINT UNSIGNED NULL,
353 353
 					QST_deleted TINYINT UNSIGNED NOT NULL DEFAULT 0,
354 354
 					PRIMARY KEY  (QST_ID)';
355
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
356
-        $this->_get_table_manager()->dropIndex('esp_question_group', 'QSG_identifier_UNIQUE');
357
-        $table_name = 'esp_question_group';
358
-        $sql = 'QSG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
355
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
356
+		$this->_get_table_manager()->dropIndex('esp_question_group', 'QSG_identifier_UNIQUE');
357
+		$table_name = 'esp_question_group';
358
+		$sql = 'QSG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
359 359
 					QSG_name VARCHAR(255) NOT NULL,
360 360
 					QSG_identifier VARCHAR(100) NOT NULL,
361 361
 					QSG_desc TEXT NULL,
@@ -366,23 +366,23 @@  discard block
 block discarded – undo
366 366
 					QSG_deleted TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
367 367
 					PRIMARY KEY  (QSG_ID),
368 368
 					UNIQUE KEY QSG_identifier_UNIQUE (QSG_identifier ASC)';
369
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
370
-        $table_name = 'esp_question_group_question';
371
-        $sql = "QGQ_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
369
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
370
+		$table_name = 'esp_question_group_question';
371
+		$sql = "QGQ_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
372 372
 					QSG_ID INT UNSIGNED NOT NULL,
373 373
 					QST_ID INT UNSIGNED NOT NULL,
374 374
 					PRIMARY KEY  (QGQ_ID) ";
375
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
376
-        $table_name = 'esp_question_option';
377
-        $sql = "QSO_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
375
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
376
+		$table_name = 'esp_question_option';
377
+		$sql = "QSO_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
378 378
 					QSO_value VARCHAR(255) NOT NULL,
379 379
 					QSO_desc TEXT NOT NULL,
380 380
 					QST_ID INT UNSIGNED NOT NULL,
381 381
 					QSO_deleted TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
382 382
 					PRIMARY KEY  (QSO_ID)";
383
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
384
-        $table_name = 'esp_registration';
385
-        $sql = "REG_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
383
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
384
+		$table_name = 'esp_registration';
385
+		$sql = "REG_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
386 386
 					  EVT_ID BIGINT(20) UNSIGNED NOT NULL,
387 387
 					  ATT_ID BIGINT(20) UNSIGNED NOT NULL,
388 388
 					  TXN_ID INT(10) UNSIGNED NOT NULL,
@@ -405,25 +405,25 @@  discard block
 block discarded – undo
405 405
 					  KEY STS_ID (STS_ID),
406 406
 					  KEY REG_url_link (REG_url_link),
407 407
 					  KEY REG_code (REG_code)";
408
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
409
-        $table_name = 'esp_checkin';
410
-        $sql = "CHK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
408
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
409
+		$table_name = 'esp_checkin';
410
+		$sql = "CHK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
411 411
 					REG_ID INT(10) UNSIGNED NOT NULL,
412 412
 					DTT_ID INT(10) UNSIGNED NOT NULL,
413 413
 					CHK_in TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
414 414
 					CHK_timestamp DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
415 415
 					PRIMARY KEY  (CHK_ID)";
416
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
417
-        $table_name = 'esp_state';
418
-        $sql = "STA_ID smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT,
416
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
417
+		$table_name = 'esp_state';
418
+		$sql = "STA_ID smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT,
419 419
 					  CNT_ISO VARCHAR(2) COLLATE utf8_bin NOT NULL,
420 420
 					  STA_abbrev VARCHAR(6) COLLATE utf8_bin NOT NULL,
421 421
 					  STA_name VARCHAR(100) COLLATE utf8_bin NOT NULL,
422 422
 					  STA_active TINYINT(1) DEFAULT '1',
423 423
 					  PRIMARY KEY  (STA_ID)";
424
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
425
-        $table_name = 'esp_status';
426
-        $sql = "STS_ID VARCHAR(3) COLLATE utf8_bin NOT NULL,
424
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
425
+		$table_name = 'esp_status';
426
+		$sql = "STS_ID VARCHAR(3) COLLATE utf8_bin NOT NULL,
427 427
 					  STS_code VARCHAR(45) COLLATE utf8_bin NOT NULL,
428 428
 					  STS_type set('event','registration','transaction','payment','email') COLLATE utf8_bin NOT NULL,
429 429
 					  STS_can_edit TINYINT(1) NOT NULL DEFAULT 0,
@@ -431,9 +431,9 @@  discard block
 block discarded – undo
431 431
 					  STS_open TINYINT(1) NOT NULL DEFAULT 1,
432 432
 					  UNIQUE KEY STS_ID_UNIQUE (STS_ID),
433 433
 					  KEY STS_type (STS_type)";
434
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
435
-        $table_name = 'esp_transaction';
436
-        $sql = "TXN_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
434
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
435
+		$table_name = 'esp_transaction';
436
+		$sql = "TXN_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
437 437
 					  TXN_timestamp DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
438 438
 					  TXN_total DECIMAL(10,3) DEFAULT '0.00',
439 439
 					  TXN_paid DECIMAL(10,3) NOT NULL DEFAULT '0.00',
@@ -443,9 +443,9 @@  discard block
 block discarded – undo
443 443
 					  PRIMARY KEY  (TXN_ID),
444 444
 					  KEY TXN_timestamp (TXN_timestamp),
445 445
 					  KEY STS_ID (STS_ID)";
446
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
447
-        $table_name = 'esp_venue_meta';
448
-        $sql = "VNUM_ID INT(11) NOT NULL AUTO_INCREMENT,
446
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
447
+		$table_name = 'esp_venue_meta';
448
+		$sql = "VNUM_ID INT(11) NOT NULL AUTO_INCREMENT,
449 449
 			VNU_ID BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
450 450
 			VNU_address VARCHAR(255) DEFAULT NULL,
451 451
 			VNU_address2 VARCHAR(255) DEFAULT NULL,
@@ -463,52 +463,52 @@  discard block
 block discarded – undo
463 463
 			PRIMARY KEY  (VNUM_ID),
464 464
 			KEY STA_ID (STA_ID),
465 465
 			KEY CNT_ISO (CNT_ISO)";
466
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
467
-        //setting up the DEFAULT stats and countries is also essential for the data migrations to run
468
-        //(because many need to convert old string states to foreign keys into the states table)
469
-        $this->insert_default_states();
470
-        $this->insert_default_countries();
471
-        //setting up DEFAULT prices, price types, and tickets is also essential for the price migrations
472
-        $this->insert_default_price_types();
473
-        $this->insert_default_prices();
474
-        $this->insert_default_tickets();
475
-        //setting up the config wp option pretty well counts as a 'schema change', or at least should happen ehre
476
-        EE_Config::instance()->update_espresso_config(false, true);
477
-        return true;
478
-    }
479
-
480
-
481
-
482
-    /**
483
-     * Yes we could have cleaned up the ee3 tables here. But just in case someone
484
-     * didn't backup their DB, and decides they want ot keep using EE3, we'll
485
-     * leave them for now. Mayeb remove them in 4.5 or something.
486
-     *
487
-     * @return boolean
488
-     */
489
-    public function schema_changes_after_migration()
490
-    {
491
-        return true;
492
-    }
493
-
494
-
495
-
496
-    /**
497
-     * insert_default_states
498
-     *
499
-     * @access public
500
-     * @static
501
-     * @return void
502
-     */
503
-    public function insert_default_states()
504
-    {
505
-        global $wpdb;
506
-        $state_table = $wpdb->prefix . "esp_state";
507
-        if ($this->_get_table_analysis()->tableExists($state_table)) {
508
-            $SQL = "SELECT COUNT('STA_ID') FROM " . $state_table;
509
-            $states = $wpdb->get_var($SQL);
510
-            if ( ! $states) {
511
-                $SQL = "INSERT INTO " . $state_table . "
466
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
467
+		//setting up the DEFAULT stats and countries is also essential for the data migrations to run
468
+		//(because many need to convert old string states to foreign keys into the states table)
469
+		$this->insert_default_states();
470
+		$this->insert_default_countries();
471
+		//setting up DEFAULT prices, price types, and tickets is also essential for the price migrations
472
+		$this->insert_default_price_types();
473
+		$this->insert_default_prices();
474
+		$this->insert_default_tickets();
475
+		//setting up the config wp option pretty well counts as a 'schema change', or at least should happen ehre
476
+		EE_Config::instance()->update_espresso_config(false, true);
477
+		return true;
478
+	}
479
+
480
+
481
+
482
+	/**
483
+	 * Yes we could have cleaned up the ee3 tables here. But just in case someone
484
+	 * didn't backup their DB, and decides they want ot keep using EE3, we'll
485
+	 * leave them for now. Mayeb remove them in 4.5 or something.
486
+	 *
487
+	 * @return boolean
488
+	 */
489
+	public function schema_changes_after_migration()
490
+	{
491
+		return true;
492
+	}
493
+
494
+
495
+
496
+	/**
497
+	 * insert_default_states
498
+	 *
499
+	 * @access public
500
+	 * @static
501
+	 * @return void
502
+	 */
503
+	public function insert_default_states()
504
+	{
505
+		global $wpdb;
506
+		$state_table = $wpdb->prefix . "esp_state";
507
+		if ($this->_get_table_analysis()->tableExists($state_table)) {
508
+			$SQL = "SELECT COUNT('STA_ID') FROM " . $state_table;
509
+			$states = $wpdb->get_var($SQL);
510
+			if ( ! $states) {
511
+				$SQL = "INSERT INTO " . $state_table . "
512 512
 				(STA_ID, CNT_ISO, STA_abbrev, STA_name, STA_active) VALUES
513 513
 				(1, 'US', 'AK', 'Alaska', 1),
514 514
 				(2, 'US', 'AL', 'Alabama', 1),
@@ -579,29 +579,29 @@  discard block
 block discarded – undo
579 579
 				(67, 'CA', 'PE', 'Prince Edward Island', 1),
580 580
 				(68, 'CA', 'QC', 'Quebec', 1),
581 581
 				(69, 'CA', 'SK', 'Saskatchewan', 1);";
582
-                $wpdb->query($SQL);
583
-            }
584
-        }
585
-    }
586
-
587
-
588
-
589
-    /**
590
-     * insert_default_countries
591
-     *
592
-     * @access public
593
-     * @static
594
-     * @return void
595
-     */
596
-    public function insert_default_countries()
597
-    {
598
-        global $wpdb;
599
-        $country_table = $wpdb->prefix . "esp_country";
600
-        if ($this->_get_table_analysis()->tableExists($country_table)) {
601
-            $SQL = "SELECT COUNT('CNT_ISO') FROM " . $country_table;
602
-            $countries = $wpdb->get_var($SQL);
603
-            if ( ! $countries) {
604
-                $SQL = "INSERT INTO " . $country_table . "
582
+				$wpdb->query($SQL);
583
+			}
584
+		}
585
+	}
586
+
587
+
588
+
589
+	/**
590
+	 * insert_default_countries
591
+	 *
592
+	 * @access public
593
+	 * @static
594
+	 * @return void
595
+	 */
596
+	public function insert_default_countries()
597
+	{
598
+		global $wpdb;
599
+		$country_table = $wpdb->prefix . "esp_country";
600
+		if ($this->_get_table_analysis()->tableExists($country_table)) {
601
+			$SQL = "SELECT COUNT('CNT_ISO') FROM " . $country_table;
602
+			$countries = $wpdb->get_var($SQL);
603
+			if ( ! $countries) {
604
+				$SQL = "INSERT INTO " . $country_table . "
605 605
 				(CNT_ISO, CNT_ISO3, RGN_ID, CNT_name, CNT_cur_code, CNT_cur_single, CNT_cur_plural, CNT_cur_sign, CNT_cur_sign_b4, CNT_cur_dec_plc, CNT_tel_code, CNT_is_EU, CNT_active) VALUES
606 606
 				('AD', 'AND', 0, 'Andorra', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+376', 0, 0),
607 607
 				('AE', 'ARE', 0, 'United Arab Emirates', 'AED', 'Dirham', 'Dirhams', 'د.إ', 1, 2, '+971', 0, 0),
@@ -829,943 +829,943 @@  discard block
 block discarded – undo
829 829
 				('ZA', 'ZAF', 0, 'South Africa', 'ZAR', 'Rand', 'Rands', 'R', 1, 2, '+27', 0, 0),
830 830
 				('ZM', 'ZMB', 0, 'Zambia', 'ZMK', 'Kwacha', 'Kwachas', '', 1, 2, '+260', 0, 0),
831 831
 				('ZW', 'ZWE', 0, 'Zimbabwe', 'ZWD', 'Dollar', 'Dollars', 'Z$', 1, 2, '+263', 0, 0);";
832
-                $wpdb->query($SQL);
833
-            }
834
-        }
835
-    }
836
-
837
-
838
-
839
-    /**
840
-     * insert_default_price_types
841
-     *
842
-     * @access public
843
-     * @static
844
-     * @return void
845
-     */
846
-    public function insert_default_price_types()
847
-    {
848
-        global $wpdb;
849
-        $price_type_table = $wpdb->prefix . "esp_price_type";
850
-        if ($this->_get_table_analysis()->tableExists($price_type_table)) {
851
-            $SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table;
852
-            $price_types_exist = $wpdb->get_var($SQL);
853
-            if ( ! $price_types_exist) {
854
-                $SQL = "INSERT INTO $price_type_table ( PRT_ID, PRT_name, PBT_ID, PRT_is_percent, PRT_order, PRT_deleted ) VALUES
832
+				$wpdb->query($SQL);
833
+			}
834
+		}
835
+	}
836
+
837
+
838
+
839
+	/**
840
+	 * insert_default_price_types
841
+	 *
842
+	 * @access public
843
+	 * @static
844
+	 * @return void
845
+	 */
846
+	public function insert_default_price_types()
847
+	{
848
+		global $wpdb;
849
+		$price_type_table = $wpdb->prefix . "esp_price_type";
850
+		if ($this->_get_table_analysis()->tableExists($price_type_table)) {
851
+			$SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table;
852
+			$price_types_exist = $wpdb->get_var($SQL);
853
+			if ( ! $price_types_exist) {
854
+				$SQL = "INSERT INTO $price_type_table ( PRT_ID, PRT_name, PBT_ID, PRT_is_percent, PRT_order, PRT_deleted ) VALUES
855 855
 							(1, '" . esc_html__('Base Price', 'event_espresso') . "', 1,  0, 0, 0),
856 856
 							(2, '" . esc_html__('Percent Discount', 'event_espresso') . "', 2,  1, 20, 0),
857 857
 							(3, '" . esc_html__('Fixed Discount', 'event_espresso') . "', 2,  0, 30, 0),
858 858
 							(4, '" . esc_html__('Percent Surcharge', 'event_espresso') . "', 3,  1, 40, 0),
859 859
 							(5, '" . esc_html__('Fixed Surcharge', 'event_espresso') . "', 3,  0, 50, 0);";
860
-                $SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_price_types__SQL', $SQL);
861
-                $wpdb->query($SQL);
862
-            }
863
-        }
864
-    }
865
-
866
-
867
-
868
-    /**
869
-     * insert_default_prices. We assume we're upgrading to regular here.
870
-     * If we're INSTALLING 4.1 CAF, then we add a few extra DEFAULT prices
871
-     * when EEH_Activaion's initialize_db_content is called via  ahook in
872
-     * EE_BRewing_regular
873
-     *
874
-     * @access public
875
-     * @static
876
-     * @return void
877
-     */
878
-    public function insert_default_prices()
879
-    {
880
-        global $wpdb;
881
-        $price_table = $wpdb->prefix . "esp_price";
882
-        if ($this->_get_table_analysis()->tableExists($price_table)) {
883
-            $SQL = 'SELECT COUNT(PRC_ID) FROM ' . $price_table;
884
-            $prices_exist = $wpdb->get_var($SQL);
885
-            if ( ! $prices_exist) {
886
-                $SQL = "INSERT INTO $price_table
860
+				$SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_price_types__SQL', $SQL);
861
+				$wpdb->query($SQL);
862
+			}
863
+		}
864
+	}
865
+
866
+
867
+
868
+	/**
869
+	 * insert_default_prices. We assume we're upgrading to regular here.
870
+	 * If we're INSTALLING 4.1 CAF, then we add a few extra DEFAULT prices
871
+	 * when EEH_Activaion's initialize_db_content is called via  ahook in
872
+	 * EE_BRewing_regular
873
+	 *
874
+	 * @access public
875
+	 * @static
876
+	 * @return void
877
+	 */
878
+	public function insert_default_prices()
879
+	{
880
+		global $wpdb;
881
+		$price_table = $wpdb->prefix . "esp_price";
882
+		if ($this->_get_table_analysis()->tableExists($price_table)) {
883
+			$SQL = 'SELECT COUNT(PRC_ID) FROM ' . $price_table;
884
+			$prices_exist = $wpdb->get_var($SQL);
885
+			if ( ! $prices_exist) {
886
+				$SQL = "INSERT INTO $price_table
887 887
 							(PRC_ID, PRT_ID, PRC_amount, PRC_name, PRC_desc,  PRC_is_default, PRC_overrides, PRC_order, PRC_deleted, PRC_parent ) VALUES
888 888
 							(1, 1, '0.00', 'Free Admission', '', 1, NULL, 0, 0, 0);";
889
-                $SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_prices__SQL', $SQL);
890
-                $wpdb->query($SQL);
891
-            }
892
-        }
893
-    }
894
-
895
-
896
-
897
-    /**
898
-     * insert DEFAULT ticket
899
-     *
900
-     * @access public
901
-     * @static
902
-     * @return void
903
-     */
904
-    public function insert_default_tickets()
905
-    {
906
-        global $wpdb;
907
-        $ticket_table = $wpdb->prefix . "esp_ticket";
908
-        if ($this->_get_table_analysis()->tableExists($ticket_table)) {
909
-            $SQL = 'SELECT COUNT(TKT_ID) FROM ' . $ticket_table;
910
-            $tickets_exist = $wpdb->get_var($SQL);
911
-            if ( ! $tickets_exist) {
912
-                $SQL = "INSERT INTO $ticket_table
889
+				$SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_prices__SQL', $SQL);
890
+				$wpdb->query($SQL);
891
+			}
892
+		}
893
+	}
894
+
895
+
896
+
897
+	/**
898
+	 * insert DEFAULT ticket
899
+	 *
900
+	 * @access public
901
+	 * @static
902
+	 * @return void
903
+	 */
904
+	public function insert_default_tickets()
905
+	{
906
+		global $wpdb;
907
+		$ticket_table = $wpdb->prefix . "esp_ticket";
908
+		if ($this->_get_table_analysis()->tableExists($ticket_table)) {
909
+			$SQL = 'SELECT COUNT(TKT_ID) FROM ' . $ticket_table;
910
+			$tickets_exist = $wpdb->get_var($SQL);
911
+			if ( ! $tickets_exist) {
912
+				$SQL = "INSERT INTO $ticket_table
913 913
 					( TKT_ID, TTM_ID, TKT_name, TKT_description, TKT_qty, TKT_sold, TKT_uses, TKT_min, TKT_max, TKT_price, TKT_start_date, TKT_end_date, TKT_taxable, TKT_order, TKT_row, TKT_is_default, TKT_parent, TKT_deleted ) VALUES
914 914
 					( 1, 0, '"
915
-                       . esc_html__("Free Ticket", "event_espresso")
916
-                       . "', '', 100, 0, -1, 0, -1, 0.00, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, 0, 1, 1, 0, 0);";
917
-                $SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_tickets__SQL', $SQL);
918
-                $wpdb->query($SQL);
919
-            }
920
-        }
921
-        $ticket_price_table = $wpdb->prefix . "esp_ticket_price";
922
-        if ($this->_get_table_analysis()->tableExists($ticket_price_table)) {
923
-            $SQL = 'SELECT COUNT(TKP_ID) FROM ' . $ticket_price_table;
924
-            $ticket_prc_exist = $wpdb->get_var($SQL);
925
-            if ( ! $ticket_prc_exist) {
926
-                $SQL = "INSERT INTO $ticket_price_table
915
+					   . esc_html__("Free Ticket", "event_espresso")
916
+					   . "', '', 100, 0, -1, 0, -1, 0.00, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, 0, 1, 1, 0, 0);";
917
+				$SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_tickets__SQL', $SQL);
918
+				$wpdb->query($SQL);
919
+			}
920
+		}
921
+		$ticket_price_table = $wpdb->prefix . "esp_ticket_price";
922
+		if ($this->_get_table_analysis()->tableExists($ticket_price_table)) {
923
+			$SQL = 'SELECT COUNT(TKP_ID) FROM ' . $ticket_price_table;
924
+			$ticket_prc_exist = $wpdb->get_var($SQL);
925
+			if ( ! $ticket_prc_exist) {
926
+				$SQL = "INSERT INTO $ticket_price_table
927 927
 				( TKP_ID, TKT_ID, PRC_ID ) VALUES
928 928
 				( 1, 1, 1 )
929 929
 				";
930
-                $SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_tickets__SQL__ticket_price', $SQL);
931
-                $wpdb->query($SQL);
932
-            }
933
-        }
934
-    }
935
-
936
-
937
-
938
-    /**
939
-     * Gets a country entry as an array, or creates one if none is found. Much like EEM_Country::instance()->get_one(),
940
-     * but is independent of outside code which can change in future versions of EE. Also, $country_name CAN be a 3.1
941
-     * country ID (int), a 2-letter ISO, 3-letter ISO, or name
942
-     *
943
-     * @global type  $wpdb
944
-     * @param string $country_name
945
-     * @return array where keys are columns, values are column values
946
-     */
947
-    public function get_or_create_country($country_name)
948
-    {
949
-        if ( ! $country_name) {
950
-            throw new EE_Error(esc_html__("Could not get a country because country name is blank", "event_espresso"));
951
-        }
952
-        global $wpdb;
953
-        $country_table = $wpdb->prefix . "esp_country";
954
-        if (is_int($country_name)) {
955
-            $country_name = $this->get_iso_from_3_1_country_id($country_name);
956
-        }
957
-        $country = $wpdb->get_row($wpdb->prepare("SELECT * FROM $country_table WHERE
930
+				$SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_tickets__SQL__ticket_price', $SQL);
931
+				$wpdb->query($SQL);
932
+			}
933
+		}
934
+	}
935
+
936
+
937
+
938
+	/**
939
+	 * Gets a country entry as an array, or creates one if none is found. Much like EEM_Country::instance()->get_one(),
940
+	 * but is independent of outside code which can change in future versions of EE. Also, $country_name CAN be a 3.1
941
+	 * country ID (int), a 2-letter ISO, 3-letter ISO, or name
942
+	 *
943
+	 * @global type  $wpdb
944
+	 * @param string $country_name
945
+	 * @return array where keys are columns, values are column values
946
+	 */
947
+	public function get_or_create_country($country_name)
948
+	{
949
+		if ( ! $country_name) {
950
+			throw new EE_Error(esc_html__("Could not get a country because country name is blank", "event_espresso"));
951
+		}
952
+		global $wpdb;
953
+		$country_table = $wpdb->prefix . "esp_country";
954
+		if (is_int($country_name)) {
955
+			$country_name = $this->get_iso_from_3_1_country_id($country_name);
956
+		}
957
+		$country = $wpdb->get_row($wpdb->prepare("SELECT * FROM $country_table WHERE
958 958
 			CNT_ISO LIKE %s OR
959 959
 			CNT_ISO3 LIKE %s OR
960 960
 			CNT_name LIKE %s LIMIT 1", $country_name, $country_name, $country_name), ARRAY_A);
961
-        if ( ! $country) {
962
-            //insert a new one then
963
-            $cols_n_values = array(
964
-                    'CNT_ISO'         => $this->_find_available_country_iso(2),
965
-                    'CNT_ISO3'        => $this->_find_available_country_iso(3),
966
-                    'RGN_ID'          => 0,
967
-                    'CNT_name'        => $country_name,
968
-                    'CNT_cur_code'    => 'USD',
969
-                    'CNT_cur_single'  => 'Dollar',
970
-                    'CNT_cur_plural'  => 'Dollars',
971
-                    'CNT_cur_sign'    => '&#36;',
972
-                    'CNT_cur_sign_b4' => true,
973
-                    'CNT_cur_dec_plc' => 2,
974
-                    'CNT_cur_dec_mrk' => '.',
975
-                    'CNT_cur_thsnds'  => ',',
976
-                    'CNT_tel_code'    => '+1',
977
-                    'CNT_is_EU'       => false,
978
-                    'CNT_active'      => true,
979
-            );
980
-            $data_types = array(
981
-                    '%s',//CNT_ISO
982
-                    '%s',//CNT_ISO3
983
-                    '%d',//RGN_ID
984
-                    '%s',//CNT_name
985
-                    '%s',//CNT_cur_code
986
-                    '%s',//CNT_cur_single
987
-                    '%s',//CNT_cur_plural
988
-                    '%s',//CNT_cur_sign
989
-                    '%d',//CNT_cur_sign_b4
990
-                    '%d',//CNT_cur_dec_plc
991
-                    '%s',//CNT_cur_dec_mrk
992
-                    '%s',//CNT_cur_thsnds
993
-                    '%s',//CNT_tel_code
994
-                    '%d',//CNT_is_EU
995
-                    '%d',//CNT_active
996
-            );
997
-            $success = $wpdb->insert($country_table,
998
-                    $cols_n_values,
999
-                    $data_types);
1000
-            if ( ! $success) {
1001
-                throw new EE_Error($this->_create_error_message_for_db_insertion('N/A',
1002
-                        array('country_id' => $country_name), $country_table, $cols_n_values, $data_types));
1003
-            }
1004
-            $country = $cols_n_values;
1005
-        }
1006
-        return $country;
1007
-    }
1008
-
1009
-
1010
-
1011
-    /**
1012
-     * finds a country iso which hasnt been used yet
1013
-     *
1014
-     * @global type $wpdb
1015
-     * @return string
1016
-     */
1017
-    private function _find_available_country_iso($num_letters = 2)
1018
-    {
1019
-        global $wpdb;
1020
-        $country_table = $wpdb->prefix . "esp_country";
1021
-        $attempts = 0;
1022
-        do {
1023
-            $current_iso = strtoupper(wp_generate_password($num_letters, false));
1024
-            $country_with_that_iso = $wpdb->get_var($wpdb->prepare("SELECT count(CNT_ISO) FROM "
1025
-                                                                   . $country_table
1026
-                                                                   . " WHERE CNT_ISO=%s", $current_iso));
1027
-            $attempts++;
1028
-            //keep going until we find an available country code, or we arbitrarily
1029
-            //decide we've tried this enough. Somehow they have way too many countries
1030
-            //(probably because they're mis-using the EE3 country_id like a custom question)
1031
-        } while (intval($country_with_that_iso) && $attempts < 200);
1032
-        return $current_iso;
1033
-    }
1034
-
1035
-
1036
-
1037
-    /**
1038
-     * Gets a state entry as an array, or creates one if none is found. Much like EEM_State::instance()->get_one(), but
1039
-     * is independent of outside code which can change in future versions of EE
1040
-     *
1041
-     * @global type  $wpdb
1042
-     * @param string $state_name
1043
-     * @return array where keys are columns, values are column values
1044
-     */
1045
-    public function get_or_create_state($state_name, $country_name = '')
1046
-    {
1047
-        if ( ! $state_name) {
1048
-            throw new EE_Error(esc_html__("Could not get-or-create state because no state name was provided",
1049
-                    "event_espresso"));
1050
-        }
1051
-        try {
1052
-            $country = $this->get_or_create_country($country_name);
1053
-            $country_iso = $country['CNT_ISO'];
1054
-        } catch (EE_Error $e) {
1055
-            $country_iso = $this->get_default_country_iso();
1056
-        }
1057
-        global $wpdb;
1058
-        $state_table = $wpdb->prefix . "esp_state";
1059
-        $state = $wpdb->get_row($wpdb->prepare("SELECT * FROM $state_table WHERE
961
+		if ( ! $country) {
962
+			//insert a new one then
963
+			$cols_n_values = array(
964
+					'CNT_ISO'         => $this->_find_available_country_iso(2),
965
+					'CNT_ISO3'        => $this->_find_available_country_iso(3),
966
+					'RGN_ID'          => 0,
967
+					'CNT_name'        => $country_name,
968
+					'CNT_cur_code'    => 'USD',
969
+					'CNT_cur_single'  => 'Dollar',
970
+					'CNT_cur_plural'  => 'Dollars',
971
+					'CNT_cur_sign'    => '&#36;',
972
+					'CNT_cur_sign_b4' => true,
973
+					'CNT_cur_dec_plc' => 2,
974
+					'CNT_cur_dec_mrk' => '.',
975
+					'CNT_cur_thsnds'  => ',',
976
+					'CNT_tel_code'    => '+1',
977
+					'CNT_is_EU'       => false,
978
+					'CNT_active'      => true,
979
+			);
980
+			$data_types = array(
981
+					'%s',//CNT_ISO
982
+					'%s',//CNT_ISO3
983
+					'%d',//RGN_ID
984
+					'%s',//CNT_name
985
+					'%s',//CNT_cur_code
986
+					'%s',//CNT_cur_single
987
+					'%s',//CNT_cur_plural
988
+					'%s',//CNT_cur_sign
989
+					'%d',//CNT_cur_sign_b4
990
+					'%d',//CNT_cur_dec_plc
991
+					'%s',//CNT_cur_dec_mrk
992
+					'%s',//CNT_cur_thsnds
993
+					'%s',//CNT_tel_code
994
+					'%d',//CNT_is_EU
995
+					'%d',//CNT_active
996
+			);
997
+			$success = $wpdb->insert($country_table,
998
+					$cols_n_values,
999
+					$data_types);
1000
+			if ( ! $success) {
1001
+				throw new EE_Error($this->_create_error_message_for_db_insertion('N/A',
1002
+						array('country_id' => $country_name), $country_table, $cols_n_values, $data_types));
1003
+			}
1004
+			$country = $cols_n_values;
1005
+		}
1006
+		return $country;
1007
+	}
1008
+
1009
+
1010
+
1011
+	/**
1012
+	 * finds a country iso which hasnt been used yet
1013
+	 *
1014
+	 * @global type $wpdb
1015
+	 * @return string
1016
+	 */
1017
+	private function _find_available_country_iso($num_letters = 2)
1018
+	{
1019
+		global $wpdb;
1020
+		$country_table = $wpdb->prefix . "esp_country";
1021
+		$attempts = 0;
1022
+		do {
1023
+			$current_iso = strtoupper(wp_generate_password($num_letters, false));
1024
+			$country_with_that_iso = $wpdb->get_var($wpdb->prepare("SELECT count(CNT_ISO) FROM "
1025
+																   . $country_table
1026
+																   . " WHERE CNT_ISO=%s", $current_iso));
1027
+			$attempts++;
1028
+			//keep going until we find an available country code, or we arbitrarily
1029
+			//decide we've tried this enough. Somehow they have way too many countries
1030
+			//(probably because they're mis-using the EE3 country_id like a custom question)
1031
+		} while (intval($country_with_that_iso) && $attempts < 200);
1032
+		return $current_iso;
1033
+	}
1034
+
1035
+
1036
+
1037
+	/**
1038
+	 * Gets a state entry as an array, or creates one if none is found. Much like EEM_State::instance()->get_one(), but
1039
+	 * is independent of outside code which can change in future versions of EE
1040
+	 *
1041
+	 * @global type  $wpdb
1042
+	 * @param string $state_name
1043
+	 * @return array where keys are columns, values are column values
1044
+	 */
1045
+	public function get_or_create_state($state_name, $country_name = '')
1046
+	{
1047
+		if ( ! $state_name) {
1048
+			throw new EE_Error(esc_html__("Could not get-or-create state because no state name was provided",
1049
+					"event_espresso"));
1050
+		}
1051
+		try {
1052
+			$country = $this->get_or_create_country($country_name);
1053
+			$country_iso = $country['CNT_ISO'];
1054
+		} catch (EE_Error $e) {
1055
+			$country_iso = $this->get_default_country_iso();
1056
+		}
1057
+		global $wpdb;
1058
+		$state_table = $wpdb->prefix . "esp_state";
1059
+		$state = $wpdb->get_row($wpdb->prepare("SELECT * FROM $state_table WHERE
1060 1060
 			(STA_abbrev LIKE %s OR
1061 1061
 			STA_name LIKE %s) AND
1062 1062
 			CNT_ISO LIKE %s LIMIT 1", $state_name, $state_name, $country_iso), ARRAY_A);
1063
-        if ( ! $state) {
1064
-            //insert a new one then
1065
-            $cols_n_values = array(
1066
-                    'CNT_ISO'    => $country_iso,
1067
-                    'STA_abbrev' => substr($state_name, 0, 6),
1068
-                    'STA_name'   => $state_name,
1069
-                    'STA_active' => true,
1070
-            );
1071
-            $data_types = array(
1072
-                    '%s',//CNT_ISO
1073
-                    '%s',//STA_abbrev
1074
-                    '%s',//STA_name
1075
-                    '%d',//STA_active
1076
-            );
1077
-            $success = $wpdb->insert($state_table, $cols_n_values, $data_types);
1078
-            if ( ! $success) {
1079
-                throw new EE_Error($this->_create_error_message_for_db_insertion('N/A',
1080
-                        array('state' => $state_name, 'country_id' => $country_name), $state_table, $cols_n_values,
1081
-                        $data_types));
1082
-            }
1083
-            $state = $cols_n_values;
1084
-            $state['STA_ID'] = $wpdb->insert_id;
1085
-        }
1086
-        return $state;
1087
-    }
1088
-
1089
-
1090
-
1091
-    /**
1092
-     * Fixes times like "5:00 PM" into the expected 24-hour format "17:00".
1093
-     * THis is actually just copied from the 3.1 JSON API because it needed to do the exact same thing
1094
-     *
1095
-     * @param type $timeString
1096
-     * @return string in the php DATETIME format: "G:i" (24-hour format hour with leading zeros, a colon, and minutes
1097
-     *                with leading zeros)
1098
-     */
1099
-    public function convertTimeFromAMPM($timeString)
1100
-    {
1101
-        $matches = array();
1102
-        preg_match("~(\\d*):(\\d*)~", $timeString, $matches);
1103
-        if ( ! $matches || count($matches) < 3) {
1104
-            $hour = '00';
1105
-            $minutes = '00';
1106
-        } else {
1107
-            $hour = intval($matches[1]);
1108
-            $minutes = $matches[2];
1109
-        }
1110
-        if (strpos($timeString, 'PM') || strpos($timeString, 'pm')) {
1111
-            $hour = intval($hour) + 12;
1112
-        }
1113
-        $hour = str_pad("$hour", 2, '0', STR_PAD_LEFT);
1114
-        $minutes = str_pad("$minutes", 2, '0', STR_PAD_LEFT);
1115
-        return "$hour:$minutes";
1116
-    }
1117
-
1118
-
1119
-
1120
-    /**
1121
-     * Gets the ISO3 fora country given its 3.1 country ID.
1122
-     *
1123
-     * @param int $country_id
1124
-     * @return string the country's ISO3 code
1125
-     */
1126
-    public function get_iso_from_3_1_country_id($country_id)
1127
-    {
1128
-        $old_countries = array(
1129
-                array(64, 'United States', 'US', 'USA', 1),
1130
-                array(15, 'Australia', 'AU', 'AUS', 1),
1131
-                array(39, 'Canada', 'CA', 'CAN', 1),
1132
-                array(171, 'United Kingdom', 'GB', 'GBR', 1),
1133
-                array(70, 'France', 'FR', 'FRA', 2),
1134
-                array(111, 'Italy', 'IT', 'ITA', 2),
1135
-                array(63, 'Spain', 'ES', 'ESP', 2),
1136
-                array(1, 'Afghanistan', 'AF', 'AFG', 1),
1137
-                array(2, 'Albania', 'AL', 'ALB', 1),
1138
-                array(3, 'Germany', 'DE', 'DEU', 2),
1139
-                array(198, 'Switzerland', 'CH', 'CHE', 1),
1140
-                array(87, 'Netherlands', 'NL', 'NLD', 2),
1141
-                array(197, 'Sweden', 'SE', 'SWE', 1),
1142
-                array(230, 'Akrotiri and Dhekelia', 'CY', 'CYP', 2),
1143
-                array(4, 'Andorra', 'AD', 'AND', 2),
1144
-                array(5, 'Angola', 'AO', 'AGO', 1),
1145
-                array(6, 'Anguilla', 'AI', 'AIA', 1),
1146
-                array(7, 'Antarctica', 'AQ', 'ATA', 1),
1147
-                array(8, 'Antigua and Barbuda', 'AG', 'ATG', 1),
1148
-                array(10, 'Saudi Arabia', 'SA', 'SAU', 1),
1149
-                array(11, 'Algeria', 'DZ', 'DZA', 1),
1150
-                array(12, 'Argentina', 'AR', 'ARG', 1),
1151
-                array(13, 'Armenia', 'AM', 'ARM', 1),
1152
-                array(14, 'Aruba', 'AW', 'ABW', 1),
1153
-                array(16, 'Austria', 'AT', 'AUT', 2),
1154
-                array(17, 'Azerbaijan', 'AZ', 'AZE', 1),
1155
-                array(18, 'Bahamas', 'BS', 'BHS', 1),
1156
-                array(19, 'Bahrain', 'BH', 'BHR', 1),
1157
-                array(20, 'Bangladesh', 'BD', 'BGD', 1),
1158
-                array(21, 'Barbados', 'BB', 'BRB', 1),
1159
-                array(22, 'Belgium ', 'BE', 'BEL', 2),
1160
-                array(23, 'Belize', 'BZ', 'BLZ', 1),
1161
-                array(24, 'Benin', 'BJ', 'BEN', 1),
1162
-                array(25, 'Bermudas', 'BM', 'BMU', 1),
1163
-                array(26, 'Belarus', 'BY', 'BLR', 1),
1164
-                array(27, 'Bolivia', 'BO', 'BOL', 1),
1165
-                array(28, 'Bosnia and Herzegovina', 'BA', 'BIH', 1),
1166
-                array(29, 'Botswana', 'BW', 'BWA', 1),
1167
-                array(96, 'Bouvet Island', 'BV', 'BVT', 1),
1168
-                array(30, 'Brazil', 'BR', 'BRA', 1),
1169
-                array(31, 'Brunei', 'BN', 'BRN', 1),
1170
-                array(32, 'Bulgaria', 'BG', 'BGR', 1),
1171
-                array(33, 'Burkina Faso', 'BF', 'BFA', 1),
1172
-                array(34, 'Burundi', 'BI', 'BDI', 1),
1173
-                array(35, 'Bhutan', 'BT', 'BTN', 1),
1174
-                array(36, 'Cape Verde', 'CV', 'CPV', 1),
1175
-                array(37, 'Cambodia', 'KH', 'KHM', 1),
1176
-                array(38, 'Cameroon', 'CM', 'CMR', 1),
1177
-                array(98, 'Cayman Islands', 'KY', 'CYM', 1),
1178
-                array(172, 'Central African Republic', 'CF', 'CAF', 1),
1179
-                array(40, 'Chad', 'TD', 'TCD', 1),
1180
-                array(41, 'Chile', 'CL', 'CHL', 1),
1181
-                array(42, 'China', 'CN', 'CHN', 1),
1182
-                array(105, 'Christmas Island', 'CX', 'CXR', 1),
1183
-                array(43, 'Cyprus', 'CY', 'CYP', 2),
1184
-                array(99, 'Cocos Island', 'CC', 'CCK', 1),
1185
-                array(100, 'Cook Islands', 'CK', 'COK', 1),
1186
-                array(44, 'Colombia', 'CO', 'COL', 1),
1187
-                array(45, 'Comoros', 'KM', 'COM', 1),
1188
-                array(46, 'Congo', 'CG', 'COG', 1),
1189
-                array(47, 'North Korea', 'KP', 'PRK', 1),
1190
-                array(50, 'Costa Rica', 'CR', 'CRI', 1),
1191
-                array(51, 'Croatia', 'HR', 'HRV', 1),
1192
-                array(52, 'Cuba', 'CU', 'CUB', 1),
1193
-                array(173, 'Czech Republic', 'CZ', 'CZE', 1),
1194
-                array(53, 'Denmark', 'DK', 'DNK', 1),
1195
-                array(54, 'Djibouti', 'DJ', 'DJI', 1),
1196
-                array(55, 'Dominica', 'DM', 'DMA', 1),
1197
-                array(174, 'Dominican Republic', 'DO', 'DOM', 1),
1198
-                array(56, 'Ecuador', 'EC', 'ECU', 1),
1199
-                array(57, 'Egypt', 'EG', 'EGY', 1),
1200
-                array(58, 'El Salvador', 'SV', 'SLV', 1),
1201
-                array(60, 'Eritrea', 'ER', 'ERI', 1),
1202
-                array(61, 'Slovakia', 'SK', 'SVK', 2),
1203
-                array(62, 'Slovenia', 'SI', 'SVN', 2),
1204
-                array(65, 'Estonia', 'EE', 'EST', 2),
1205
-                array(66, 'Ethiopia', 'ET', 'ETH', 1),
1206
-                array(102, 'Faroe islands', 'FO', 'FRO', 1),
1207
-                array(103, 'Falkland Islands', 'FK', 'FLK', 1),
1208
-                array(67, 'Fiji', 'FJ', 'FJI', 1),
1209
-                array(69, 'Finland', 'FI', 'FIN', 2),
1210
-                array(71, 'Gabon', 'GA', 'GAB', 1),
1211
-                array(72, 'Gambia', 'GM', 'GMB', 1),
1212
-                array(73, 'Georgia', 'GE', 'GEO', 1),
1213
-                array(74, 'Ghana', 'GH', 'GHA', 1),
1214
-                array(75, 'Gibraltar', 'GI', 'GIB', 1),
1215
-                array(76, 'Greece', 'GR', 'GRC', 2),
1216
-                array(77, 'Grenada', 'GD', 'GRD', 1),
1217
-                array(78, 'Greenland', 'GL', 'GRL', 1),
1218
-                array(79, 'Guadeloupe', 'GP', 'GLP', 1),
1219
-                array(80, 'Guam', 'GU', 'GUM', 1),
1220
-                array(81, 'Guatemala', 'GT', 'GTM', 1),
1221
-                array(82, 'Guinea', 'GN', 'GIN', 1),
1222
-                array(83, 'Equatorial Guinea', 'GQ', 'GNQ', 1),
1223
-                array(84, 'Guinea-Bissau', 'GW', 'GNB', 1),
1224
-                array(85, 'Guyana', 'GY', 'GUY', 1),
1225
-                array(86, 'Haiti', 'HT', 'HTI', 1),
1226
-                array(88, 'Honduras', 'HN', 'HND', 1),
1227
-                array(89, 'Hong Kong', 'HK', 'HKG', 1),
1228
-                array(90, 'Hungary', 'HU', 'HUN', 1),
1229
-                array(91, 'India', 'IN', 'IND', 1),
1230
-                array(205, 'British Indian Ocean Territory', 'IO', 'IOT', 1),
1231
-                array(92, 'Indonesia', 'ID', 'IDN', 1),
1232
-                array(93, 'Iraq', 'IQ', 'IRQ', 1),
1233
-                array(94, 'Iran', 'IR', 'IRN', 1),
1234
-                array(95, 'Ireland', 'IE', 'IRL', 2),
1235
-                array(97, 'Iceland', 'IS', 'ISL', 1),
1236
-                array(110, 'Israel', 'IL', 'ISR', 1),
1237
-                array(49, 'Ivory Coast ', 'CI', 'CIV', 1),
1238
-                array(112, 'Jamaica', 'JM', 'JAM', 1),
1239
-                array(113, 'Japan', 'JP', 'JPN', 1),
1240
-                array(114, 'Jordan', 'JO', 'JOR', 1),
1241
-                array(115, 'Kazakhstan', 'KZ', 'KAZ', 1),
1242
-                array(116, 'Kenya', 'KE', 'KEN', 1),
1243
-                array(117, 'Kyrgyzstan', 'KG', 'KGZ', 1),
1244
-                array(118, 'Kiribati', 'KI', 'KIR', 1),
1245
-                array(48, 'South Korea', 'KR', 'KOR', 1),
1246
-                array(228, 'Kosovo', 'XK', 'XKV', 2),
1247
-                // there is no official ISO code for Kosovo yet (http://geonames.wordpress.com/2010/03/08/xk-country-code-for-kosovo/) so using a temporary country code and a modified 3 character code for ISO code -- this should be updated if/when Kosovo gets its own ISO code
1248
-                array(119, 'Kuwait', 'KW', 'KWT', 1),
1249
-                array(120, 'Laos', 'LA', 'LAO', 1),
1250
-                array(121, 'Latvia', 'LV', 'LVA', 2),
1251
-                array(122, 'Lesotho', 'LS', 'LSO', 1),
1252
-                array(123, 'Lebanon', 'LB', 'LBN', 1),
1253
-                array(124, 'Liberia', 'LR', 'LBR', 1),
1254
-                array(125, 'Libya', 'LY', 'LBY', 1),
1255
-                array(126, 'Liechtenstein', 'LI', 'LIE', 1),
1256
-                array(127, 'Lithuania', 'LT', 'LTU', 2),
1257
-                array(128, 'Luxemburg', 'LU', 'LUX', 2),
1258
-                array(129, 'Macao', 'MO', 'MAC', 1),
1259
-                array(130, 'Macedonia', 'MK', 'MKD', 1),
1260
-                array(131, 'Madagascar', 'MG', 'MDG', 1),
1261
-                array(132, 'Malaysia', 'MY', 'MYS', 1),
1262
-                array(133, 'Malawi', 'MW', 'MWI', 1),
1263
-                array(134, 'Maldivas', 'MV', 'MDV', 1),
1264
-                array(135, 'Mali', 'ML', 'MLI', 1),
1265
-                array(136, 'Malta', 'MT', 'MLT', 2),
1266
-                array(101, 'Northern Marianas', 'MP', 'MNP', 1),
1267
-                array(137, 'Morocco', 'MA', 'MAR', 1),
1268
-                array(104, 'Marshall islands', 'MH', 'MHL', 1),
1269
-                array(138, 'Martinique', 'MQ', 'MTQ', 1),
1270
-                array(139, 'Mauritius', 'MU', 'MUS', 1),
1271
-                array(140, 'Mauritania', 'MR', 'MRT', 1),
1272
-                array(141, 'Mayote', 'YT', 'MYT', 2),
1273
-                array(142, 'Mexico', 'MX', 'MEX', 1),
1274
-                array(143, 'Micronesia', 'FM', 'FSM', 1),
1275
-                array(144, 'Moldova', 'MD', 'MDA', 1),
1276
-                array(145, 'Monaco', 'MC', 'MCO', 2),
1277
-                array(146, 'Mongolia', 'MN', 'MNG', 1),
1278
-                array(147, 'Montserrat', 'MS', 'MSR', 1),
1279
-                array(227, 'Montenegro', 'ME', 'MNE', 2),
1280
-                array(148, 'Mozambique', 'MZ', 'MOZ', 1),
1281
-                array(149, 'Myanmar', 'MM', 'MMR', 1),
1282
-                array(150, 'Namibia', 'NA', 'NAM', 1),
1283
-                array(151, 'Nauru', 'NR', 'NRU', 1),
1284
-                array(152, 'Nepal', 'NP', 'NPL', 1),
1285
-                array(9, 'Netherlands Antilles', 'AN', 'ANT', 1),
1286
-                array(153, 'Nicaragua', 'NI', 'NIC', 1),
1287
-                array(154, 'Niger', 'NE', 'NER', 1),
1288
-                array(155, 'Nigeria', 'NG', 'NGA', 1),
1289
-                array(156, 'Niue', 'NU', 'NIU', 1),
1290
-                array(157, 'Norway', 'NO', 'NOR', 1),
1291
-                array(158, 'New Caledonia', 'NC', 'NCL', 1),
1292
-                array(159, 'New Zealand', 'NZ', 'NZL', 1),
1293
-                array(160, 'Oman', 'OM', 'OMN', 1),
1294
-                array(161, 'Pakistan', 'PK', 'PAK', 1),
1295
-                array(162, 'Palau', 'PW', 'PLW', 1),
1296
-                array(163, 'Panama', 'PA', 'PAN', 1),
1297
-                array(164, 'Papua New Guinea', 'PG', 'PNG', 1),
1298
-                array(165, 'Paraguay', 'PY', 'PRY', 1),
1299
-                array(166, 'Peru', 'PE', 'PER', 1),
1300
-                array(68, 'Philippines', 'PH', 'PHL', 1),
1301
-                array(167, 'Poland', 'PL', 'POL', 1),
1302
-                array(168, 'Portugal', 'PT', 'PRT', 2),
1303
-                array(169, 'Puerto Rico', 'PR', 'PRI', 1),
1304
-                array(170, 'Qatar', 'QA', 'QAT', 1),
1305
-                array(176, 'Rwanda', 'RW', 'RWA', 1),
1306
-                array(177, 'Romania', 'RO', 'ROM', 2),
1307
-                array(178, 'Russia', 'RU', 'RUS', 1),
1308
-                array(229, 'Saint Pierre and Miquelon', 'PM', 'SPM', 2),
1309
-                array(180, 'Samoa', 'WS', 'WSM', 1),
1310
-                array(181, 'American Samoa', 'AS', 'ASM', 1),
1311
-                array(183, 'San Marino', 'SM', 'SMR', 2),
1312
-                array(184, 'Saint Vincent and the Grenadines', 'VC', 'VCT', 1),
1313
-                array(185, 'Saint Helena', 'SH', 'SHN', 1),
1314
-                array(186, 'Saint Lucia', 'LC', 'LCA', 1),
1315
-                array(188, 'Senegal', 'SN', 'SEN', 1),
1316
-                array(189, 'Seychelles', 'SC', 'SYC', 1),
1317
-                array(190, 'Sierra Leona', 'SL', 'SLE', 1),
1318
-                array(191, 'Singapore', 'SG', 'SGP', 1),
1319
-                array(192, 'Syria', 'SY', 'SYR', 1),
1320
-                array(193, 'Somalia', 'SO', 'SOM', 1),
1321
-                array(194, 'Sri Lanka', 'LK', 'LKA', 1),
1322
-                array(195, 'South Africa', 'ZA', 'ZAF', 1),
1323
-                array(196, 'Sudan', 'SD', 'SDN', 1),
1324
-                array(199, 'Suriname', 'SR', 'SUR', 1),
1325
-                array(200, 'Swaziland', 'SZ', 'SWZ', 1),
1326
-                array(201, 'Thailand', 'TH', 'THA', 1),
1327
-                array(202, 'Taiwan', 'TW', 'TWN', 1),
1328
-                array(203, 'Tanzania', 'TZ', 'TZA', 1),
1329
-                array(204, 'Tajikistan', 'TJ', 'TJK', 1),
1330
-                array(206, 'Timor-Leste', 'TL', 'TLS', 1),
1331
-                array(207, 'Togo', 'TG', 'TGO', 1),
1332
-                array(208, 'Tokelau', 'TK', 'TKL', 1),
1333
-                array(209, 'Tonga', 'TO', 'TON', 1),
1334
-                array(210, 'Trinidad and Tobago', 'TT', 'TTO', 1),
1335
-                array(211, 'Tunisia', 'TN', 'TUN', 1),
1336
-                array(212, 'Turkmenistan', 'TM', 'TKM', 1),
1337
-                array(213, 'Turkey', 'TR', 'TUR', 1),
1338
-                array(214, 'Tuvalu', 'TV', 'TUV', 1),
1339
-                array(215, 'Ukraine', 'UA', 'UKR', 1),
1340
-                array(216, 'Uganda', 'UG', 'UGA', 1),
1341
-                array(59, 'United Arab Emirates', 'AE', 'ARE', 1),
1342
-                array(217, 'Uruguay', 'UY', 'URY', 1),
1343
-                array(218, 'Uzbekistan', 'UZ', 'UZB', 1),
1344
-                array(219, 'Vanuatu', 'VU', 'VUT', 1),
1345
-                array(220, 'Vatican City', 'VA', 'VAT', 2),
1346
-                array(221, 'Venezuela', 'VE', 'VEN', 1),
1347
-                array(222, 'Vietnam', 'VN', 'VNM', 1),
1348
-                array(108, 'Virgin Islands', 'VI', 'VIR', 1),
1349
-                array(223, 'Yemen', 'YE', 'YEM', 1),
1350
-                array(225, 'Zambia', 'ZM', 'ZMB', 1),
1351
-                array(226, 'Zimbabwe', 'ZW', 'ZWE', 1),
1352
-        );
1353
-        $country_iso = 'US';
1354
-        foreach ($old_countries as $country_array) {
1355
-            //note: index 0 is the 3.1 country ID
1356
-            if ($country_array[0] == $country_id) {
1357
-                //note: index 2 is the ISO
1358
-                $country_iso = $country_array[2];
1359
-                break;
1360
-            }
1361
-        }
1362
-        return $country_iso;
1363
-    }
1364
-
1365
-
1366
-
1367
-    /**
1368
-     * Gets the ISO3 for the
1369
-     *
1370
-     * @return string
1371
-     */
1372
-    public function get_default_country_iso()
1373
-    {
1374
-        $old_org_options = get_option('events_organization_settings');
1375
-        $iso = $this->get_iso_from_3_1_country_id($old_org_options['organization_country']);
1376
-        return $iso;
1377
-    }
1378
-
1379
-
1380
-
1381
-    /**
1382
-     * Converst a 3.1 payment status to its equivalent 4.1 regisration status
1383
-     *
1384
-     * @param string  $payment_status                   possible value for 3.1's evens_attendee.payment_status
1385
-     * @param boolean $this_thing_required_pre_approval whether the thing we're considering (the general setting's
1386
-     *                                                  DEFAULT payment status, the event's DEFAULT payment status, or
1387
-     *                                                  the attendee's payment status) required pre-approval.
1388
-     * @return string STS_ID for use in 4.1
1389
-     */
1390
-    public function convert_3_1_payment_status_to_4_1_STS_ID($payment_status, $this_thing_required_pre_approval = false)
1391
-    {
1392
-        //EE team can read the related discussion: https://app.asana.com/0/2400967562914/9418495544455
1393
-        if ($this_thing_required_pre_approval) {
1394
-            return 'RNA';
1395
-        } else {
1396
-            $mapping = $default_reg_stati_conversions = array(
1397
-                    'Completed'        => 'RAP',
1398
-                    ''                 => 'RPP',
1399
-                    'Incomplete'       => 'RPP',
1400
-                    'Pending'          => 'RAP',
1401
-                    //stati that only occurred on 3.1 attendees:
1402
-                    'Payment Declined' => 'RPP',
1403
-                    'Not Completed'    => 'RPP',
1404
-                    'Cancelled'        => 'RPP',
1405
-                    'Declined'         => 'RPP',
1406
-            );
1407
-        }
1408
-        return isset($mapping[$payment_status]) ? $mapping[$payment_status] : 'RNA';
1409
-    }
1410
-
1411
-
1412
-
1413
-    /**
1414
-     * Makes sure the 3.1's image url is converted to an image attachment post to the 4.1 CPT event
1415
-     * and sets it as the featured image on the CPT event
1416
-     *
1417
-     * @param type                            $old_event
1418
-     * @param type                            $new_cpt_id
1419
-     * @param  EE_Data_Migration_Script_Stage $migration_stage the stage which called this, where errors should be added
1420
-     * @return boolean whether or not we had to do the big job of creating an image attachment
1421
-     */
1422
-    public function convert_image_url_to_attachment_and_attach_to_post(
1423
-            $guid,
1424
-            $new_cpt_id,
1425
-            EE_Data_Migration_Script_Stage $migration_stage
1426
-    ) {
1427
-        $created_attachment_post = false;
1428
-        $guid = $this->_get_original_guid($guid);
1429
-        if ($guid) {
1430
-            //check for an existing attachment post with this guid
1431
-            $attachment_post_id = $this->_get_image_attachment_id_by_GUID($guid);
1432
-            if ( ! $attachment_post_id) {
1433
-                //post thumbnail with that GUID doesn't exist, we should create one
1434
-                $attachment_post_id = $this->_create_image_attachment_from_GUID($guid, $migration_stage);
1435
-                $created_attachment_post = true;
1436
-            }
1437
-            //double-check we actually have an attachment post
1438
-            if ($attachment_post_id) {
1439
-                update_post_meta($new_cpt_id, '_thumbnail_id', $attachment_post_id);
1440
-            } else {
1441
-                $migration_stage->add_error(sprintf(esc_html__("Could not update event image %s for CPT with ID %d, but attachments post ID is %d",
1442
-                        "event_espresso"), $guid, $new_cpt_id, $attachment_post_id));
1443
-            }
1444
-        }
1445
-        return $created_attachment_post;
1446
-    }
1447
-
1448
-
1449
-
1450
-    /**
1451
-     * In 3.1, the event thumbnail image DOESN'T point to the orignal image, but instead
1452
-     * to a large thumbnail (which has nearly the same GUID, except it adds "-{width}x{height}" before the filetype,
1453
-     * or whatever dimensions it is. Eg 'http://mysite.com/image1-300x400.jpg' instead of
1454
-     * 'http://mysite.com/image1.jpg' ). This function attempts to strip that off and get the original file, if it
1455
-     * exists
1456
-     *
1457
-     * @param string $guid_in_old_event
1458
-     * @return string either the original guid, or $guid_in_old_event if we couldn't figure out what the original was
1459
-     */
1460
-    private function _get_original_guid($guid_in_old_event)
1461
-    {
1462
-        $original_guid = preg_replace('~-\d*x\d*\.~', '.', $guid_in_old_event, 1);
1463
-        //do a head request to verify the file exists
1464
-        $head_response = wp_remote_head($original_guid);
1465
-        if ( ! $head_response instanceof WP_Error && $head_response['response']['message'] == 'OK') {
1466
-            return $original_guid;
1467
-        } else {
1468
-            return $guid_in_old_event;
1469
-        }
1470
-    }
1471
-
1472
-
1473
-
1474
-    /**
1475
-     * Creates an image attachment post for the GUID. If the GUID points to a remote image,
1476
-     * we download it to our uploads directory so that it can be properly processed (eg, creates different sizes of
1477
-     * thumbnails)
1478
-     *
1479
-     * @param type                           $guid
1480
-     * @param EE_Data_Migration_Script_Stage $migration_stage
1481
-     * @return int
1482
-     */
1483
-    private function _create_image_attachment_from_GUID($guid, EE_Data_Migration_Script_Stage $migration_stage)
1484
-    {
1485
-        if ( ! $guid) {
1486
-            $migration_stage->add_error(sprintf(esc_html__("Cannot create image attachment for a blank GUID!",
1487
-                    "event_espresso")));
1488
-            return 0;
1489
-        }
1490
-        $wp_filetype = wp_check_filetype(basename($guid), null);
1491
-        $wp_upload_dir = wp_upload_dir();
1492
-        //if the file is located remotely, download it to our uploads DIR, because wp_genereate_attachmnet_metadata needs the file to be local
1493
-        if (strpos($guid, $wp_upload_dir['url']) === false) {
1494
-            //image is located remotely. download it and place it in the uploads directory
1495
-            if ( ! is_readable($guid)) {
1496
-                $migration_stage->add_error(sprintf(esc_html__("Could not create image attachment from non-existent file: %s",
1497
-                        "event_espresso"), $guid));
1498
-                return 0;
1499
-            }
1500
-            $contents = file_get_contents($guid);
1501
-            if ($contents === false) {
1502
-                $migration_stage->add_error(sprintf(esc_html__("Could not read image at %s, and therefore couldnt create an attachment post for it.",
1503
-                        "event_espresso"), $guid));
1504
-                return false;
1505
-            }
1506
-            $local_filepath = $wp_upload_dir['path'] . DS . basename($guid);
1507
-            $savefile = fopen($local_filepath, 'w');
1508
-            fwrite($savefile, $contents);
1509
-            fclose($savefile);
1510
-            $guid = str_replace($wp_upload_dir['path'], $wp_upload_dir['url'], $local_filepath);
1511
-        } else {
1512
-            $local_filepath = str_replace($wp_upload_dir['url'], $wp_upload_dir['path'], $guid);
1513
-        }
1514
-        $attachment = array(
1515
-                'guid'           => $guid,
1516
-                'post_mime_type' => $wp_filetype['type'],
1517
-                'post_title'     => preg_replace('/\.[^.]+$/', '', basename($guid)),
1518
-                'post_content'   => '',
1519
-                'post_status'    => 'inherit',
1520
-        );
1521
-        $attach_id = wp_insert_attachment($attachment, $guid);
1522
-        if ( ! $attach_id) {
1523
-            $migration_stage->add_error(sprintf(esc_html__("Could not create image attachment post from image '%s'. Attachment data was %s.",
1524
-                    "event_espresso"), $guid, $this->_json_encode($attachment)));
1525
-            return $attach_id;
1526
-        }
1527
-        // you must first include the image.php file
1528
-        // for the function wp_generate_attachment_metadata() to work
1529
-        require_once(ABSPATH . 'wp-admin/includes/image.php');
1530
-        $attach_data = wp_generate_attachment_metadata($attach_id, $local_filepath);
1531
-        if ( ! $attach_data) {
1532
-            $migration_stage->add_error(sprintf(esc_html__("Coudl not genereate attachment metadata for attachment post %d with filepath %s and GUID %s. Please check the file was downloaded properly.",
1533
-                    "event_espresso"), $attach_id, $local_filepath, $guid));
1534
-            return $attach_id;
1535
-        }
1536
-        $metadata_save_result = wp_update_attachment_metadata($attach_id, $attach_data);
1537
-        if ( ! $metadata_save_result) {
1538
-            $migration_stage->add_error(sprintf(esc_html__("Could not update attachment metadata for attachment %d with data %s",
1539
-                    "event_espresso"), $attach_id, $this->_json_encode($attach_data)));
1540
-        }
1541
-        return $attach_id;
1542
-    }
1543
-
1544
-
1545
-
1546
-    /**
1547
-     * Finds the attachment post containing info about an image attachment given the GUID (link to the image itself),
1548
-     * and returns its ID.
1549
-     *
1550
-     * @global type  $wpdb
1551
-     * @param string $guid
1552
-     * @return int
1553
-     */
1554
-    private function _get_image_attachment_id_by_GUID($guid)
1555
-    {
1556
-        global $wpdb;
1557
-        $attachment_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid=%s LIMIT 1", $guid));
1558
-        return $attachment_id;
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     * Returns a mysql-formatted DATETIME in UTC time, given a $DATETIME_string
1565
-     * (and optionally a timezone; if none is given, the wp DEFAULT is used)
1566
-     *
1567
-     * @param EE_Data_Migration_Script_base $stage
1568
-     * @param array                         $row_of_data , the row from the DB (as an array) we're trying to find the
1569
-     *                                                   UTC time for
1570
-     * @param string                        $DATETIME_string
1571
-     * @param string                        $timezone
1572
-     * @return string
1573
-     */
1574
-    public function convert_date_string_to_utc(
1575
-            EE_Data_Migration_Script_Stage $stage,
1576
-            $row_of_data,
1577
-            $DATETIME_string,
1578
-            $timezone = null
1579
-    ) {
1580
-        $original_tz = $timezone;
1581
-        if ( ! $timezone) {
1582
-            $timezone = $this->_get_wp_timezone();
1583
-        }
1584
-        if ( ! $timezone) {
1585
-            $stage->add_error(sprintf(esc_html__("Could not find timezone given %s for %s", "event_espresso"), $original_tz,
1586
-                    $row_of_data));
1587
-            $timezone = 'UTC';
1588
-        }
1589
-        try {
1590
-            $date_obj = new DateTime($DATETIME_string, new DateTimeZone($timezone));
1591
-            $date_obj->setTimezone(new DateTimeZone('UTC'));
1592
-            // workaround for php datetime bug (@see https://events.codebasehq.com/projects/event-espresso/tickets/11407
1593
-            $date_obj->getTimestamp();
1594
-        } catch (Exception $e) {
1595
-            $stage->add_error(sprintf(esc_html__("Could not convert time string '%s' using timezone '%s' into a proper DATETIME. Using current time instead.",
1596
-                    "event_espresso"), $DATETIME_string, $timezone));
1597
-            $date_obj = new DateTime();
1598
-        }
1599
-        return $date_obj->format('Y-m-d H:i:s');
1600
-    }
1601
-
1602
-
1603
-
1604
-    /**
1605
-     * Gets the DEFAULT timezone string from wordpress (even if they set a gmt offset)
1606
-     *
1607
-     * @return string
1608
-     */
1609
-    private function _get_wp_timezone()
1610
-    {
1611
-        $timezone = empty($timezone) ? get_option('timezone_string') : $timezone;
1612
-        //if timezone is STILL empty then let's get the GMT offset and then set the timezone_string using our converter
1613
-        if (empty($timezone)) {
1614
-            //let's get a the WordPress UTC offset
1615
-            $offset = get_option('gmt_offset');
1616
-            $timezone = $this->timezone_convert_to_string_from_offset($offset);
1617
-        }
1618
-        return $timezone;
1619
-    }
1620
-
1621
-
1622
-
1623
-    /**
1624
-     * Gets the wordpress timezone string from a UTC offset
1625
-     *
1626
-     * @param int $offset
1627
-     * @return boolean
1628
-     */
1629
-    private function timezone_convert_to_string_from_offset($offset)
1630
-    {
1631
-        //shamelessly taken from bottom comment at http://ca1.php.net/manual/en/function.timezone-name-from-abbr.php because timezone_name_from_abbr() did NOT work as expected - its not reliable
1632
-        $offset *= 3600; // convert hour offset to seconds
1633
-        $abbrarray = timezone_abbreviations_list();
1634
-        foreach ($abbrarray as $abbr) {
1635
-            foreach ($abbr as $city) {
1636
-                if ($city['offset'] == $offset) {
1637
-                    return $city['timezone_id'];
1638
-                }
1639
-            }
1640
-        }
1641
-        return false;
1642
-    }
1643
-
1644
-
1645
-
1646
-    public function migration_page_hooks()
1647
-    {
1648
-        add_filter(
1649
-                'FHEE__ee_migration_page__header',
1650
-                array($this, '_migrate_page_hook_simplify_version_strings'),
1651
-                10,
1652
-                3
1653
-        );
1654
-        add_filter(
1655
-                'FHEE__ee_migration_page__p_after_header',
1656
-                array($this, '_migration_page_hook_simplify_next_db_state'),
1657
-                10,
1658
-                2
1659
-        );
1660
-        add_filter(
1661
-                'FHEE__ee_migration_page__option_1_main',
1662
-                array($this, '_migrate_page_hook_simplify_version_strings'),
1663
-                10,
1664
-                3
1665
-        );
1666
-        add_filter(
1667
-                'FHEE__ee_migration_page__option_1_button_text',
1668
-                array($this, '_migrate_page_hook_simplify_version_strings'),
1669
-                10,
1670
-                3
1671
-        );
1672
-        add_action(
1673
-                'AHEE__ee_migration_page__option_1_extra_details',
1674
-                array($this, '_migration_page_hook_option_1_extra_details'),
1675
-                10,
1676
-                3
1677
-        );
1678
-        add_filter(
1679
-                'FHEE__ee_migration_page__option_2_main',
1680
-                array($this, '_migrate_page_hook_simplify_version_strings'),
1681
-                10,
1682
-                4
1683
-        );
1684
-        add_filter(
1685
-                'FHEE__ee_migration_page__option_2_button_text',
1686
-                array($this, '_migration_page_hook_simplify_next_db_state'),
1687
-                10,
1688
-                2
1689
-        );
1690
-        add_filter(
1691
-                'FHEE__ee_migration_page__option_2_details',
1692
-                array($this, '_migration_page_hook_simplify_next_db_state'),
1693
-                10,
1694
-                2
1695
-        );
1696
-        add_action(
1697
-                'AHEE__ee_migration_page__after_migration_options_table',
1698
-                array($this, '_migration_page_hook_after_migration_options_table')
1699
-        );
1700
-        add_filter(
1701
-                'FHEE__ee_migration_page__done_migration_header',
1702
-                array($this, '_migration_page_hook_simplify_next_db_state'),
1703
-                10,
1704
-                2
1705
-        );
1706
-        add_filter(
1707
-                'FHEE__ee_migration_page__p_after_done_migration_header',
1708
-                array($this, '_migration_page_hook_simplify_next_db_state'),
1709
-                10,
1710
-                2
1711
-        );
1712
-        add_filter(
1713
-                'FHEE__ee_migration_page__migration_options_template',
1714
-                array($this,'use_migration_options_from_ee3_template')
1715
-        );
1716
-    }
1717
-
1718
-
1719
-
1720
-    public function _migrate_page_hook_simplify_version_strings(
1721
-            $old_content,
1722
-            $current_db_state,
1723
-            $next_db_state,
1724
-            $ultimate_db_state = null
1725
-    ) {
1726
-        return str_replace(array($current_db_state, $next_db_state, $ultimate_db_state),
1727
-                array(esc_html__('EE3', 'event_espresso'), esc_html__('EE4', 'event_espresso'), esc_html__("EE4", 'event_espresso')),
1728
-                $old_content);
1729
-    }
1730
-
1731
-
1732
-
1733
-    public function _migration_page_hook_simplify_next_db_state($old_content, $next_db_state)
1734
-    {
1735
-        return str_replace($next_db_state, esc_html__("EE4", 'event_espresso'), $old_content);
1736
-    }
1737
-
1738
-
1739
-
1740
-    public function _migration_page_hook_option_1_extra_details()
1741
-    {
1742
-        ?>
1063
+		if ( ! $state) {
1064
+			//insert a new one then
1065
+			$cols_n_values = array(
1066
+					'CNT_ISO'    => $country_iso,
1067
+					'STA_abbrev' => substr($state_name, 0, 6),
1068
+					'STA_name'   => $state_name,
1069
+					'STA_active' => true,
1070
+			);
1071
+			$data_types = array(
1072
+					'%s',//CNT_ISO
1073
+					'%s',//STA_abbrev
1074
+					'%s',//STA_name
1075
+					'%d',//STA_active
1076
+			);
1077
+			$success = $wpdb->insert($state_table, $cols_n_values, $data_types);
1078
+			if ( ! $success) {
1079
+				throw new EE_Error($this->_create_error_message_for_db_insertion('N/A',
1080
+						array('state' => $state_name, 'country_id' => $country_name), $state_table, $cols_n_values,
1081
+						$data_types));
1082
+			}
1083
+			$state = $cols_n_values;
1084
+			$state['STA_ID'] = $wpdb->insert_id;
1085
+		}
1086
+		return $state;
1087
+	}
1088
+
1089
+
1090
+
1091
+	/**
1092
+	 * Fixes times like "5:00 PM" into the expected 24-hour format "17:00".
1093
+	 * THis is actually just copied from the 3.1 JSON API because it needed to do the exact same thing
1094
+	 *
1095
+	 * @param type $timeString
1096
+	 * @return string in the php DATETIME format: "G:i" (24-hour format hour with leading zeros, a colon, and minutes
1097
+	 *                with leading zeros)
1098
+	 */
1099
+	public function convertTimeFromAMPM($timeString)
1100
+	{
1101
+		$matches = array();
1102
+		preg_match("~(\\d*):(\\d*)~", $timeString, $matches);
1103
+		if ( ! $matches || count($matches) < 3) {
1104
+			$hour = '00';
1105
+			$minutes = '00';
1106
+		} else {
1107
+			$hour = intval($matches[1]);
1108
+			$minutes = $matches[2];
1109
+		}
1110
+		if (strpos($timeString, 'PM') || strpos($timeString, 'pm')) {
1111
+			$hour = intval($hour) + 12;
1112
+		}
1113
+		$hour = str_pad("$hour", 2, '0', STR_PAD_LEFT);
1114
+		$minutes = str_pad("$minutes", 2, '0', STR_PAD_LEFT);
1115
+		return "$hour:$minutes";
1116
+	}
1117
+
1118
+
1119
+
1120
+	/**
1121
+	 * Gets the ISO3 fora country given its 3.1 country ID.
1122
+	 *
1123
+	 * @param int $country_id
1124
+	 * @return string the country's ISO3 code
1125
+	 */
1126
+	public function get_iso_from_3_1_country_id($country_id)
1127
+	{
1128
+		$old_countries = array(
1129
+				array(64, 'United States', 'US', 'USA', 1),
1130
+				array(15, 'Australia', 'AU', 'AUS', 1),
1131
+				array(39, 'Canada', 'CA', 'CAN', 1),
1132
+				array(171, 'United Kingdom', 'GB', 'GBR', 1),
1133
+				array(70, 'France', 'FR', 'FRA', 2),
1134
+				array(111, 'Italy', 'IT', 'ITA', 2),
1135
+				array(63, 'Spain', 'ES', 'ESP', 2),
1136
+				array(1, 'Afghanistan', 'AF', 'AFG', 1),
1137
+				array(2, 'Albania', 'AL', 'ALB', 1),
1138
+				array(3, 'Germany', 'DE', 'DEU', 2),
1139
+				array(198, 'Switzerland', 'CH', 'CHE', 1),
1140
+				array(87, 'Netherlands', 'NL', 'NLD', 2),
1141
+				array(197, 'Sweden', 'SE', 'SWE', 1),
1142
+				array(230, 'Akrotiri and Dhekelia', 'CY', 'CYP', 2),
1143
+				array(4, 'Andorra', 'AD', 'AND', 2),
1144
+				array(5, 'Angola', 'AO', 'AGO', 1),
1145
+				array(6, 'Anguilla', 'AI', 'AIA', 1),
1146
+				array(7, 'Antarctica', 'AQ', 'ATA', 1),
1147
+				array(8, 'Antigua and Barbuda', 'AG', 'ATG', 1),
1148
+				array(10, 'Saudi Arabia', 'SA', 'SAU', 1),
1149
+				array(11, 'Algeria', 'DZ', 'DZA', 1),
1150
+				array(12, 'Argentina', 'AR', 'ARG', 1),
1151
+				array(13, 'Armenia', 'AM', 'ARM', 1),
1152
+				array(14, 'Aruba', 'AW', 'ABW', 1),
1153
+				array(16, 'Austria', 'AT', 'AUT', 2),
1154
+				array(17, 'Azerbaijan', 'AZ', 'AZE', 1),
1155
+				array(18, 'Bahamas', 'BS', 'BHS', 1),
1156
+				array(19, 'Bahrain', 'BH', 'BHR', 1),
1157
+				array(20, 'Bangladesh', 'BD', 'BGD', 1),
1158
+				array(21, 'Barbados', 'BB', 'BRB', 1),
1159
+				array(22, 'Belgium ', 'BE', 'BEL', 2),
1160
+				array(23, 'Belize', 'BZ', 'BLZ', 1),
1161
+				array(24, 'Benin', 'BJ', 'BEN', 1),
1162
+				array(25, 'Bermudas', 'BM', 'BMU', 1),
1163
+				array(26, 'Belarus', 'BY', 'BLR', 1),
1164
+				array(27, 'Bolivia', 'BO', 'BOL', 1),
1165
+				array(28, 'Bosnia and Herzegovina', 'BA', 'BIH', 1),
1166
+				array(29, 'Botswana', 'BW', 'BWA', 1),
1167
+				array(96, 'Bouvet Island', 'BV', 'BVT', 1),
1168
+				array(30, 'Brazil', 'BR', 'BRA', 1),
1169
+				array(31, 'Brunei', 'BN', 'BRN', 1),
1170
+				array(32, 'Bulgaria', 'BG', 'BGR', 1),
1171
+				array(33, 'Burkina Faso', 'BF', 'BFA', 1),
1172
+				array(34, 'Burundi', 'BI', 'BDI', 1),
1173
+				array(35, 'Bhutan', 'BT', 'BTN', 1),
1174
+				array(36, 'Cape Verde', 'CV', 'CPV', 1),
1175
+				array(37, 'Cambodia', 'KH', 'KHM', 1),
1176
+				array(38, 'Cameroon', 'CM', 'CMR', 1),
1177
+				array(98, 'Cayman Islands', 'KY', 'CYM', 1),
1178
+				array(172, 'Central African Republic', 'CF', 'CAF', 1),
1179
+				array(40, 'Chad', 'TD', 'TCD', 1),
1180
+				array(41, 'Chile', 'CL', 'CHL', 1),
1181
+				array(42, 'China', 'CN', 'CHN', 1),
1182
+				array(105, 'Christmas Island', 'CX', 'CXR', 1),
1183
+				array(43, 'Cyprus', 'CY', 'CYP', 2),
1184
+				array(99, 'Cocos Island', 'CC', 'CCK', 1),
1185
+				array(100, 'Cook Islands', 'CK', 'COK', 1),
1186
+				array(44, 'Colombia', 'CO', 'COL', 1),
1187
+				array(45, 'Comoros', 'KM', 'COM', 1),
1188
+				array(46, 'Congo', 'CG', 'COG', 1),
1189
+				array(47, 'North Korea', 'KP', 'PRK', 1),
1190
+				array(50, 'Costa Rica', 'CR', 'CRI', 1),
1191
+				array(51, 'Croatia', 'HR', 'HRV', 1),
1192
+				array(52, 'Cuba', 'CU', 'CUB', 1),
1193
+				array(173, 'Czech Republic', 'CZ', 'CZE', 1),
1194
+				array(53, 'Denmark', 'DK', 'DNK', 1),
1195
+				array(54, 'Djibouti', 'DJ', 'DJI', 1),
1196
+				array(55, 'Dominica', 'DM', 'DMA', 1),
1197
+				array(174, 'Dominican Republic', 'DO', 'DOM', 1),
1198
+				array(56, 'Ecuador', 'EC', 'ECU', 1),
1199
+				array(57, 'Egypt', 'EG', 'EGY', 1),
1200
+				array(58, 'El Salvador', 'SV', 'SLV', 1),
1201
+				array(60, 'Eritrea', 'ER', 'ERI', 1),
1202
+				array(61, 'Slovakia', 'SK', 'SVK', 2),
1203
+				array(62, 'Slovenia', 'SI', 'SVN', 2),
1204
+				array(65, 'Estonia', 'EE', 'EST', 2),
1205
+				array(66, 'Ethiopia', 'ET', 'ETH', 1),
1206
+				array(102, 'Faroe islands', 'FO', 'FRO', 1),
1207
+				array(103, 'Falkland Islands', 'FK', 'FLK', 1),
1208
+				array(67, 'Fiji', 'FJ', 'FJI', 1),
1209
+				array(69, 'Finland', 'FI', 'FIN', 2),
1210
+				array(71, 'Gabon', 'GA', 'GAB', 1),
1211
+				array(72, 'Gambia', 'GM', 'GMB', 1),
1212
+				array(73, 'Georgia', 'GE', 'GEO', 1),
1213
+				array(74, 'Ghana', 'GH', 'GHA', 1),
1214
+				array(75, 'Gibraltar', 'GI', 'GIB', 1),
1215
+				array(76, 'Greece', 'GR', 'GRC', 2),
1216
+				array(77, 'Grenada', 'GD', 'GRD', 1),
1217
+				array(78, 'Greenland', 'GL', 'GRL', 1),
1218
+				array(79, 'Guadeloupe', 'GP', 'GLP', 1),
1219
+				array(80, 'Guam', 'GU', 'GUM', 1),
1220
+				array(81, 'Guatemala', 'GT', 'GTM', 1),
1221
+				array(82, 'Guinea', 'GN', 'GIN', 1),
1222
+				array(83, 'Equatorial Guinea', 'GQ', 'GNQ', 1),
1223
+				array(84, 'Guinea-Bissau', 'GW', 'GNB', 1),
1224
+				array(85, 'Guyana', 'GY', 'GUY', 1),
1225
+				array(86, 'Haiti', 'HT', 'HTI', 1),
1226
+				array(88, 'Honduras', 'HN', 'HND', 1),
1227
+				array(89, 'Hong Kong', 'HK', 'HKG', 1),
1228
+				array(90, 'Hungary', 'HU', 'HUN', 1),
1229
+				array(91, 'India', 'IN', 'IND', 1),
1230
+				array(205, 'British Indian Ocean Territory', 'IO', 'IOT', 1),
1231
+				array(92, 'Indonesia', 'ID', 'IDN', 1),
1232
+				array(93, 'Iraq', 'IQ', 'IRQ', 1),
1233
+				array(94, 'Iran', 'IR', 'IRN', 1),
1234
+				array(95, 'Ireland', 'IE', 'IRL', 2),
1235
+				array(97, 'Iceland', 'IS', 'ISL', 1),
1236
+				array(110, 'Israel', 'IL', 'ISR', 1),
1237
+				array(49, 'Ivory Coast ', 'CI', 'CIV', 1),
1238
+				array(112, 'Jamaica', 'JM', 'JAM', 1),
1239
+				array(113, 'Japan', 'JP', 'JPN', 1),
1240
+				array(114, 'Jordan', 'JO', 'JOR', 1),
1241
+				array(115, 'Kazakhstan', 'KZ', 'KAZ', 1),
1242
+				array(116, 'Kenya', 'KE', 'KEN', 1),
1243
+				array(117, 'Kyrgyzstan', 'KG', 'KGZ', 1),
1244
+				array(118, 'Kiribati', 'KI', 'KIR', 1),
1245
+				array(48, 'South Korea', 'KR', 'KOR', 1),
1246
+				array(228, 'Kosovo', 'XK', 'XKV', 2),
1247
+				// there is no official ISO code for Kosovo yet (http://geonames.wordpress.com/2010/03/08/xk-country-code-for-kosovo/) so using a temporary country code and a modified 3 character code for ISO code -- this should be updated if/when Kosovo gets its own ISO code
1248
+				array(119, 'Kuwait', 'KW', 'KWT', 1),
1249
+				array(120, 'Laos', 'LA', 'LAO', 1),
1250
+				array(121, 'Latvia', 'LV', 'LVA', 2),
1251
+				array(122, 'Lesotho', 'LS', 'LSO', 1),
1252
+				array(123, 'Lebanon', 'LB', 'LBN', 1),
1253
+				array(124, 'Liberia', 'LR', 'LBR', 1),
1254
+				array(125, 'Libya', 'LY', 'LBY', 1),
1255
+				array(126, 'Liechtenstein', 'LI', 'LIE', 1),
1256
+				array(127, 'Lithuania', 'LT', 'LTU', 2),
1257
+				array(128, 'Luxemburg', 'LU', 'LUX', 2),
1258
+				array(129, 'Macao', 'MO', 'MAC', 1),
1259
+				array(130, 'Macedonia', 'MK', 'MKD', 1),
1260
+				array(131, 'Madagascar', 'MG', 'MDG', 1),
1261
+				array(132, 'Malaysia', 'MY', 'MYS', 1),
1262
+				array(133, 'Malawi', 'MW', 'MWI', 1),
1263
+				array(134, 'Maldivas', 'MV', 'MDV', 1),
1264
+				array(135, 'Mali', 'ML', 'MLI', 1),
1265
+				array(136, 'Malta', 'MT', 'MLT', 2),
1266
+				array(101, 'Northern Marianas', 'MP', 'MNP', 1),
1267
+				array(137, 'Morocco', 'MA', 'MAR', 1),
1268
+				array(104, 'Marshall islands', 'MH', 'MHL', 1),
1269
+				array(138, 'Martinique', 'MQ', 'MTQ', 1),
1270
+				array(139, 'Mauritius', 'MU', 'MUS', 1),
1271
+				array(140, 'Mauritania', 'MR', 'MRT', 1),
1272
+				array(141, 'Mayote', 'YT', 'MYT', 2),
1273
+				array(142, 'Mexico', 'MX', 'MEX', 1),
1274
+				array(143, 'Micronesia', 'FM', 'FSM', 1),
1275
+				array(144, 'Moldova', 'MD', 'MDA', 1),
1276
+				array(145, 'Monaco', 'MC', 'MCO', 2),
1277
+				array(146, 'Mongolia', 'MN', 'MNG', 1),
1278
+				array(147, 'Montserrat', 'MS', 'MSR', 1),
1279
+				array(227, 'Montenegro', 'ME', 'MNE', 2),
1280
+				array(148, 'Mozambique', 'MZ', 'MOZ', 1),
1281
+				array(149, 'Myanmar', 'MM', 'MMR', 1),
1282
+				array(150, 'Namibia', 'NA', 'NAM', 1),
1283
+				array(151, 'Nauru', 'NR', 'NRU', 1),
1284
+				array(152, 'Nepal', 'NP', 'NPL', 1),
1285
+				array(9, 'Netherlands Antilles', 'AN', 'ANT', 1),
1286
+				array(153, 'Nicaragua', 'NI', 'NIC', 1),
1287
+				array(154, 'Niger', 'NE', 'NER', 1),
1288
+				array(155, 'Nigeria', 'NG', 'NGA', 1),
1289
+				array(156, 'Niue', 'NU', 'NIU', 1),
1290
+				array(157, 'Norway', 'NO', 'NOR', 1),
1291
+				array(158, 'New Caledonia', 'NC', 'NCL', 1),
1292
+				array(159, 'New Zealand', 'NZ', 'NZL', 1),
1293
+				array(160, 'Oman', 'OM', 'OMN', 1),
1294
+				array(161, 'Pakistan', 'PK', 'PAK', 1),
1295
+				array(162, 'Palau', 'PW', 'PLW', 1),
1296
+				array(163, 'Panama', 'PA', 'PAN', 1),
1297
+				array(164, 'Papua New Guinea', 'PG', 'PNG', 1),
1298
+				array(165, 'Paraguay', 'PY', 'PRY', 1),
1299
+				array(166, 'Peru', 'PE', 'PER', 1),
1300
+				array(68, 'Philippines', 'PH', 'PHL', 1),
1301
+				array(167, 'Poland', 'PL', 'POL', 1),
1302
+				array(168, 'Portugal', 'PT', 'PRT', 2),
1303
+				array(169, 'Puerto Rico', 'PR', 'PRI', 1),
1304
+				array(170, 'Qatar', 'QA', 'QAT', 1),
1305
+				array(176, 'Rwanda', 'RW', 'RWA', 1),
1306
+				array(177, 'Romania', 'RO', 'ROM', 2),
1307
+				array(178, 'Russia', 'RU', 'RUS', 1),
1308
+				array(229, 'Saint Pierre and Miquelon', 'PM', 'SPM', 2),
1309
+				array(180, 'Samoa', 'WS', 'WSM', 1),
1310
+				array(181, 'American Samoa', 'AS', 'ASM', 1),
1311
+				array(183, 'San Marino', 'SM', 'SMR', 2),
1312
+				array(184, 'Saint Vincent and the Grenadines', 'VC', 'VCT', 1),
1313
+				array(185, 'Saint Helena', 'SH', 'SHN', 1),
1314
+				array(186, 'Saint Lucia', 'LC', 'LCA', 1),
1315
+				array(188, 'Senegal', 'SN', 'SEN', 1),
1316
+				array(189, 'Seychelles', 'SC', 'SYC', 1),
1317
+				array(190, 'Sierra Leona', 'SL', 'SLE', 1),
1318
+				array(191, 'Singapore', 'SG', 'SGP', 1),
1319
+				array(192, 'Syria', 'SY', 'SYR', 1),
1320
+				array(193, 'Somalia', 'SO', 'SOM', 1),
1321
+				array(194, 'Sri Lanka', 'LK', 'LKA', 1),
1322
+				array(195, 'South Africa', 'ZA', 'ZAF', 1),
1323
+				array(196, 'Sudan', 'SD', 'SDN', 1),
1324
+				array(199, 'Suriname', 'SR', 'SUR', 1),
1325
+				array(200, 'Swaziland', 'SZ', 'SWZ', 1),
1326
+				array(201, 'Thailand', 'TH', 'THA', 1),
1327
+				array(202, 'Taiwan', 'TW', 'TWN', 1),
1328
+				array(203, 'Tanzania', 'TZ', 'TZA', 1),
1329
+				array(204, 'Tajikistan', 'TJ', 'TJK', 1),
1330
+				array(206, 'Timor-Leste', 'TL', 'TLS', 1),
1331
+				array(207, 'Togo', 'TG', 'TGO', 1),
1332
+				array(208, 'Tokelau', 'TK', 'TKL', 1),
1333
+				array(209, 'Tonga', 'TO', 'TON', 1),
1334
+				array(210, 'Trinidad and Tobago', 'TT', 'TTO', 1),
1335
+				array(211, 'Tunisia', 'TN', 'TUN', 1),
1336
+				array(212, 'Turkmenistan', 'TM', 'TKM', 1),
1337
+				array(213, 'Turkey', 'TR', 'TUR', 1),
1338
+				array(214, 'Tuvalu', 'TV', 'TUV', 1),
1339
+				array(215, 'Ukraine', 'UA', 'UKR', 1),
1340
+				array(216, 'Uganda', 'UG', 'UGA', 1),
1341
+				array(59, 'United Arab Emirates', 'AE', 'ARE', 1),
1342
+				array(217, 'Uruguay', 'UY', 'URY', 1),
1343
+				array(218, 'Uzbekistan', 'UZ', 'UZB', 1),
1344
+				array(219, 'Vanuatu', 'VU', 'VUT', 1),
1345
+				array(220, 'Vatican City', 'VA', 'VAT', 2),
1346
+				array(221, 'Venezuela', 'VE', 'VEN', 1),
1347
+				array(222, 'Vietnam', 'VN', 'VNM', 1),
1348
+				array(108, 'Virgin Islands', 'VI', 'VIR', 1),
1349
+				array(223, 'Yemen', 'YE', 'YEM', 1),
1350
+				array(225, 'Zambia', 'ZM', 'ZMB', 1),
1351
+				array(226, 'Zimbabwe', 'ZW', 'ZWE', 1),
1352
+		);
1353
+		$country_iso = 'US';
1354
+		foreach ($old_countries as $country_array) {
1355
+			//note: index 0 is the 3.1 country ID
1356
+			if ($country_array[0] == $country_id) {
1357
+				//note: index 2 is the ISO
1358
+				$country_iso = $country_array[2];
1359
+				break;
1360
+			}
1361
+		}
1362
+		return $country_iso;
1363
+	}
1364
+
1365
+
1366
+
1367
+	/**
1368
+	 * Gets the ISO3 for the
1369
+	 *
1370
+	 * @return string
1371
+	 */
1372
+	public function get_default_country_iso()
1373
+	{
1374
+		$old_org_options = get_option('events_organization_settings');
1375
+		$iso = $this->get_iso_from_3_1_country_id($old_org_options['organization_country']);
1376
+		return $iso;
1377
+	}
1378
+
1379
+
1380
+
1381
+	/**
1382
+	 * Converst a 3.1 payment status to its equivalent 4.1 regisration status
1383
+	 *
1384
+	 * @param string  $payment_status                   possible value for 3.1's evens_attendee.payment_status
1385
+	 * @param boolean $this_thing_required_pre_approval whether the thing we're considering (the general setting's
1386
+	 *                                                  DEFAULT payment status, the event's DEFAULT payment status, or
1387
+	 *                                                  the attendee's payment status) required pre-approval.
1388
+	 * @return string STS_ID for use in 4.1
1389
+	 */
1390
+	public function convert_3_1_payment_status_to_4_1_STS_ID($payment_status, $this_thing_required_pre_approval = false)
1391
+	{
1392
+		//EE team can read the related discussion: https://app.asana.com/0/2400967562914/9418495544455
1393
+		if ($this_thing_required_pre_approval) {
1394
+			return 'RNA';
1395
+		} else {
1396
+			$mapping = $default_reg_stati_conversions = array(
1397
+					'Completed'        => 'RAP',
1398
+					''                 => 'RPP',
1399
+					'Incomplete'       => 'RPP',
1400
+					'Pending'          => 'RAP',
1401
+					//stati that only occurred on 3.1 attendees:
1402
+					'Payment Declined' => 'RPP',
1403
+					'Not Completed'    => 'RPP',
1404
+					'Cancelled'        => 'RPP',
1405
+					'Declined'         => 'RPP',
1406
+			);
1407
+		}
1408
+		return isset($mapping[$payment_status]) ? $mapping[$payment_status] : 'RNA';
1409
+	}
1410
+
1411
+
1412
+
1413
+	/**
1414
+	 * Makes sure the 3.1's image url is converted to an image attachment post to the 4.1 CPT event
1415
+	 * and sets it as the featured image on the CPT event
1416
+	 *
1417
+	 * @param type                            $old_event
1418
+	 * @param type                            $new_cpt_id
1419
+	 * @param  EE_Data_Migration_Script_Stage $migration_stage the stage which called this, where errors should be added
1420
+	 * @return boolean whether or not we had to do the big job of creating an image attachment
1421
+	 */
1422
+	public function convert_image_url_to_attachment_and_attach_to_post(
1423
+			$guid,
1424
+			$new_cpt_id,
1425
+			EE_Data_Migration_Script_Stage $migration_stage
1426
+	) {
1427
+		$created_attachment_post = false;
1428
+		$guid = $this->_get_original_guid($guid);
1429
+		if ($guid) {
1430
+			//check for an existing attachment post with this guid
1431
+			$attachment_post_id = $this->_get_image_attachment_id_by_GUID($guid);
1432
+			if ( ! $attachment_post_id) {
1433
+				//post thumbnail with that GUID doesn't exist, we should create one
1434
+				$attachment_post_id = $this->_create_image_attachment_from_GUID($guid, $migration_stage);
1435
+				$created_attachment_post = true;
1436
+			}
1437
+			//double-check we actually have an attachment post
1438
+			if ($attachment_post_id) {
1439
+				update_post_meta($new_cpt_id, '_thumbnail_id', $attachment_post_id);
1440
+			} else {
1441
+				$migration_stage->add_error(sprintf(esc_html__("Could not update event image %s for CPT with ID %d, but attachments post ID is %d",
1442
+						"event_espresso"), $guid, $new_cpt_id, $attachment_post_id));
1443
+			}
1444
+		}
1445
+		return $created_attachment_post;
1446
+	}
1447
+
1448
+
1449
+
1450
+	/**
1451
+	 * In 3.1, the event thumbnail image DOESN'T point to the orignal image, but instead
1452
+	 * to a large thumbnail (which has nearly the same GUID, except it adds "-{width}x{height}" before the filetype,
1453
+	 * or whatever dimensions it is. Eg 'http://mysite.com/image1-300x400.jpg' instead of
1454
+	 * 'http://mysite.com/image1.jpg' ). This function attempts to strip that off and get the original file, if it
1455
+	 * exists
1456
+	 *
1457
+	 * @param string $guid_in_old_event
1458
+	 * @return string either the original guid, or $guid_in_old_event if we couldn't figure out what the original was
1459
+	 */
1460
+	private function _get_original_guid($guid_in_old_event)
1461
+	{
1462
+		$original_guid = preg_replace('~-\d*x\d*\.~', '.', $guid_in_old_event, 1);
1463
+		//do a head request to verify the file exists
1464
+		$head_response = wp_remote_head($original_guid);
1465
+		if ( ! $head_response instanceof WP_Error && $head_response['response']['message'] == 'OK') {
1466
+			return $original_guid;
1467
+		} else {
1468
+			return $guid_in_old_event;
1469
+		}
1470
+	}
1471
+
1472
+
1473
+
1474
+	/**
1475
+	 * Creates an image attachment post for the GUID. If the GUID points to a remote image,
1476
+	 * we download it to our uploads directory so that it can be properly processed (eg, creates different sizes of
1477
+	 * thumbnails)
1478
+	 *
1479
+	 * @param type                           $guid
1480
+	 * @param EE_Data_Migration_Script_Stage $migration_stage
1481
+	 * @return int
1482
+	 */
1483
+	private function _create_image_attachment_from_GUID($guid, EE_Data_Migration_Script_Stage $migration_stage)
1484
+	{
1485
+		if ( ! $guid) {
1486
+			$migration_stage->add_error(sprintf(esc_html__("Cannot create image attachment for a blank GUID!",
1487
+					"event_espresso")));
1488
+			return 0;
1489
+		}
1490
+		$wp_filetype = wp_check_filetype(basename($guid), null);
1491
+		$wp_upload_dir = wp_upload_dir();
1492
+		//if the file is located remotely, download it to our uploads DIR, because wp_genereate_attachmnet_metadata needs the file to be local
1493
+		if (strpos($guid, $wp_upload_dir['url']) === false) {
1494
+			//image is located remotely. download it and place it in the uploads directory
1495
+			if ( ! is_readable($guid)) {
1496
+				$migration_stage->add_error(sprintf(esc_html__("Could not create image attachment from non-existent file: %s",
1497
+						"event_espresso"), $guid));
1498
+				return 0;
1499
+			}
1500
+			$contents = file_get_contents($guid);
1501
+			if ($contents === false) {
1502
+				$migration_stage->add_error(sprintf(esc_html__("Could not read image at %s, and therefore couldnt create an attachment post for it.",
1503
+						"event_espresso"), $guid));
1504
+				return false;
1505
+			}
1506
+			$local_filepath = $wp_upload_dir['path'] . DS . basename($guid);
1507
+			$savefile = fopen($local_filepath, 'w');
1508
+			fwrite($savefile, $contents);
1509
+			fclose($savefile);
1510
+			$guid = str_replace($wp_upload_dir['path'], $wp_upload_dir['url'], $local_filepath);
1511
+		} else {
1512
+			$local_filepath = str_replace($wp_upload_dir['url'], $wp_upload_dir['path'], $guid);
1513
+		}
1514
+		$attachment = array(
1515
+				'guid'           => $guid,
1516
+				'post_mime_type' => $wp_filetype['type'],
1517
+				'post_title'     => preg_replace('/\.[^.]+$/', '', basename($guid)),
1518
+				'post_content'   => '',
1519
+				'post_status'    => 'inherit',
1520
+		);
1521
+		$attach_id = wp_insert_attachment($attachment, $guid);
1522
+		if ( ! $attach_id) {
1523
+			$migration_stage->add_error(sprintf(esc_html__("Could not create image attachment post from image '%s'. Attachment data was %s.",
1524
+					"event_espresso"), $guid, $this->_json_encode($attachment)));
1525
+			return $attach_id;
1526
+		}
1527
+		// you must first include the image.php file
1528
+		// for the function wp_generate_attachment_metadata() to work
1529
+		require_once(ABSPATH . 'wp-admin/includes/image.php');
1530
+		$attach_data = wp_generate_attachment_metadata($attach_id, $local_filepath);
1531
+		if ( ! $attach_data) {
1532
+			$migration_stage->add_error(sprintf(esc_html__("Coudl not genereate attachment metadata for attachment post %d with filepath %s and GUID %s. Please check the file was downloaded properly.",
1533
+					"event_espresso"), $attach_id, $local_filepath, $guid));
1534
+			return $attach_id;
1535
+		}
1536
+		$metadata_save_result = wp_update_attachment_metadata($attach_id, $attach_data);
1537
+		if ( ! $metadata_save_result) {
1538
+			$migration_stage->add_error(sprintf(esc_html__("Could not update attachment metadata for attachment %d with data %s",
1539
+					"event_espresso"), $attach_id, $this->_json_encode($attach_data)));
1540
+		}
1541
+		return $attach_id;
1542
+	}
1543
+
1544
+
1545
+
1546
+	/**
1547
+	 * Finds the attachment post containing info about an image attachment given the GUID (link to the image itself),
1548
+	 * and returns its ID.
1549
+	 *
1550
+	 * @global type  $wpdb
1551
+	 * @param string $guid
1552
+	 * @return int
1553
+	 */
1554
+	private function _get_image_attachment_id_by_GUID($guid)
1555
+	{
1556
+		global $wpdb;
1557
+		$attachment_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid=%s LIMIT 1", $guid));
1558
+		return $attachment_id;
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 * Returns a mysql-formatted DATETIME in UTC time, given a $DATETIME_string
1565
+	 * (and optionally a timezone; if none is given, the wp DEFAULT is used)
1566
+	 *
1567
+	 * @param EE_Data_Migration_Script_base $stage
1568
+	 * @param array                         $row_of_data , the row from the DB (as an array) we're trying to find the
1569
+	 *                                                   UTC time for
1570
+	 * @param string                        $DATETIME_string
1571
+	 * @param string                        $timezone
1572
+	 * @return string
1573
+	 */
1574
+	public function convert_date_string_to_utc(
1575
+			EE_Data_Migration_Script_Stage $stage,
1576
+			$row_of_data,
1577
+			$DATETIME_string,
1578
+			$timezone = null
1579
+	) {
1580
+		$original_tz = $timezone;
1581
+		if ( ! $timezone) {
1582
+			$timezone = $this->_get_wp_timezone();
1583
+		}
1584
+		if ( ! $timezone) {
1585
+			$stage->add_error(sprintf(esc_html__("Could not find timezone given %s for %s", "event_espresso"), $original_tz,
1586
+					$row_of_data));
1587
+			$timezone = 'UTC';
1588
+		}
1589
+		try {
1590
+			$date_obj = new DateTime($DATETIME_string, new DateTimeZone($timezone));
1591
+			$date_obj->setTimezone(new DateTimeZone('UTC'));
1592
+			// workaround for php datetime bug (@see https://events.codebasehq.com/projects/event-espresso/tickets/11407
1593
+			$date_obj->getTimestamp();
1594
+		} catch (Exception $e) {
1595
+			$stage->add_error(sprintf(esc_html__("Could not convert time string '%s' using timezone '%s' into a proper DATETIME. Using current time instead.",
1596
+					"event_espresso"), $DATETIME_string, $timezone));
1597
+			$date_obj = new DateTime();
1598
+		}
1599
+		return $date_obj->format('Y-m-d H:i:s');
1600
+	}
1601
+
1602
+
1603
+
1604
+	/**
1605
+	 * Gets the DEFAULT timezone string from wordpress (even if they set a gmt offset)
1606
+	 *
1607
+	 * @return string
1608
+	 */
1609
+	private function _get_wp_timezone()
1610
+	{
1611
+		$timezone = empty($timezone) ? get_option('timezone_string') : $timezone;
1612
+		//if timezone is STILL empty then let's get the GMT offset and then set the timezone_string using our converter
1613
+		if (empty($timezone)) {
1614
+			//let's get a the WordPress UTC offset
1615
+			$offset = get_option('gmt_offset');
1616
+			$timezone = $this->timezone_convert_to_string_from_offset($offset);
1617
+		}
1618
+		return $timezone;
1619
+	}
1620
+
1621
+
1622
+
1623
+	/**
1624
+	 * Gets the wordpress timezone string from a UTC offset
1625
+	 *
1626
+	 * @param int $offset
1627
+	 * @return boolean
1628
+	 */
1629
+	private function timezone_convert_to_string_from_offset($offset)
1630
+	{
1631
+		//shamelessly taken from bottom comment at http://ca1.php.net/manual/en/function.timezone-name-from-abbr.php because timezone_name_from_abbr() did NOT work as expected - its not reliable
1632
+		$offset *= 3600; // convert hour offset to seconds
1633
+		$abbrarray = timezone_abbreviations_list();
1634
+		foreach ($abbrarray as $abbr) {
1635
+			foreach ($abbr as $city) {
1636
+				if ($city['offset'] == $offset) {
1637
+					return $city['timezone_id'];
1638
+				}
1639
+			}
1640
+		}
1641
+		return false;
1642
+	}
1643
+
1644
+
1645
+
1646
+	public function migration_page_hooks()
1647
+	{
1648
+		add_filter(
1649
+				'FHEE__ee_migration_page__header',
1650
+				array($this, '_migrate_page_hook_simplify_version_strings'),
1651
+				10,
1652
+				3
1653
+		);
1654
+		add_filter(
1655
+				'FHEE__ee_migration_page__p_after_header',
1656
+				array($this, '_migration_page_hook_simplify_next_db_state'),
1657
+				10,
1658
+				2
1659
+		);
1660
+		add_filter(
1661
+				'FHEE__ee_migration_page__option_1_main',
1662
+				array($this, '_migrate_page_hook_simplify_version_strings'),
1663
+				10,
1664
+				3
1665
+		);
1666
+		add_filter(
1667
+				'FHEE__ee_migration_page__option_1_button_text',
1668
+				array($this, '_migrate_page_hook_simplify_version_strings'),
1669
+				10,
1670
+				3
1671
+		);
1672
+		add_action(
1673
+				'AHEE__ee_migration_page__option_1_extra_details',
1674
+				array($this, '_migration_page_hook_option_1_extra_details'),
1675
+				10,
1676
+				3
1677
+		);
1678
+		add_filter(
1679
+				'FHEE__ee_migration_page__option_2_main',
1680
+				array($this, '_migrate_page_hook_simplify_version_strings'),
1681
+				10,
1682
+				4
1683
+		);
1684
+		add_filter(
1685
+				'FHEE__ee_migration_page__option_2_button_text',
1686
+				array($this, '_migration_page_hook_simplify_next_db_state'),
1687
+				10,
1688
+				2
1689
+		);
1690
+		add_filter(
1691
+				'FHEE__ee_migration_page__option_2_details',
1692
+				array($this, '_migration_page_hook_simplify_next_db_state'),
1693
+				10,
1694
+				2
1695
+		);
1696
+		add_action(
1697
+				'AHEE__ee_migration_page__after_migration_options_table',
1698
+				array($this, '_migration_page_hook_after_migration_options_table')
1699
+		);
1700
+		add_filter(
1701
+				'FHEE__ee_migration_page__done_migration_header',
1702
+				array($this, '_migration_page_hook_simplify_next_db_state'),
1703
+				10,
1704
+				2
1705
+		);
1706
+		add_filter(
1707
+				'FHEE__ee_migration_page__p_after_done_migration_header',
1708
+				array($this, '_migration_page_hook_simplify_next_db_state'),
1709
+				10,
1710
+				2
1711
+		);
1712
+		add_filter(
1713
+				'FHEE__ee_migration_page__migration_options_template',
1714
+				array($this,'use_migration_options_from_ee3_template')
1715
+		);
1716
+	}
1717
+
1718
+
1719
+
1720
+	public function _migrate_page_hook_simplify_version_strings(
1721
+			$old_content,
1722
+			$current_db_state,
1723
+			$next_db_state,
1724
+			$ultimate_db_state = null
1725
+	) {
1726
+		return str_replace(array($current_db_state, $next_db_state, $ultimate_db_state),
1727
+				array(esc_html__('EE3', 'event_espresso'), esc_html__('EE4', 'event_espresso'), esc_html__("EE4", 'event_espresso')),
1728
+				$old_content);
1729
+	}
1730
+
1731
+
1732
+
1733
+	public function _migration_page_hook_simplify_next_db_state($old_content, $next_db_state)
1734
+	{
1735
+		return str_replace($next_db_state, esc_html__("EE4", 'event_espresso'), $old_content);
1736
+	}
1737
+
1738
+
1739
+
1740
+	public function _migration_page_hook_option_1_extra_details()
1741
+	{
1742
+		?>
1743 1743
         <p><?php printf(esc_html__("Note: many of your EE3 shortcodes will be changed to EE4 shortcodes during this migration (among many other things). Should you revert to EE3, then you should restore to your backup or manually change the EE4 shortcodes back to their EE3 equivalents",
1744
-            "event_espresso")); ?></p><?php
1745
-    }
1744
+			"event_espresso")); ?></p><?php
1745
+	}
1746 1746
 
1747 1747
 
1748 1748
 
1749
-    public function _migration_page_hook_after_migration_options_table()
1750
-    {
1751
-        ?><p class="ee-attention">
1749
+	public function _migration_page_hook_after_migration_options_table()
1750
+	{
1751
+		?><p class="ee-attention">
1752 1752
         <strong><span class="reminder-spn"><?php _e("Important note to those using Event Espresso 3 addons: ",
1753
-                        "event_espresso"); ?></span></strong>
1753
+						"event_espresso"); ?></span></strong>
1754 1754
         <br/><?php _e("Unless an addon's description on our website explicitly states that it is compatible with EE4, you should consider it incompatible and know that it WILL NOT WORK correctly with this new version of Event Espresso 4 (EE4). As well, any data for incompatible addons will NOT BE MIGRATED until an updated EE4 compatible version of the addon is available. If you want, or need to keep using your EE3 addons, you should simply continue using EE3 until EE4 compatible versions of your addons become available. To continue using EE3 for now, just deactivate EE4 and reactivate EE3.",
1755
-            "event_espresso"); ?>
1755
+			"event_espresso"); ?>
1756 1756
         </p><?php
1757
-    }
1757
+	}
1758 1758
 
1759 1759
 
1760 1760
 
1761
-    /**
1762
-     * When showing the migration options, show more options and info than normal (ie, give folks the option
1763
-     * to start using EE4 without migrating. From EE3 that's fine, because it doesn't actually remove any data, because
1764
-     * EE4 doesn't have any yet. But when migrating from EE4 it would remove old data, so its not a great idea).
1765
-     * @param $template_filepath
1766
-     * @return string
1767
-     */
1768
-    public function use_migration_options_from_ee3_template( $template_filepath ) {
1769
-        return EE_MAINTENANCE_TEMPLATE_PATH . 'migration_options_from_ee3.template.php';
1770
-    }
1761
+	/**
1762
+	 * When showing the migration options, show more options and info than normal (ie, give folks the option
1763
+	 * to start using EE4 without migrating. From EE3 that's fine, because it doesn't actually remove any data, because
1764
+	 * EE4 doesn't have any yet. But when migrating from EE4 it would remove old data, so its not a great idea).
1765
+	 * @param $template_filepath
1766
+	 * @return string
1767
+	 */
1768
+	public function use_migration_options_from_ee3_template( $template_filepath ) {
1769
+		return EE_MAINTENANCE_TEMPLATE_PATH . 'migration_options_from_ee3.template.php';
1770
+	}
1771 1771
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Indentation   +3144 added lines, -3144 removed lines patch added patch discarded remove patch
@@ -15,3150 +15,3150 @@
 block discarded – undo
15 15
 abstract class EE_Base_Class
16 16
 {
17 17
 
18
-    /**
19
-     * This is an array of the original properties and values provided during construction
20
-     * of this model object. (keys are model field names, values are their values).
21
-     * This list is important to remember so that when we are merging data from the db, we know
22
-     * which values to override and which to not override.
23
-     *
24
-     * @var array
25
-     */
26
-    protected $_props_n_values_provided_in_constructor;
27
-
28
-    /**
29
-     * Timezone
30
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
31
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
32
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
33
-     * access to it.
34
-     *
35
-     * @var string
36
-     */
37
-    protected $_timezone;
38
-
39
-    /**
40
-     * date format
41
-     * pattern or format for displaying dates
42
-     *
43
-     * @var string $_dt_frmt
44
-     */
45
-    protected $_dt_frmt;
46
-
47
-    /**
48
-     * time format
49
-     * pattern or format for displaying time
50
-     *
51
-     * @var string $_tm_frmt
52
-     */
53
-    protected $_tm_frmt;
54
-
55
-    /**
56
-     * This property is for holding a cached array of object properties indexed by property name as the key.
57
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
58
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
59
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
60
-     *
61
-     * @var array
62
-     */
63
-    protected $_cached_properties = array();
64
-
65
-    /**
66
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
67
-     * single
68
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
69
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
70
-     * all others have an array)
71
-     *
72
-     * @var array
73
-     */
74
-    protected $_model_relations = array();
75
-
76
-    /**
77
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
78
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
79
-     *
80
-     * @var array
81
-     */
82
-    protected $_fields = array();
83
-
84
-    /**
85
-     * @var boolean indicating whether or not this model object is intended to ever be saved
86
-     * For example, we might create model objects intended to only be used for the duration
87
-     * of this request and to be thrown away, and if they were accidentally saved
88
-     * it would be a bug.
89
-     */
90
-    protected $_allow_persist = true;
91
-
92
-    /**
93
-     * @var boolean indicating whether or not this model object's properties have changed since construction
94
-     */
95
-    protected $_has_changes = false;
96
-
97
-    /**
98
-     * @var EEM_Base
99
-     */
100
-    protected $_model;
101
-
102
-    /**
103
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
104
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
105
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
106
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
107
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
108
-     * array as:
109
-     * array(
110
-     *  'Registration_Count' => 24
111
-     * );
112
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
113
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
114
-     * info)
115
-     *
116
-     * @var array
117
-     */
118
-    protected $custom_selection_results = array();
119
-
120
-
121
-    /**
122
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
123
-     * play nice
124
-     *
125
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
126
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
127
-     *                                                         TXN_amount, QST_name, etc) and values are their values
128
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
129
-     *                                                         corresponding db model or not.
130
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
131
-     *                                                         be in when instantiating a EE_Base_Class object.
132
-     * @param array   $date_formats                            An array of date formats to set on construct where first
133
-     *                                                         value is the date_format and second value is the time
134
-     *                                                         format.
135
-     * @throws InvalidArgumentException
136
-     * @throws InvalidInterfaceException
137
-     * @throws InvalidDataTypeException
138
-     * @throws EE_Error
139
-     * @throws ReflectionException
140
-     */
141
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
142
-    {
143
-        $className = get_class($this);
144
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
145
-        $model        = $this->get_model();
146
-        $model_fields = $model->field_settings(false);
147
-        // ensure $fieldValues is an array
148
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
149
-        // verify client code has not passed any invalid field names
150
-        foreach ($fieldValues as $field_name => $field_value) {
151
-            if (! isset($model_fields[ $field_name ])) {
152
-                throw new EE_Error(
153
-                    sprintf(
154
-                        esc_html__(
155
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
156
-                            'event_espresso'
157
-                        ),
158
-                        $field_name,
159
-                        get_class($this),
160
-                        implode(', ', array_keys($model_fields))
161
-                    )
162
-                );
163
-            }
164
-        }
165
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
166
-        if (! empty($date_formats) && is_array($date_formats)) {
167
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
168
-        } else {
169
-            //set default formats for date and time
170
-            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
171
-            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
172
-        }
173
-        //if db model is instantiating
174
-        if ($bydb) {
175
-            //client code has indicated these field values are from the database
176
-            foreach ($model_fields as $fieldName => $field) {
177
-                $this->set_from_db(
178
-                    $fieldName,
179
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
180
-                );
181
-            }
182
-        } else {
183
-            //we're constructing a brand
184
-            //new instance of the model object. Generally, this means we'll need to do more field validation
185
-            foreach ($model_fields as $fieldName => $field) {
186
-                $this->set(
187
-                    $fieldName,
188
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null, true
189
-                );
190
-            }
191
-        }
192
-        //remember what values were passed to this constructor
193
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
194
-        //remember in entity mapper
195
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
196
-            $model->add_to_entity_map($this);
197
-        }
198
-        //setup all the relations
199
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
-                $this->_model_relations[ $relation_name ] = null;
202
-            } else {
203
-                $this->_model_relations[ $relation_name ] = array();
204
-            }
205
-        }
206
-        /**
207
-         * Action done at the end of each model object construction
208
-         *
209
-         * @param EE_Base_Class $this the model object just created
210
-         */
211
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
-    }
213
-
214
-
215
-    /**
216
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
217
-     *
218
-     * @return boolean
219
-     */
220
-    public function allow_persist()
221
-    {
222
-        return $this->_allow_persist;
223
-    }
224
-
225
-
226
-    /**
227
-     * Sets whether or not this model object should be allowed to be saved to the DB.
228
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
229
-     * you got new information that somehow made you change your mind.
230
-     *
231
-     * @param boolean $allow_persist
232
-     * @return boolean
233
-     */
234
-    public function set_allow_persist($allow_persist)
235
-    {
236
-        return $this->_allow_persist = $allow_persist;
237
-    }
238
-
239
-
240
-    /**
241
-     * Gets the field's original value when this object was constructed during this request.
242
-     * This can be helpful when determining if a model object has changed or not
243
-     *
244
-     * @param string $field_name
245
-     * @return mixed|null
246
-     * @throws ReflectionException
247
-     * @throws InvalidArgumentException
248
-     * @throws InvalidInterfaceException
249
-     * @throws InvalidDataTypeException
250
-     * @throws EE_Error
251
-     */
252
-    public function get_original($field_name)
253
-    {
254
-        if (isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
256
-        ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
-        }
259
-        return null;
260
-    }
261
-
262
-
263
-    /**
264
-     * @param EE_Base_Class $obj
265
-     * @return string
266
-     */
267
-    public function get_class($obj)
268
-    {
269
-        return get_class($obj);
270
-    }
271
-
272
-
273
-    /**
274
-     * Overrides parent because parent expects old models.
275
-     * This also doesn't do any validation, and won't work for serialized arrays
276
-     *
277
-     * @param    string $field_name
278
-     * @param    mixed  $field_value
279
-     * @param bool      $use_default
280
-     * @throws InvalidArgumentException
281
-     * @throws InvalidInterfaceException
282
-     * @throws InvalidDataTypeException
283
-     * @throws EE_Error
284
-     * @throws ReflectionException
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     */
288
-    public function set($field_name, $field_value, $use_default = false)
289
-    {
290
-        // if not using default and nothing has changed, and object has already been setup (has ID),
291
-        // then don't do anything
292
-        if (
293
-            ! $use_default
294
-            && $this->_fields[ $field_name ] === $field_value
295
-            && $this->ID()
296
-        ) {
297
-            return;
298
-        }
299
-        $model              = $this->get_model();
300
-        $this->_has_changes = true;
301
-        $field_obj          = $model->field_settings_for($field_name);
302
-        if ($field_obj instanceof EE_Model_Field_Base) {
303
-            //			if ( method_exists( $field_obj, 'set_timezone' )) {
304
-            if ($field_obj instanceof EE_Datetime_Field) {
305
-                $field_obj->set_timezone($this->_timezone);
306
-                $field_obj->set_date_format($this->_dt_frmt);
307
-                $field_obj->set_time_format($this->_tm_frmt);
308
-            }
309
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
310
-            //should the value be null?
311
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
313
-                /**
314
-                 * To save having to refactor all the models, if a default value is used for a
315
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
-                 * object.
318
-                 *
319
-                 * @since 4.6.10+
320
-                 */
321
-                if (
322
-                    $field_obj instanceof EE_Datetime_Field
323
-                    && $this->_fields[ $field_name ] !== null
324
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
325
-                ) {
326
-                    empty($this->_fields[ $field_name ])
327
-                        ? $this->set($field_name, time())
328
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
329
-                }
330
-            } else {
331
-                $this->_fields[ $field_name ] = $holder_of_value;
332
-            }
333
-            //if we're not in the constructor...
334
-            //now check if what we set was a primary key
335
-            if (
336
-                //note: props_n_values_provided_in_constructor is only set at the END of the constructor
337
-                $this->_props_n_values_provided_in_constructor
338
-                && $field_value
339
-                && $field_name === $model->primary_key_name()
340
-            ) {
341
-                //if so, we want all this object's fields to be filled either with
342
-                //what we've explicitly set on this model
343
-                //or what we have in the db
344
-                // echo "setting primary key!";
345
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
346
-                $obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
-                foreach ($fields_on_model as $field_obj) {
348
-                    if (! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
349
-                        && $field_obj->get_name() !== $field_name
350
-                    ) {
351
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
352
-                    }
353
-                }
354
-                //oh this model object has an ID? well make sure its in the entity mapper
355
-                $model->add_to_entity_map($this);
356
-            }
357
-            //let's unset any cache for this field_name from the $_cached_properties property.
358
-            $this->_clear_cached_property($field_name);
359
-        } else {
360
-            throw new EE_Error(
361
-                sprintf(
362
-                    esc_html__(
363
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
364
-                        'event_espresso'
365
-                    ),
366
-                    $field_name
367
-                )
368
-            );
369
-        }
370
-    }
371
-
372
-
373
-    /**
374
-     * Set custom select values for model.
375
-     *
376
-     * @param array $custom_select_values
377
-     */
378
-    public function setCustomSelectsValues(array $custom_select_values)
379
-    {
380
-        $this->custom_selection_results = $custom_select_values;
381
-    }
382
-
383
-
384
-    /**
385
-     * Returns the custom select value for the provided alias if its set.
386
-     * If not set, returns null.
387
-     *
388
-     * @param string $alias
389
-     * @return string|int|float|null
390
-     */
391
-    public function getCustomSelect($alias)
392
-    {
393
-        return isset($this->custom_selection_results[ $alias ])
394
-            ? $this->custom_selection_results[ $alias ]
395
-            : null;
396
-    }
397
-
398
-
399
-    /**
400
-     * This sets the field value on the db column if it exists for the given $column_name or
401
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
402
-     *
403
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
404
-     * @param string $field_name  Must be the exact column name.
405
-     * @param mixed  $field_value The value to set.
406
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
407
-     * @throws InvalidArgumentException
408
-     * @throws InvalidInterfaceException
409
-     * @throws InvalidDataTypeException
410
-     * @throws EE_Error
411
-     * @throws ReflectionException
412
-     */
413
-    public function set_field_or_extra_meta($field_name, $field_value)
414
-    {
415
-        if ($this->get_model()->has_field($field_name)) {
416
-            $this->set($field_name, $field_value);
417
-            return true;
418
-        }
419
-        //ensure this object is saved first so that extra meta can be properly related.
420
-        $this->save();
421
-        return $this->update_extra_meta($field_name, $field_value);
422
-    }
423
-
424
-
425
-    /**
426
-     * This retrieves the value of the db column set on this class or if that's not present
427
-     * it will attempt to retrieve from extra_meta if found.
428
-     * Example Usage:
429
-     * Via EE_Message child class:
430
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
431
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
432
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
433
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
434
-     * value for those extra fields dynamically via the EE_message object.
435
-     *
436
-     * @param  string $field_name expecting the fully qualified field name.
437
-     * @return mixed|null  value for the field if found.  null if not found.
438
-     * @throws ReflectionException
439
-     * @throws InvalidArgumentException
440
-     * @throws InvalidInterfaceException
441
-     * @throws InvalidDataTypeException
442
-     * @throws EE_Error
443
-     */
444
-    public function get_field_or_extra_meta($field_name)
445
-    {
446
-        if ($this->get_model()->has_field($field_name)) {
447
-            $column_value = $this->get($field_name);
448
-        } else {
449
-            //This isn't a column in the main table, let's see if it is in the extra meta.
450
-            $column_value = $this->get_extra_meta($field_name, true, null);
451
-        }
452
-        return $column_value;
453
-    }
454
-
455
-
456
-    /**
457
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
458
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
459
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
460
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
461
-     *
462
-     * @access public
463
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
464
-     * @return void
465
-     * @throws InvalidArgumentException
466
-     * @throws InvalidInterfaceException
467
-     * @throws InvalidDataTypeException
468
-     * @throws EE_Error
469
-     * @throws ReflectionException
470
-     */
471
-    public function set_timezone($timezone = '')
472
-    {
473
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
474
-        //make sure we clear all cached properties because they won't be relevant now
475
-        $this->_clear_cached_properties();
476
-        //make sure we update field settings and the date for all EE_Datetime_Fields
477
-        $model_fields = $this->get_model()->field_settings(false);
478
-        foreach ($model_fields as $field_name => $field_obj) {
479
-            if ($field_obj instanceof EE_Datetime_Field) {
480
-                $field_obj->set_timezone($this->_timezone);
481
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
482
-                    $this->_fields[ $field_name ]->setTimezone(new DateTimeZone($this->_timezone));
483
-                    // workaround for php datetime bug
484
-                    // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
485
-                    $this->_fields[$field_name]->getTimestamp();
486
-                }
487
-            }
488
-        }
489
-    }
490
-
491
-
492
-    /**
493
-     * This just returns whatever is set for the current timezone.
494
-     *
495
-     * @access public
496
-     * @return string timezone string
497
-     */
498
-    public function get_timezone()
499
-    {
500
-        return $this->_timezone;
501
-    }
502
-
503
-
504
-    /**
505
-     * This sets the internal date format to what is sent in to be used as the new default for the class
506
-     * internally instead of wp set date format options
507
-     *
508
-     * @since 4.6
509
-     * @param string $format should be a format recognizable by PHP date() functions.
510
-     */
511
-    public function set_date_format($format)
512
-    {
513
-        $this->_dt_frmt = $format;
514
-        //clear cached_properties because they won't be relevant now.
515
-        $this->_clear_cached_properties();
516
-    }
517
-
518
-
519
-    /**
520
-     * This sets the internal time format string to what is sent in to be used as the new default for the
521
-     * class internally instead of wp set time format options.
522
-     *
523
-     * @since 4.6
524
-     * @param string $format should be a format recognizable by PHP date() functions.
525
-     */
526
-    public function set_time_format($format)
527
-    {
528
-        $this->_tm_frmt = $format;
529
-        //clear cached_properties because they won't be relevant now.
530
-        $this->_clear_cached_properties();
531
-    }
532
-
533
-
534
-    /**
535
-     * This returns the current internal set format for the date and time formats.
536
-     *
537
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
538
-     *                             where the first value is the date format and the second value is the time format.
539
-     * @return mixed string|array
540
-     */
541
-    public function get_format($full = true)
542
-    {
543
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
544
-    }
545
-
546
-
547
-    /**
548
-     * cache
549
-     * stores the passed model object on the current model object.
550
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
551
-     *
552
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
553
-     *                                       'Registration' associated with this model object
554
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
555
-     *                                       that could be a payment or a registration)
556
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
557
-     *                                       items which will be stored in an array on this object
558
-     * @throws ReflectionException
559
-     * @throws InvalidArgumentException
560
-     * @throws InvalidInterfaceException
561
-     * @throws InvalidDataTypeException
562
-     * @throws EE_Error
563
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
564
-     *                                       related thing, no array)
565
-     */
566
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
567
-    {
568
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
569
-        if (! $object_to_cache instanceof EE_Base_Class) {
570
-            return false;
571
-        }
572
-        // also get "how" the object is related, or throw an error
573
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
574
-            throw new EE_Error(
575
-                sprintf(
576
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
577
-                    $relationName,
578
-                    get_class($this)
579
-                )
580
-            );
581
-        }
582
-        // how many things are related ?
583
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
584
-            // if it's a "belongs to" relationship, then there's only one related model object
585
-            // eg, if this is a registration, there's only 1 attendee for it
586
-            // so for these model objects just set it to be cached
587
-            $this->_model_relations[ $relationName ] = $object_to_cache;
588
-            $return                                  = true;
589
-        } else {
590
-            // otherwise, this is the "many" side of a one to many relationship,
591
-            // so we'll add the object to the array of related objects for that type.
592
-            // eg: if this is an event, there are many registrations for that event,
593
-            // so we cache the registrations in an array
594
-            if (! is_array($this->_model_relations[ $relationName ])) {
595
-                // if for some reason, the cached item is a model object,
596
-                // then stick that in the array, otherwise start with an empty array
597
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
598
-                                                           instanceof
599
-                                                           EE_Base_Class
600
-                    ? array($this->_model_relations[ $relationName ]) : array();
601
-            }
602
-            // first check for a cache_id which is normally empty
603
-            if (! empty($cache_id)) {
604
-                // if the cache_id exists, then it means we are purposely trying to cache this
605
-                // with a known key that can then be used to retrieve the object later on
606
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
607
-                $return                                               = $cache_id;
608
-            } elseif ($object_to_cache->ID()) {
609
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
610
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
611
-                $return                                                            = $object_to_cache->ID();
612
-            } else {
613
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
614
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
615
-                // move the internal pointer to the end of the array
616
-                end($this->_model_relations[ $relationName ]);
617
-                // and grab the key so that we can return it
618
-                $return = key($this->_model_relations[ $relationName ]);
619
-            }
620
-        }
621
-        return $return;
622
-    }
623
-
624
-
625
-    /**
626
-     * For adding an item to the cached_properties property.
627
-     *
628
-     * @access protected
629
-     * @param string      $fieldname the property item the corresponding value is for.
630
-     * @param mixed       $value     The value we are caching.
631
-     * @param string|null $cache_type
632
-     * @return void
633
-     * @throws ReflectionException
634
-     * @throws InvalidArgumentException
635
-     * @throws InvalidInterfaceException
636
-     * @throws InvalidDataTypeException
637
-     * @throws EE_Error
638
-     */
639
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
640
-    {
641
-        //first make sure this property exists
642
-        $this->get_model()->field_settings_for($fieldname);
643
-        $cache_type                                            = empty($cache_type) ? 'standard' : $cache_type;
644
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
645
-    }
646
-
647
-
648
-    /**
649
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
650
-     * This also SETS the cache if we return the actual property!
651
-     *
652
-     * @param string $fieldname        the name of the property we're trying to retrieve
653
-     * @param bool   $pretty
654
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
655
-     *                                 (in cases where the same property may be used for different outputs
656
-     *                                 - i.e. datetime, money etc.)
657
-     *                                 It can also accept certain pre-defined "schema" strings
658
-     *                                 to define how to output the property.
659
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
660
-     * @return mixed                   whatever the value for the property is we're retrieving
661
-     * @throws ReflectionException
662
-     * @throws InvalidArgumentException
663
-     * @throws InvalidInterfaceException
664
-     * @throws InvalidDataTypeException
665
-     * @throws EE_Error
666
-     */
667
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
668
-    {
669
-        //verify the field exists
670
-        $model = $this->get_model();
671
-        $model->field_settings_for($fieldname);
672
-        $cache_type = $pretty ? 'pretty' : 'standard';
673
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
674
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
675
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
676
-        }
677
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
678
-        $this->_set_cached_property($fieldname, $value, $cache_type);
679
-        return $value;
680
-    }
681
-
682
-
683
-    /**
684
-     * If the cache didn't fetch the needed item, this fetches it.
685
-     *
686
-     * @param string $fieldname
687
-     * @param bool   $pretty
688
-     * @param string $extra_cache_ref
689
-     * @return mixed
690
-     * @throws InvalidArgumentException
691
-     * @throws InvalidInterfaceException
692
-     * @throws InvalidDataTypeException
693
-     * @throws EE_Error
694
-     * @throws ReflectionException
695
-     */
696
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
697
-    {
698
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
699
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
700
-        if ($field_obj instanceof EE_Datetime_Field) {
701
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
702
-        }
703
-        if (! isset($this->_fields[ $fieldname ])) {
704
-            $this->_fields[ $fieldname ] = null;
705
-        }
706
-        $value = $pretty
707
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
708
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
709
-        return $value;
710
-    }
711
-
712
-
713
-    /**
714
-     * set timezone, formats, and output for EE_Datetime_Field objects
715
-     *
716
-     * @param \EE_Datetime_Field $datetime_field
717
-     * @param bool               $pretty
718
-     * @param null               $date_or_time
719
-     * @return void
720
-     * @throws InvalidArgumentException
721
-     * @throws InvalidInterfaceException
722
-     * @throws InvalidDataTypeException
723
-     * @throws EE_Error
724
-     */
725
-    protected function _prepare_datetime_field(
726
-        EE_Datetime_Field $datetime_field,
727
-        $pretty = false,
728
-        $date_or_time = null
729
-    ) {
730
-        $datetime_field->set_timezone($this->_timezone);
731
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
732
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
733
-        //set the output returned
734
-        switch ($date_or_time) {
735
-            case 'D' :
736
-                $datetime_field->set_date_time_output('date');
737
-                break;
738
-            case 'T' :
739
-                $datetime_field->set_date_time_output('time');
740
-                break;
741
-            default :
742
-                $datetime_field->set_date_time_output();
743
-        }
744
-    }
745
-
746
-
747
-    /**
748
-     * This just takes care of clearing out the cached_properties
749
-     *
750
-     * @return void
751
-     */
752
-    protected function _clear_cached_properties()
753
-    {
754
-        $this->_cached_properties = array();
755
-    }
756
-
757
-
758
-    /**
759
-     * This just clears out ONE property if it exists in the cache
760
-     *
761
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
762
-     * @return void
763
-     */
764
-    protected function _clear_cached_property($property_name)
765
-    {
766
-        if (isset($this->_cached_properties[ $property_name ])) {
767
-            unset($this->_cached_properties[ $property_name ]);
768
-        }
769
-    }
770
-
771
-
772
-    /**
773
-     * Ensures that this related thing is a model object.
774
-     *
775
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
776
-     * @param string $model_name   name of the related thing, eg 'Attendee',
777
-     * @return EE_Base_Class
778
-     * @throws ReflectionException
779
-     * @throws InvalidArgumentException
780
-     * @throws InvalidInterfaceException
781
-     * @throws InvalidDataTypeException
782
-     * @throws EE_Error
783
-     */
784
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
785
-    {
786
-        $other_model_instance = self::_get_model_instance_with_name(
787
-            self::_get_model_classname($model_name),
788
-            $this->_timezone
789
-        );
790
-        return $other_model_instance->ensure_is_obj($object_or_id);
791
-    }
792
-
793
-
794
-    /**
795
-     * Forgets the cached model of the given relation Name. So the next time we request it,
796
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
797
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
798
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
799
-     *
800
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
801
-     *                                                     Eg 'Registration'
802
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
803
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
804
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
805
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
806
-     *                                                     this is HasMany or HABTM.
807
-     * @throws ReflectionException
808
-     * @throws InvalidArgumentException
809
-     * @throws InvalidInterfaceException
810
-     * @throws InvalidDataTypeException
811
-     * @throws EE_Error
812
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
813
-     *                                                     relation from all
814
-     */
815
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
816
-    {
817
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
818
-        $index_in_cache        = '';
819
-        if (! $relationship_to_model) {
820
-            throw new EE_Error(
821
-                sprintf(
822
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
823
-                    $relationName,
824
-                    get_class($this)
825
-                )
826
-            );
827
-        }
828
-        if ($clear_all) {
829
-            $obj_removed                             = true;
830
-            $this->_model_relations[ $relationName ] = null;
831
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
832
-            $obj_removed                             = $this->_model_relations[ $relationName ];
833
-            $this->_model_relations[ $relationName ] = null;
834
-        } else {
835
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
836
-                && $object_to_remove_or_index_into_array->ID()
837
-            ) {
838
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
839
-                if (is_array($this->_model_relations[ $relationName ])
840
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
841
-                ) {
842
-                    $index_found_at = null;
843
-                    //find this object in the array even though it has a different key
844
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
845
-                        /** @noinspection TypeUnsafeComparisonInspection */
846
-                        if (
847
-                            $obj instanceof EE_Base_Class
848
-                            && (
849
-                                $obj == $object_to_remove_or_index_into_array
850
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
851
-                            )
852
-                        ) {
853
-                            $index_found_at = $index;
854
-                            break;
855
-                        }
856
-                    }
857
-                    if ($index_found_at) {
858
-                        $index_in_cache = $index_found_at;
859
-                    } else {
860
-                        //it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
861
-                        //if it wasn't in it to begin with. So we're done
862
-                        return $object_to_remove_or_index_into_array;
863
-                    }
864
-                }
865
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
866
-                //so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
867
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
868
-                    /** @noinspection TypeUnsafeComparisonInspection */
869
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
870
-                        $index_in_cache = $index;
871
-                    }
872
-                }
873
-            } else {
874
-                $index_in_cache = $object_to_remove_or_index_into_array;
875
-            }
876
-            //supposedly we've found it. But it could just be that the client code
877
-            //provided a bad index/object
878
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
879
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
880
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
881
-            } else {
882
-                //that thing was never cached anyways.
883
-                $obj_removed = null;
884
-            }
885
-        }
886
-        return $obj_removed;
887
-    }
888
-
889
-
890
-    /**
891
-     * update_cache_after_object_save
892
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
893
-     * obtained after being saved to the db
894
-     *
895
-     * @param string        $relationName       - the type of object that is cached
896
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
897
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
898
-     * @return boolean TRUE on success, FALSE on fail
899
-     * @throws ReflectionException
900
-     * @throws InvalidArgumentException
901
-     * @throws InvalidInterfaceException
902
-     * @throws InvalidDataTypeException
903
-     * @throws EE_Error
904
-     */
905
-    public function update_cache_after_object_save(
906
-        $relationName,
907
-        EE_Base_Class $newly_saved_object,
908
-        $current_cache_id = ''
909
-    ) {
910
-        // verify that incoming object is of the correct type
911
-        $obj_class = 'EE_' . $relationName;
912
-        if ($newly_saved_object instanceof $obj_class) {
913
-            /* @type EE_Base_Class $newly_saved_object */
914
-            // now get the type of relation
915
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
916
-            // if this is a 1:1 relationship
917
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
918
-                // then just replace the cached object with the newly saved object
919
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
920
-                return true;
921
-                // or if it's some kind of sordid feral polyamorous relationship...
922
-            }
923
-            if (is_array($this->_model_relations[ $relationName ])
924
-                      && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
925
-            ) {
926
-                // then remove the current cached item
927
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
928
-                // and cache the newly saved object using it's new ID
929
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
930
-                return true;
931
-            }
932
-        }
933
-        return false;
934
-    }
935
-
936
-
937
-    /**
938
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
939
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
940
-     *
941
-     * @param string $relationName
942
-     * @return EE_Base_Class
943
-     */
944
-    public function get_one_from_cache($relationName)
945
-    {
946
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
947
-            ? $this->_model_relations[ $relationName ]
948
-            : null;
949
-        if (is_array($cached_array_or_object)) {
950
-            return array_shift($cached_array_or_object);
951
-        }
952
-        return $cached_array_or_object;
953
-    }
954
-
955
-
956
-    /**
957
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
958
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
959
-     *
960
-     * @param string $relationName
961
-     * @throws ReflectionException
962
-     * @throws InvalidArgumentException
963
-     * @throws InvalidInterfaceException
964
-     * @throws InvalidDataTypeException
965
-     * @throws EE_Error
966
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
967
-     */
968
-    public function get_all_from_cache($relationName)
969
-    {
970
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
971
-        // if the result is not an array, but exists, make it an array
972
-        $objects = is_array($objects) ? $objects : array($objects);
973
-        //bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
974
-        //basically, if this model object was stored in the session, and these cached model objects
975
-        //already have IDs, let's make sure they're in their model's entity mapper
976
-        //otherwise we will have duplicates next time we call
977
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
978
-        $model = EE_Registry::instance()->load_model($relationName);
979
-        foreach ($objects as $model_object) {
980
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
981
-                //ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
982
-                if ($model_object->ID()) {
983
-                    $model->add_to_entity_map($model_object);
984
-                }
985
-            } else {
986
-                throw new EE_Error(
987
-                    sprintf(
988
-                        esc_html__(
989
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
990
-                            'event_espresso'
991
-                        ),
992
-                        $relationName,
993
-                        gettype($model_object)
994
-                    )
995
-                );
996
-            }
997
-        }
998
-        return $objects;
999
-    }
1000
-
1001
-
1002
-    /**
1003
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1004
-     * matching the given query conditions.
1005
-     *
1006
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1007
-     * @param int   $limit              How many objects to return.
1008
-     * @param array $query_params       Any additional conditions on the query.
1009
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1010
-     *                                  you can indicate just the columns you want returned
1011
-     * @return array|EE_Base_Class[]
1012
-     * @throws ReflectionException
1013
-     * @throws InvalidArgumentException
1014
-     * @throws InvalidInterfaceException
1015
-     * @throws InvalidDataTypeException
1016
-     * @throws EE_Error
1017
-     */
1018
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1019
-    {
1020
-        $model         = $this->get_model();
1021
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1022
-            ? $model->get_primary_key_field()->get_name()
1023
-            : $field_to_order_by;
1024
-        $current_value = ! empty($field) ? $this->get($field) : null;
1025
-        if (empty($field) || empty($current_value)) {
1026
-            return array();
1027
-        }
1028
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1029
-    }
1030
-
1031
-
1032
-    /**
1033
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1034
-     * matching the given query conditions.
1035
-     *
1036
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1037
-     * @param int   $limit              How many objects to return.
1038
-     * @param array $query_params       Any additional conditions on the query.
1039
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1040
-     *                                  you can indicate just the columns you want returned
1041
-     * @return array|EE_Base_Class[]
1042
-     * @throws ReflectionException
1043
-     * @throws InvalidArgumentException
1044
-     * @throws InvalidInterfaceException
1045
-     * @throws InvalidDataTypeException
1046
-     * @throws EE_Error
1047
-     */
1048
-    public function previous_x(
1049
-        $field_to_order_by = null,
1050
-        $limit = 1,
1051
-        $query_params = array(),
1052
-        $columns_to_select = null
1053
-    ) {
1054
-        $model         = $this->get_model();
1055
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1056
-            ? $model->get_primary_key_field()->get_name()
1057
-            : $field_to_order_by;
1058
-        $current_value = ! empty($field) ? $this->get($field) : null;
1059
-        if (empty($field) || empty($current_value)) {
1060
-            return array();
1061
-        }
1062
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1063
-    }
1064
-
1065
-
1066
-    /**
1067
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1068
-     * matching the given query conditions.
1069
-     *
1070
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1071
-     * @param array $query_params       Any additional conditions on the query.
1072
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1073
-     *                                  you can indicate just the columns you want returned
1074
-     * @return array|EE_Base_Class
1075
-     * @throws ReflectionException
1076
-     * @throws InvalidArgumentException
1077
-     * @throws InvalidInterfaceException
1078
-     * @throws InvalidDataTypeException
1079
-     * @throws EE_Error
1080
-     */
1081
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1082
-    {
1083
-        $model         = $this->get_model();
1084
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1085
-            ? $model->get_primary_key_field()->get_name()
1086
-            : $field_to_order_by;
1087
-        $current_value = ! empty($field) ? $this->get($field) : null;
1088
-        if (empty($field) || empty($current_value)) {
1089
-            return array();
1090
-        }
1091
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1092
-    }
1093
-
1094
-
1095
-    /**
1096
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1097
-     * matching the given query conditions.
1098
-     *
1099
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1100
-     * @param array $query_params       Any additional conditions on the query.
1101
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1102
-     *                                  you can indicate just the column you want returned
1103
-     * @return array|EE_Base_Class
1104
-     * @throws ReflectionException
1105
-     * @throws InvalidArgumentException
1106
-     * @throws InvalidInterfaceException
1107
-     * @throws InvalidDataTypeException
1108
-     * @throws EE_Error
1109
-     */
1110
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1111
-    {
1112
-        $model         = $this->get_model();
1113
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1114
-            ? $model->get_primary_key_field()->get_name()
1115
-            : $field_to_order_by;
1116
-        $current_value = ! empty($field) ? $this->get($field) : null;
1117
-        if (empty($field) || empty($current_value)) {
1118
-            return array();
1119
-        }
1120
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1121
-    }
1122
-
1123
-
1124
-    /**
1125
-     * Overrides parent because parent expects old models.
1126
-     * This also doesn't do any validation, and won't work for serialized arrays
1127
-     *
1128
-     * @param string $field_name
1129
-     * @param mixed  $field_value_from_db
1130
-     * @throws ReflectionException
1131
-     * @throws InvalidArgumentException
1132
-     * @throws InvalidInterfaceException
1133
-     * @throws InvalidDataTypeException
1134
-     * @throws EE_Error
1135
-     */
1136
-    public function set_from_db($field_name, $field_value_from_db)
1137
-    {
1138
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1139
-        if ($field_obj instanceof EE_Model_Field_Base) {
1140
-            //you would think the DB has no NULLs for non-null label fields right? wrong!
1141
-            //eg, a CPT model object could have an entry in the posts table, but no
1142
-            //entry in the meta table. Meaning that all its columns in the meta table
1143
-            //are null! yikes! so when we find one like that, use defaults for its meta columns
1144
-            if ($field_value_from_db === null) {
1145
-                if ($field_obj->is_nullable()) {
1146
-                    //if the field allows nulls, then let it be null
1147
-                    $field_value = null;
1148
-                } else {
1149
-                    $field_value = $field_obj->get_default_value();
1150
-                }
1151
-            } else {
1152
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1153
-            }
1154
-            $this->_fields[ $field_name ] = $field_value;
1155
-            $this->_clear_cached_property($field_name);
1156
-        }
1157
-    }
1158
-
1159
-
1160
-    /**
1161
-     * verifies that the specified field is of the correct type
1162
-     *
1163
-     * @param string $field_name
1164
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1165
-     *                                (in cases where the same property may be used for different outputs
1166
-     *                                - i.e. datetime, money etc.)
1167
-     * @return mixed
1168
-     * @throws ReflectionException
1169
-     * @throws InvalidArgumentException
1170
-     * @throws InvalidInterfaceException
1171
-     * @throws InvalidDataTypeException
1172
-     * @throws EE_Error
1173
-     */
1174
-    public function get($field_name, $extra_cache_ref = null)
1175
-    {
1176
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1177
-    }
1178
-
1179
-
1180
-    /**
1181
-     * This method simply returns the RAW unprocessed value for the given property in this class
1182
-     *
1183
-     * @param  string $field_name A valid fieldname
1184
-     * @return mixed              Whatever the raw value stored on the property is.
1185
-     * @throws ReflectionException
1186
-     * @throws InvalidArgumentException
1187
-     * @throws InvalidInterfaceException
1188
-     * @throws InvalidDataTypeException
1189
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1190
-     */
1191
-    public function get_raw($field_name)
1192
-    {
1193
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1194
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1195
-            ? $this->_fields[ $field_name ]->format('U')
1196
-            : $this->_fields[ $field_name ];
1197
-    }
1198
-
1199
-
1200
-    /**
1201
-     * This is used to return the internal DateTime object used for a field that is a
1202
-     * EE_Datetime_Field.
1203
-     *
1204
-     * @param string $field_name               The field name retrieving the DateTime object.
1205
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1206
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1207
-     *                                         EE_Datetime_Field and but the field value is null, then
1208
-     *                                         just null is returned (because that indicates that likely
1209
-     *                                         this field is nullable).
1210
-     * @throws InvalidArgumentException
1211
-     * @throws InvalidDataTypeException
1212
-     * @throws InvalidInterfaceException
1213
-     * @throws ReflectionException
1214
-     */
1215
-    public function get_DateTime_object($field_name)
1216
-    {
1217
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1218
-        if (! $field_settings instanceof EE_Datetime_Field) {
1219
-            EE_Error::add_error(
1220
-                sprintf(
1221
-                    esc_html__(
1222
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1223
-                        'event_espresso'
1224
-                    ),
1225
-                    $field_name
1226
-                ),
1227
-                __FILE__,
1228
-                __FUNCTION__,
1229
-                __LINE__
1230
-            );
1231
-            return false;
1232
-        }
1233
-        return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1234
-            ? clone $this->_fields[$field_name]
1235
-            : null;
1236
-    }
1237
-
1238
-
1239
-    /**
1240
-     * To be used in template to immediately echo out the value, and format it for output.
1241
-     * Eg, should call stripslashes and whatnot before echoing
1242
-     *
1243
-     * @param string $field_name      the name of the field as it appears in the DB
1244
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1245
-     *                                (in cases where the same property may be used for different outputs
1246
-     *                                - i.e. datetime, money etc.)
1247
-     * @return void
1248
-     * @throws ReflectionException
1249
-     * @throws InvalidArgumentException
1250
-     * @throws InvalidInterfaceException
1251
-     * @throws InvalidDataTypeException
1252
-     * @throws EE_Error
1253
-     */
1254
-    public function e($field_name, $extra_cache_ref = null)
1255
-    {
1256
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1257
-    }
1258
-
1259
-
1260
-    /**
1261
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1262
-     * can be easily used as the value of form input.
1263
-     *
1264
-     * @param string $field_name
1265
-     * @return void
1266
-     * @throws ReflectionException
1267
-     * @throws InvalidArgumentException
1268
-     * @throws InvalidInterfaceException
1269
-     * @throws InvalidDataTypeException
1270
-     * @throws EE_Error
1271
-     */
1272
-    public function f($field_name)
1273
-    {
1274
-        $this->e($field_name, 'form_input');
1275
-    }
1276
-
1277
-
1278
-    /**
1279
-     * Same as `f()` but just returns the value instead of echoing it
1280
-     *
1281
-     * @param string $field_name
1282
-     * @return string
1283
-     * @throws ReflectionException
1284
-     * @throws InvalidArgumentException
1285
-     * @throws InvalidInterfaceException
1286
-     * @throws InvalidDataTypeException
1287
-     * @throws EE_Error
1288
-     */
1289
-    public function get_f($field_name)
1290
-    {
1291
-        return (string) $this->get_pretty($field_name, 'form_input');
1292
-    }
1293
-
1294
-
1295
-    /**
1296
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1297
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1298
-     * to see what options are available.
1299
-     *
1300
-     * @param string $field_name
1301
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1302
-     *                                (in cases where the same property may be used for different outputs
1303
-     *                                - i.e. datetime, money etc.)
1304
-     * @return mixed
1305
-     * @throws ReflectionException
1306
-     * @throws InvalidArgumentException
1307
-     * @throws InvalidInterfaceException
1308
-     * @throws InvalidDataTypeException
1309
-     * @throws EE_Error
1310
-     */
1311
-    public function get_pretty($field_name, $extra_cache_ref = null)
1312
-    {
1313
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1314
-    }
1315
-
1316
-
1317
-    /**
1318
-     * This simply returns the datetime for the given field name
1319
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1320
-     * (and the equivalent e_date, e_time, e_datetime).
1321
-     *
1322
-     * @access   protected
1323
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1324
-     * @param string   $dt_frmt      valid datetime format used for date
1325
-     *                               (if '' then we just use the default on the field,
1326
-     *                               if NULL we use the last-used format)
1327
-     * @param string   $tm_frmt      Same as above except this is for time format
1328
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1329
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1330
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1331
-     *                               if field is not a valid dtt field, or void if echoing
1332
-     * @throws ReflectionException
1333
-     * @throws InvalidArgumentException
1334
-     * @throws InvalidInterfaceException
1335
-     * @throws InvalidDataTypeException
1336
-     * @throws EE_Error
1337
-     */
1338
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1339
-    {
1340
-        // clear cached property
1341
-        $this->_clear_cached_property($field_name);
1342
-        //reset format properties because they are used in get()
1343
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1344
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1345
-        if ($echo) {
1346
-            $this->e($field_name, $date_or_time);
1347
-            return '';
1348
-        }
1349
-        return $this->get($field_name, $date_or_time);
1350
-    }
1351
-
1352
-
1353
-    /**
1354
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1355
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1356
-     * other echoes the pretty value for dtt)
1357
-     *
1358
-     * @param  string $field_name name of model object datetime field holding the value
1359
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1360
-     * @return string            datetime value formatted
1361
-     * @throws ReflectionException
1362
-     * @throws InvalidArgumentException
1363
-     * @throws InvalidInterfaceException
1364
-     * @throws InvalidDataTypeException
1365
-     * @throws EE_Error
1366
-     */
1367
-    public function get_date($field_name, $format = '')
1368
-    {
1369
-        return $this->_get_datetime($field_name, $format, null, 'D');
1370
-    }
1371
-
1372
-
1373
-    /**
1374
-     * @param        $field_name
1375
-     * @param string $format
1376
-     * @throws ReflectionException
1377
-     * @throws InvalidArgumentException
1378
-     * @throws InvalidInterfaceException
1379
-     * @throws InvalidDataTypeException
1380
-     * @throws EE_Error
1381
-     */
1382
-    public function e_date($field_name, $format = '')
1383
-    {
1384
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1385
-    }
1386
-
1387
-
1388
-    /**
1389
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1390
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1391
-     * other echoes the pretty value for dtt)
1392
-     *
1393
-     * @param  string $field_name name of model object datetime field holding the value
1394
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1395
-     * @return string             datetime value formatted
1396
-     * @throws ReflectionException
1397
-     * @throws InvalidArgumentException
1398
-     * @throws InvalidInterfaceException
1399
-     * @throws InvalidDataTypeException
1400
-     * @throws EE_Error
1401
-     */
1402
-    public function get_time($field_name, $format = '')
1403
-    {
1404
-        return $this->_get_datetime($field_name, null, $format, 'T');
1405
-    }
1406
-
1407
-
1408
-    /**
1409
-     * @param        $field_name
1410
-     * @param string $format
1411
-     * @throws ReflectionException
1412
-     * @throws InvalidArgumentException
1413
-     * @throws InvalidInterfaceException
1414
-     * @throws InvalidDataTypeException
1415
-     * @throws EE_Error
1416
-     */
1417
-    public function e_time($field_name, $format = '')
1418
-    {
1419
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1420
-    }
1421
-
1422
-
1423
-    /**
1424
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1425
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1426
-     * other echoes the pretty value for dtt)
1427
-     *
1428
-     * @param  string $field_name name of model object datetime field holding the value
1429
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1430
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1431
-     * @return string             datetime value formatted
1432
-     * @throws ReflectionException
1433
-     * @throws InvalidArgumentException
1434
-     * @throws InvalidInterfaceException
1435
-     * @throws InvalidDataTypeException
1436
-     * @throws EE_Error
1437
-     */
1438
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1439
-    {
1440
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1441
-    }
1442
-
1443
-
1444
-    /**
1445
-     * @param string $field_name
1446
-     * @param string $dt_frmt
1447
-     * @param string $tm_frmt
1448
-     * @throws ReflectionException
1449
-     * @throws InvalidArgumentException
1450
-     * @throws InvalidInterfaceException
1451
-     * @throws InvalidDataTypeException
1452
-     * @throws EE_Error
1453
-     */
1454
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1455
-    {
1456
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1457
-    }
1458
-
1459
-
1460
-    /**
1461
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1462
-     *
1463
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1464
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1465
-     *                           on the object will be used.
1466
-     * @return string Date and time string in set locale or false if no field exists for the given
1467
-     * @throws ReflectionException
1468
-     * @throws InvalidArgumentException
1469
-     * @throws InvalidInterfaceException
1470
-     * @throws InvalidDataTypeException
1471
-     * @throws EE_Error
1472
-     *                           field name.
1473
-     */
1474
-    public function get_i18n_datetime($field_name, $format = '')
1475
-    {
1476
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1477
-        return date_i18n(
1478
-            $format,
1479
-            EEH_DTT_Helper::get_timestamp_with_offset(
1480
-                $this->get_raw($field_name),
1481
-                $this->_timezone
1482
-            )
1483
-        );
1484
-    }
1485
-
1486
-
1487
-    /**
1488
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1489
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1490
-     * thrown.
1491
-     *
1492
-     * @param  string $field_name The field name being checked
1493
-     * @throws ReflectionException
1494
-     * @throws InvalidArgumentException
1495
-     * @throws InvalidInterfaceException
1496
-     * @throws InvalidDataTypeException
1497
-     * @throws EE_Error
1498
-     * @return EE_Datetime_Field
1499
-     */
1500
-    protected function _get_dtt_field_settings($field_name)
1501
-    {
1502
-        $field = $this->get_model()->field_settings_for($field_name);
1503
-        //check if field is dtt
1504
-        if ($field instanceof EE_Datetime_Field) {
1505
-            return $field;
1506
-        }
1507
-        throw new EE_Error(
1508
-            sprintf(
1509
-                esc_html__(
1510
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1511
-                    'event_espresso'
1512
-                ),
1513
-                $field_name,
1514
-                self::_get_model_classname(get_class($this))
1515
-            )
1516
-        );
1517
-    }
1518
-
1519
-
1520
-
1521
-
1522
-    /**
1523
-     * NOTE ABOUT BELOW:
1524
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1525
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1526
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1527
-     * method and make sure you send the entire datetime value for setting.
1528
-     */
1529
-    /**
1530
-     * sets the time on a datetime property
1531
-     *
1532
-     * @access protected
1533
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1534
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1535
-     * @throws ReflectionException
1536
-     * @throws InvalidArgumentException
1537
-     * @throws InvalidInterfaceException
1538
-     * @throws InvalidDataTypeException
1539
-     * @throws EE_Error
1540
-     */
1541
-    protected function _set_time_for($time, $fieldname)
1542
-    {
1543
-        $this->_set_date_time('T', $time, $fieldname);
1544
-    }
1545
-
1546
-
1547
-    /**
1548
-     * sets the date on a datetime property
1549
-     *
1550
-     * @access protected
1551
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1552
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1553
-     * @throws ReflectionException
1554
-     * @throws InvalidArgumentException
1555
-     * @throws InvalidInterfaceException
1556
-     * @throws InvalidDataTypeException
1557
-     * @throws EE_Error
1558
-     */
1559
-    protected function _set_date_for($date, $fieldname)
1560
-    {
1561
-        $this->_set_date_time('D', $date, $fieldname);
1562
-    }
1563
-
1564
-
1565
-    /**
1566
-     * This takes care of setting a date or time independently on a given model object property. This method also
1567
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1568
-     *
1569
-     * @access protected
1570
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1571
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1572
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1573
-     *                                        EE_Datetime_Field property)
1574
-     * @throws ReflectionException
1575
-     * @throws InvalidArgumentException
1576
-     * @throws InvalidInterfaceException
1577
-     * @throws InvalidDataTypeException
1578
-     * @throws EE_Error
1579
-     */
1580
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1581
-    {
1582
-        $field = $this->_get_dtt_field_settings($fieldname);
1583
-        $field->set_timezone($this->_timezone);
1584
-        $field->set_date_format($this->_dt_frmt);
1585
-        $field->set_time_format($this->_tm_frmt);
1586
-        switch ($what) {
1587
-            case 'T' :
1588
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1589
-                    $datetime_value,
1590
-                    $this->_fields[ $fieldname ]
1591
-                );
1592
-                break;
1593
-            case 'D' :
1594
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1595
-                    $datetime_value,
1596
-                    $this->_fields[ $fieldname ]
1597
-                );
1598
-                break;
1599
-            case 'B' :
1600
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1601
-                break;
1602
-        }
1603
-        $this->_clear_cached_property($fieldname);
1604
-    }
1605
-
1606
-
1607
-    /**
1608
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1609
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1610
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1611
-     * that could lead to some unexpected results!
1612
-     *
1613
-     * @access public
1614
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1615
-     *                                         value being returned.
1616
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1617
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1618
-     * @param string $prepend                  You can include something to prepend on the timestamp
1619
-     * @param string $append                   You can include something to append on the timestamp
1620
-     * @throws ReflectionException
1621
-     * @throws InvalidArgumentException
1622
-     * @throws InvalidInterfaceException
1623
-     * @throws InvalidDataTypeException
1624
-     * @throws EE_Error
1625
-     * @return string timestamp
1626
-     */
1627
-    public function display_in_my_timezone(
1628
-        $field_name,
1629
-        $callback = 'get_datetime',
1630
-        $args = null,
1631
-        $prepend = '',
1632
-        $append = ''
1633
-    ) {
1634
-        $timezone = EEH_DTT_Helper::get_timezone();
1635
-        if ($timezone === $this->_timezone) {
1636
-            return '';
1637
-        }
1638
-        $original_timezone = $this->_timezone;
1639
-        $this->set_timezone($timezone);
1640
-        $fn   = (array) $field_name;
1641
-        $args = array_merge($fn, (array) $args);
1642
-        if (! method_exists($this, $callback)) {
1643
-            throw new EE_Error(
1644
-                sprintf(
1645
-                    esc_html__(
1646
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1647
-                        'event_espresso'
1648
-                    ),
1649
-                    $callback
1650
-                )
1651
-            );
1652
-        }
1653
-        $args   = (array) $args;
1654
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1655
-        $this->set_timezone($original_timezone);
1656
-        return $return;
1657
-    }
1658
-
1659
-
1660
-    /**
1661
-     * Deletes this model object.
1662
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1663
-     * override
1664
-     * `EE_Base_Class::_delete` NOT this class.
1665
-     *
1666
-     * @return boolean | int
1667
-     * @throws ReflectionException
1668
-     * @throws InvalidArgumentException
1669
-     * @throws InvalidInterfaceException
1670
-     * @throws InvalidDataTypeException
1671
-     * @throws EE_Error
1672
-     */
1673
-    public function delete()
1674
-    {
1675
-        /**
1676
-         * Called just before the `EE_Base_Class::_delete` method call.
1677
-         * Note:
1678
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1679
-         * should be aware that `_delete` may not always result in a permanent delete.
1680
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1681
-         * soft deletes (trash) the object and does not permanently delete it.
1682
-         *
1683
-         * @param EE_Base_Class $model_object about to be 'deleted'
1684
-         */
1685
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1686
-        $result = $this->_delete();
1687
-        /**
1688
-         * Called just after the `EE_Base_Class::_delete` method call.
1689
-         * Note:
1690
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1691
-         * should be aware that `_delete` may not always result in a permanent delete.
1692
-         * For example `EE_Soft_Base_Class::_delete`
1693
-         * soft deletes (trash) the object and does not permanently delete it.
1694
-         *
1695
-         * @param EE_Base_Class $model_object that was just 'deleted'
1696
-         * @param boolean       $result
1697
-         */
1698
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1699
-        return $result;
1700
-    }
1701
-
1702
-
1703
-    /**
1704
-     * Calls the specific delete method for the instantiated class.
1705
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1706
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1707
-     * `EE_Base_Class::delete`
1708
-     *
1709
-     * @return bool|int
1710
-     * @throws ReflectionException
1711
-     * @throws InvalidArgumentException
1712
-     * @throws InvalidInterfaceException
1713
-     * @throws InvalidDataTypeException
1714
-     * @throws EE_Error
1715
-     */
1716
-    protected function _delete()
1717
-    {
1718
-        return $this->delete_permanently();
1719
-    }
1720
-
1721
-
1722
-    /**
1723
-     * Deletes this model object permanently from db
1724
-     * (but keep in mind related models may block the delete and return an error)
1725
-     *
1726
-     * @return bool | int
1727
-     * @throws ReflectionException
1728
-     * @throws InvalidArgumentException
1729
-     * @throws InvalidInterfaceException
1730
-     * @throws InvalidDataTypeException
1731
-     * @throws EE_Error
1732
-     */
1733
-    public function delete_permanently()
1734
-    {
1735
-        /**
1736
-         * Called just before HARD deleting a model object
1737
-         *
1738
-         * @param EE_Base_Class $model_object about to be 'deleted'
1739
-         */
1740
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1741
-        $model  = $this->get_model();
1742
-        $result = $model->delete_permanently_by_ID($this->ID());
1743
-        $this->refresh_cache_of_related_objects();
1744
-        /**
1745
-         * Called just after HARD deleting a model object
1746
-         *
1747
-         * @param EE_Base_Class $model_object that was just 'deleted'
1748
-         * @param boolean       $result
1749
-         */
1750
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1751
-        return $result;
1752
-    }
1753
-
1754
-
1755
-    /**
1756
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1757
-     * related model objects
1758
-     *
1759
-     * @throws ReflectionException
1760
-     * @throws InvalidArgumentException
1761
-     * @throws InvalidInterfaceException
1762
-     * @throws InvalidDataTypeException
1763
-     * @throws EE_Error
1764
-     */
1765
-    public function refresh_cache_of_related_objects()
1766
-    {
1767
-        $model = $this->get_model();
1768
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1769
-            if (! empty($this->_model_relations[ $relation_name ])) {
1770
-                $related_objects = $this->_model_relations[ $relation_name ];
1771
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1772
-                    //this relation only stores a single model object, not an array
1773
-                    //but let's make it consistent
1774
-                    $related_objects = array($related_objects);
1775
-                }
1776
-                foreach ($related_objects as $related_object) {
1777
-                    //only refresh their cache if they're in memory
1778
-                    if ($related_object instanceof EE_Base_Class) {
1779
-                        $related_object->clear_cache(
1780
-                            $model->get_this_model_name(),
1781
-                            $this
1782
-                        );
1783
-                    }
1784
-                }
1785
-            }
1786
-        }
1787
-    }
1788
-
1789
-
1790
-    /**
1791
-     *        Saves this object to the database. An array may be supplied to set some values on this
1792
-     * object just before saving.
1793
-     *
1794
-     * @access public
1795
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1796
-     *                                 if provided during the save() method (often client code will change the fields'
1797
-     *                                 values before calling save)
1798
-     * @throws InvalidArgumentException
1799
-     * @throws InvalidInterfaceException
1800
-     * @throws InvalidDataTypeException
1801
-     * @throws EE_Error
1802
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1803
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1804
-     * @throws ReflectionException
1805
-     * @throws ReflectionException
1806
-     * @throws ReflectionException
1807
-     */
1808
-    public function save($set_cols_n_values = array())
1809
-    {
1810
-        $model = $this->get_model();
1811
-        /**
1812
-         * Filters the fields we're about to save on the model object
1813
-         *
1814
-         * @param array         $set_cols_n_values
1815
-         * @param EE_Base_Class $model_object
1816
-         */
1817
-        $set_cols_n_values = (array) apply_filters(
1818
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1819
-            $set_cols_n_values,
1820
-            $this
1821
-        );
1822
-        //set attributes as provided in $set_cols_n_values
1823
-        foreach ($set_cols_n_values as $column => $value) {
1824
-            $this->set($column, $value);
1825
-        }
1826
-        // no changes ? then don't do anything
1827
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1828
-            return 0;
1829
-        }
1830
-        /**
1831
-         * Saving a model object.
1832
-         * Before we perform a save, this action is fired.
1833
-         *
1834
-         * @param EE_Base_Class $model_object the model object about to be saved.
1835
-         */
1836
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1837
-        if (! $this->allow_persist()) {
1838
-            return 0;
1839
-        }
1840
-        // now get current attribute values
1841
-        $save_cols_n_values = $this->_fields;
1842
-        // if the object already has an ID, update it. Otherwise, insert it
1843
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1844
-        // They have been
1845
-        $old_assumption_concerning_value_preparation = $model
1846
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1847
-        $model->assume_values_already_prepared_by_model_object(true);
1848
-        //does this model have an autoincrement PK?
1849
-        if ($model->has_primary_key_field()) {
1850
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1851
-                //ok check if it's set, if so: update; if not, insert
1852
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1853
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1854
-                } else {
1855
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1856
-                    $results = $model->insert($save_cols_n_values);
1857
-                    if ($results) {
1858
-                        //if successful, set the primary key
1859
-                        //but don't use the normal SET method, because it will check if
1860
-                        //an item with the same ID exists in the mapper & db, then
1861
-                        //will find it in the db (because we just added it) and THAT object
1862
-                        //will get added to the mapper before we can add this one!
1863
-                        //but if we just avoid using the SET method, all that headache can be avoided
1864
-                        $pk_field_name                   = $model->primary_key_name();
1865
-                        $this->_fields[ $pk_field_name ] = $results;
1866
-                        $this->_clear_cached_property($pk_field_name);
1867
-                        $model->add_to_entity_map($this);
1868
-                        $this->_update_cached_related_model_objs_fks();
1869
-                    }
1870
-                }
1871
-            } else {//PK is NOT auto-increment
1872
-                //so check if one like it already exists in the db
1873
-                if ($model->exists_by_ID($this->ID())) {
1874
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1875
-                        throw new EE_Error(
1876
-                            sprintf(
1877
-                                esc_html__(
1878
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1879
-                                    'event_espresso'
1880
-                                ),
1881
-                                get_class($this),
1882
-                                get_class($model) . '::instance()->add_to_entity_map()',
1883
-                                get_class($model) . '::instance()->get_one_by_ID()',
1884
-                                '<br />'
1885
-                            )
1886
-                        );
1887
-                    }
1888
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1889
-                } else {
1890
-                    $results = $model->insert($save_cols_n_values);
1891
-                    $this->_update_cached_related_model_objs_fks();
1892
-                }
1893
-            }
1894
-        } else {//there is NO primary key
1895
-            $already_in_db = false;
1896
-            foreach ($model->unique_indexes() as $index) {
1897
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1898
-                if ($model->exists(array($uniqueness_where_params))) {
1899
-                    $already_in_db = true;
1900
-                }
1901
-            }
1902
-            if ($already_in_db) {
1903
-                $combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1904
-                    $model->get_combined_primary_key_fields());
1905
-                $results                     = $model->update(
1906
-                    $save_cols_n_values,
1907
-                    $combined_pk_fields_n_values
1908
-                );
1909
-            } else {
1910
-                $results = $model->insert($save_cols_n_values);
1911
-            }
1912
-        }
1913
-        //restore the old assumption about values being prepared by the model object
1914
-        $model->assume_values_already_prepared_by_model_object(
1915
-                $old_assumption_concerning_value_preparation
1916
-            );
1917
-        /**
1918
-         * After saving the model object this action is called
1919
-         *
1920
-         * @param EE_Base_Class $model_object which was just saved
1921
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1922
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1923
-         */
1924
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1925
-        $this->_has_changes = false;
1926
-        return $results;
1927
-    }
1928
-
1929
-
1930
-    /**
1931
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1932
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1933
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1934
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1935
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1936
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1937
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1938
-     *
1939
-     * @return void
1940
-     * @throws ReflectionException
1941
-     * @throws InvalidArgumentException
1942
-     * @throws InvalidInterfaceException
1943
-     * @throws InvalidDataTypeException
1944
-     * @throws EE_Error
1945
-     */
1946
-    protected function _update_cached_related_model_objs_fks()
1947
-    {
1948
-        $model = $this->get_model();
1949
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1950
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1951
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1952
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1953
-                        $model->get_this_model_name()
1954
-                    );
1955
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1956
-                    if ($related_model_obj_in_cache->ID()) {
1957
-                        $related_model_obj_in_cache->save();
1958
-                    }
1959
-                }
1960
-            }
1961
-        }
1962
-    }
1963
-
1964
-
1965
-    /**
1966
-     * Saves this model object and its NEW cached relations to the database.
1967
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1968
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1969
-     * because otherwise, there's a potential for infinite looping of saving
1970
-     * Saves the cached related model objects, and ensures the relation between them
1971
-     * and this object and properly setup
1972
-     *
1973
-     * @return int ID of new model object on save; 0 on failure+
1974
-     * @throws ReflectionException
1975
-     * @throws InvalidArgumentException
1976
-     * @throws InvalidInterfaceException
1977
-     * @throws InvalidDataTypeException
1978
-     * @throws EE_Error
1979
-     */
1980
-    public function save_new_cached_related_model_objs()
1981
-    {
1982
-        //make sure this has been saved
1983
-        if (! $this->ID()) {
1984
-            $id = $this->save();
1985
-        } else {
1986
-            $id = $this->ID();
1987
-        }
1988
-        //now save all the NEW cached model objects  (ie they don't exist in the DB)
1989
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1990
-            if ($this->_model_relations[ $relationName ]) {
1991
-                //is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1992
-                //or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1993
-                /* @var $related_model_obj EE_Base_Class */
1994
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1995
-                    //add a relation to that relation type (which saves the appropriate thing in the process)
1996
-                    //but ONLY if it DOES NOT exist in the DB
1997
-                    $related_model_obj = $this->_model_relations[ $relationName ];
1998
-                    //					if( ! $related_model_obj->ID()){
1999
-                    $this->_add_relation_to($related_model_obj, $relationName);
2000
-                    $related_model_obj->save_new_cached_related_model_objs();
2001
-                    //					}
2002
-                } else {
2003
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2004
-                        //add a relation to that relation type (which saves the appropriate thing in the process)
2005
-                        //but ONLY if it DOES NOT exist in the DB
2006
-                        //						if( ! $related_model_obj->ID()){
2007
-                        $this->_add_relation_to($related_model_obj, $relationName);
2008
-                        $related_model_obj->save_new_cached_related_model_objs();
2009
-                        //						}
2010
-                    }
2011
-                }
2012
-            }
2013
-        }
2014
-        return $id;
2015
-    }
2016
-
2017
-
2018
-    /**
2019
-     * for getting a model while instantiated.
2020
-     *
2021
-     * @return EEM_Base | EEM_CPT_Base
2022
-     * @throws ReflectionException
2023
-     * @throws InvalidArgumentException
2024
-     * @throws InvalidInterfaceException
2025
-     * @throws InvalidDataTypeException
2026
-     * @throws EE_Error
2027
-     */
2028
-    public function get_model()
2029
-    {
2030
-        if (! $this->_model) {
2031
-            $modelName    = self::_get_model_classname(get_class($this));
2032
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2033
-        } else {
2034
-            $this->_model->set_timezone($this->_timezone);
2035
-        }
2036
-        return $this->_model;
2037
-    }
2038
-
2039
-
2040
-    /**
2041
-     * @param $props_n_values
2042
-     * @param $classname
2043
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2044
-     * @throws ReflectionException
2045
-     * @throws InvalidArgumentException
2046
-     * @throws InvalidInterfaceException
2047
-     * @throws InvalidDataTypeException
2048
-     * @throws EE_Error
2049
-     */
2050
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2051
-    {
2052
-        //TODO: will not work for Term_Relationships because they have no PK!
2053
-        $primary_id_ref = self::_get_primary_key_name($classname);
2054
-        if (
2055
-            array_key_exists($primary_id_ref, $props_n_values)
2056
-            && ! empty($props_n_values[ $primary_id_ref ])
2057
-        ) {
2058
-            $id = $props_n_values[ $primary_id_ref ];
2059
-            return self::_get_model($classname)->get_from_entity_map($id);
2060
-        }
2061
-        return false;
2062
-    }
2063
-
2064
-
2065
-    /**
2066
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2067
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2068
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2069
-     * we return false.
2070
-     *
2071
-     * @param  array  $props_n_values   incoming array of properties and their values
2072
-     * @param  string $classname        the classname of the child class
2073
-     * @param null    $timezone
2074
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2075
-     *                                  date_format and the second value is the time format
2076
-     * @return mixed (EE_Base_Class|bool)
2077
-     * @throws InvalidArgumentException
2078
-     * @throws InvalidInterfaceException
2079
-     * @throws InvalidDataTypeException
2080
-     * @throws EE_Error
2081
-     * @throws ReflectionException
2082
-     * @throws ReflectionException
2083
-     * @throws ReflectionException
2084
-     */
2085
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2086
-    {
2087
-        $existing = null;
2088
-        $model    = self::_get_model($classname, $timezone);
2089
-        if ($model->has_primary_key_field()) {
2090
-            $primary_id_ref = self::_get_primary_key_name($classname);
2091
-            if (array_key_exists($primary_id_ref, $props_n_values)
2092
-                && ! empty($props_n_values[ $primary_id_ref ])
2093
-            ) {
2094
-                $existing = $model->get_one_by_ID(
2095
-                    $props_n_values[ $primary_id_ref ]
2096
-                );
2097
-            }
2098
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2099
-            //no primary key on this model, but there's still a matching item in the DB
2100
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2101
-                self::_get_model($classname, $timezone)
2102
-                    ->get_index_primary_key_string($props_n_values)
2103
-            );
2104
-        }
2105
-        if ($existing) {
2106
-            //set date formats if present before setting values
2107
-            if (! empty($date_formats) && is_array($date_formats)) {
2108
-                $existing->set_date_format($date_formats[0]);
2109
-                $existing->set_time_format($date_formats[1]);
2110
-            } else {
2111
-                //set default formats for date and time
2112
-                $existing->set_date_format(get_option('date_format'));
2113
-                $existing->set_time_format(get_option('time_format'));
2114
-            }
2115
-            foreach ($props_n_values as $property => $field_value) {
2116
-                $existing->set($property, $field_value);
2117
-            }
2118
-            return $existing;
2119
-        }
2120
-        return false;
2121
-    }
2122
-
2123
-
2124
-    /**
2125
-     * Gets the EEM_*_Model for this class
2126
-     *
2127
-     * @access public now, as this is more convenient
2128
-     * @param      $classname
2129
-     * @param null $timezone
2130
-     * @throws ReflectionException
2131
-     * @throws InvalidArgumentException
2132
-     * @throws InvalidInterfaceException
2133
-     * @throws InvalidDataTypeException
2134
-     * @throws EE_Error
2135
-     * @return EEM_Base
2136
-     */
2137
-    protected static function _get_model($classname, $timezone = null)
2138
-    {
2139
-        //find model for this class
2140
-        if (! $classname) {
2141
-            throw new EE_Error(
2142
-                sprintf(
2143
-                    esc_html__(
2144
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2145
-                        'event_espresso'
2146
-                    ),
2147
-                    $classname
2148
-                )
2149
-            );
2150
-        }
2151
-        $modelName = self::_get_model_classname($classname);
2152
-        return self::_get_model_instance_with_name($modelName, $timezone);
2153
-    }
2154
-
2155
-
2156
-    /**
2157
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2158
-     *
2159
-     * @param string $model_classname
2160
-     * @param null   $timezone
2161
-     * @return EEM_Base
2162
-     * @throws ReflectionException
2163
-     * @throws InvalidArgumentException
2164
-     * @throws InvalidInterfaceException
2165
-     * @throws InvalidDataTypeException
2166
-     * @throws EE_Error
2167
-     */
2168
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2169
-    {
2170
-        $model_classname = str_replace('EEM_', '', $model_classname);
2171
-        $model           = EE_Registry::instance()->load_model($model_classname);
2172
-        $model->set_timezone($timezone);
2173
-        return $model;
2174
-    }
2175
-
2176
-
2177
-    /**
2178
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2179
-     * Also works if a model class's classname is provided (eg EE_Registration).
2180
-     *
2181
-     * @param null $model_name
2182
-     * @return string like EEM_Attendee
2183
-     */
2184
-    private static function _get_model_classname($model_name = null)
2185
-    {
2186
-        if (strpos($model_name, 'EE_') === 0) {
2187
-            $model_classname = str_replace('EE_', 'EEM_', $model_name);
2188
-        } else {
2189
-            $model_classname = 'EEM_' . $model_name;
2190
-        }
2191
-        return $model_classname;
2192
-    }
2193
-
2194
-
2195
-    /**
2196
-     * returns the name of the primary key attribute
2197
-     *
2198
-     * @param null $classname
2199
-     * @throws ReflectionException
2200
-     * @throws InvalidArgumentException
2201
-     * @throws InvalidInterfaceException
2202
-     * @throws InvalidDataTypeException
2203
-     * @throws EE_Error
2204
-     * @return string
2205
-     */
2206
-    protected static function _get_primary_key_name($classname = null)
2207
-    {
2208
-        if (! $classname) {
2209
-            throw new EE_Error(
2210
-                sprintf(
2211
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2212
-                    $classname
2213
-                )
2214
-            );
2215
-        }
2216
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2217
-    }
2218
-
2219
-
2220
-    /**
2221
-     * Gets the value of the primary key.
2222
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2223
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2224
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2225
-     *
2226
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2227
-     * @throws ReflectionException
2228
-     * @throws InvalidArgumentException
2229
-     * @throws InvalidInterfaceException
2230
-     * @throws InvalidDataTypeException
2231
-     * @throws EE_Error
2232
-     */
2233
-    public function ID()
2234
-    {
2235
-        $model = $this->get_model();
2236
-        //now that we know the name of the variable, use a variable variable to get its value and return its
2237
-        if ($model->has_primary_key_field()) {
2238
-            return $this->_fields[ $model->primary_key_name() ];
2239
-        }
2240
-        return $model->get_index_primary_key_string($this->_fields);
2241
-    }
2242
-
2243
-
2244
-    /**
2245
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2246
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2247
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2248
-     *
2249
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2250
-     * @param string $relationName                     eg 'Events','Question',etc.
2251
-     *                                                 an attendee to a group, you also want to specify which role they
2252
-     *                                                 will have in that group. So you would use this parameter to
2253
-     *                                                 specify array('role-column-name'=>'role-id')
2254
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2255
-     *                                                 allow you to further constrict the relation to being added.
2256
-     *                                                 However, keep in mind that the columns (keys) given must match a
2257
-     *                                                 column on the JOIN table and currently only the HABTM models
2258
-     *                                                 accept these additional conditions.  Also remember that if an
2259
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2260
-     *                                                 NEW row is created in the join table.
2261
-     * @param null   $cache_id
2262
-     * @throws ReflectionException
2263
-     * @throws InvalidArgumentException
2264
-     * @throws InvalidInterfaceException
2265
-     * @throws InvalidDataTypeException
2266
-     * @throws EE_Error
2267
-     * @return EE_Base_Class the object the relation was added to
2268
-     */
2269
-    public function _add_relation_to(
2270
-        $otherObjectModelObjectOrID,
2271
-        $relationName,
2272
-        $extra_join_model_fields_n_values = array(),
2273
-        $cache_id = null
2274
-    ) {
2275
-        $model = $this->get_model();
2276
-        //if this thing exists in the DB, save the relation to the DB
2277
-        if ($this->ID()) {
2278
-            $otherObject = $model->add_relationship_to(
2279
-                $this,
2280
-                $otherObjectModelObjectOrID,
2281
-                $relationName,
2282
-                $extra_join_model_fields_n_values
2283
-            );
2284
-            //clear cache so future get_many_related and get_first_related() return new results.
2285
-            $this->clear_cache($relationName, $otherObject, true);
2286
-            if ($otherObject instanceof EE_Base_Class) {
2287
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2288
-            }
2289
-        } else {
2290
-            //this thing doesn't exist in the DB,  so just cache it
2291
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2292
-                throw new EE_Error(
2293
-                    sprintf(
2294
-                        esc_html__(
2295
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2296
-                            'event_espresso'
2297
-                        ),
2298
-                        $otherObjectModelObjectOrID,
2299
-                        get_class($this)
2300
-                    )
2301
-                );
2302
-            }
2303
-            $otherObject = $otherObjectModelObjectOrID;
2304
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2305
-        }
2306
-        if ($otherObject instanceof EE_Base_Class) {
2307
-            //fix the reciprocal relation too
2308
-            if ($otherObject->ID()) {
2309
-                //its saved so assumed relations exist in the DB, so we can just
2310
-                //clear the cache so future queries use the updated info in the DB
2311
-                $otherObject->clear_cache(
2312
-                    $model->get_this_model_name(),
2313
-                    null,
2314
-                    true
2315
-                );
2316
-            } else {
2317
-                //it's not saved, so it caches relations like this
2318
-                $otherObject->cache($model->get_this_model_name(), $this);
2319
-            }
2320
-        }
2321
-        return $otherObject;
2322
-    }
2323
-
2324
-
2325
-    /**
2326
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2327
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2328
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2329
-     * from the cache
2330
-     *
2331
-     * @param mixed  $otherObjectModelObjectOrID
2332
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2333
-     *                to the DB yet
2334
-     * @param string $relationName
2335
-     * @param array  $where_query
2336
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2337
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2338
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2339
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2340
-     *                created in the join table.
2341
-     * @return EE_Base_Class the relation was removed from
2342
-     * @throws ReflectionException
2343
-     * @throws InvalidArgumentException
2344
-     * @throws InvalidInterfaceException
2345
-     * @throws InvalidDataTypeException
2346
-     * @throws EE_Error
2347
-     */
2348
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2349
-    {
2350
-        if ($this->ID()) {
2351
-            //if this exists in the DB, save the relation change to the DB too
2352
-            $otherObject = $this->get_model()->remove_relationship_to(
2353
-                $this,
2354
-                $otherObjectModelObjectOrID,
2355
-                $relationName,
2356
-                $where_query
2357
-            );
2358
-            $this->clear_cache(
2359
-                $relationName,
2360
-                $otherObject
2361
-            );
2362
-        } else {
2363
-            //this doesn't exist in the DB, just remove it from the cache
2364
-            $otherObject = $this->clear_cache(
2365
-                $relationName,
2366
-                $otherObjectModelObjectOrID
2367
-            );
2368
-        }
2369
-        if ($otherObject instanceof EE_Base_Class) {
2370
-            $otherObject->clear_cache(
2371
-                $this->get_model()->get_this_model_name(),
2372
-                $this
2373
-            );
2374
-        }
2375
-        return $otherObject;
2376
-    }
2377
-
2378
-
2379
-    /**
2380
-     * Removes ALL the related things for the $relationName.
2381
-     *
2382
-     * @param string $relationName
2383
-     * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2384
-     * @return EE_Base_Class
2385
-     * @throws ReflectionException
2386
-     * @throws InvalidArgumentException
2387
-     * @throws InvalidInterfaceException
2388
-     * @throws InvalidDataTypeException
2389
-     * @throws EE_Error
2390
-     */
2391
-    public function _remove_relations($relationName, $where_query_params = array())
2392
-    {
2393
-        if ($this->ID()) {
2394
-            //if this exists in the DB, save the relation change to the DB too
2395
-            $otherObjects = $this->get_model()->remove_relations(
2396
-                $this,
2397
-                $relationName,
2398
-                $where_query_params
2399
-            );
2400
-            $this->clear_cache(
2401
-                $relationName,
2402
-                null,
2403
-                true
2404
-            );
2405
-        } else {
2406
-            //this doesn't exist in the DB, just remove it from the cache
2407
-            $otherObjects = $this->clear_cache(
2408
-                $relationName,
2409
-                null,
2410
-                true
2411
-            );
2412
-        }
2413
-        if (is_array($otherObjects)) {
2414
-            foreach ($otherObjects as $otherObject) {
2415
-                $otherObject->clear_cache(
2416
-                    $this->get_model()->get_this_model_name(),
2417
-                    $this
2418
-                );
2419
-            }
2420
-        }
2421
-        return $otherObjects;
2422
-    }
2423
-
2424
-
2425
-    /**
2426
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2427
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2428
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2429
-     * because we want to get even deleted items etc.
2430
-     *
2431
-     * @param string $relationName key in the model's _model_relations array
2432
-     * @param array  $query_params like EEM_Base::get_all
2433
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2434
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2435
-     *                             results if you want IDs
2436
-     * @throws ReflectionException
2437
-     * @throws InvalidArgumentException
2438
-     * @throws InvalidInterfaceException
2439
-     * @throws InvalidDataTypeException
2440
-     * @throws EE_Error
2441
-     */
2442
-    public function get_many_related($relationName, $query_params = array())
2443
-    {
2444
-        if ($this->ID()) {
2445
-            //this exists in the DB, so get the related things from either the cache or the DB
2446
-            //if there are query parameters, forget about caching the related model objects.
2447
-            if ($query_params) {
2448
-                $related_model_objects = $this->get_model()->get_all_related(
2449
-                    $this,
2450
-                    $relationName,
2451
-                    $query_params
2452
-                );
2453
-            } else {
2454
-                //did we already cache the result of this query?
2455
-                $cached_results = $this->get_all_from_cache($relationName);
2456
-                if (! $cached_results) {
2457
-                    $related_model_objects = $this->get_model()->get_all_related(
2458
-                        $this,
2459
-                        $relationName,
2460
-                        $query_params
2461
-                    );
2462
-                    //if no query parameters were passed, then we got all the related model objects
2463
-                    //for that relation. We can cache them then.
2464
-                    foreach ($related_model_objects as $related_model_object) {
2465
-                        $this->cache($relationName, $related_model_object);
2466
-                    }
2467
-                } else {
2468
-                    $related_model_objects = $cached_results;
2469
-                }
2470
-            }
2471
-        } else {
2472
-            //this doesn't exist in the DB, so just get the related things from the cache
2473
-            $related_model_objects = $this->get_all_from_cache($relationName);
2474
-        }
2475
-        return $related_model_objects;
2476
-    }
2477
-
2478
-
2479
-    /**
2480
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2481
-     * unless otherwise specified in the $query_params
2482
-     *
2483
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2484
-     * @param array  $query_params   like EEM_Base::get_all's
2485
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2486
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2487
-     *                               that by the setting $distinct to TRUE;
2488
-     * @return int
2489
-     * @throws ReflectionException
2490
-     * @throws InvalidArgumentException
2491
-     * @throws InvalidInterfaceException
2492
-     * @throws InvalidDataTypeException
2493
-     * @throws EE_Error
2494
-     */
2495
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2496
-    {
2497
-        return $this->get_model()->count_related(
2498
-            $this,
2499
-            $relation_name,
2500
-            $query_params,
2501
-            $field_to_count,
2502
-            $distinct
2503
-        );
2504
-    }
2505
-
2506
-
2507
-    /**
2508
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2509
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2510
-     *
2511
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2512
-     * @param array  $query_params  like EEM_Base::get_all's
2513
-     * @param string $field_to_sum  name of field to count by.
2514
-     *                              By default, uses primary key
2515
-     *                              (which doesn't make much sense, so you should probably change it)
2516
-     * @return int
2517
-     * @throws ReflectionException
2518
-     * @throws InvalidArgumentException
2519
-     * @throws InvalidInterfaceException
2520
-     * @throws InvalidDataTypeException
2521
-     * @throws EE_Error
2522
-     */
2523
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2524
-    {
2525
-        return $this->get_model()->sum_related(
2526
-            $this,
2527
-            $relation_name,
2528
-            $query_params,
2529
-            $field_to_sum
2530
-        );
2531
-    }
2532
-
2533
-
2534
-    /**
2535
-     * Gets the first (ie, one) related model object of the specified type.
2536
-     *
2537
-     * @param string $relationName key in the model's _model_relations array
2538
-     * @param array  $query_params like EEM_Base::get_all
2539
-     * @return EE_Base_Class (not an array, a single object)
2540
-     * @throws ReflectionException
2541
-     * @throws InvalidArgumentException
2542
-     * @throws InvalidInterfaceException
2543
-     * @throws InvalidDataTypeException
2544
-     * @throws EE_Error
2545
-     */
2546
-    public function get_first_related($relationName, $query_params = array())
2547
-    {
2548
-        $model = $this->get_model();
2549
-        if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2550
-            //if they've provided some query parameters, don't bother trying to cache the result
2551
-            //also make sure we're not caching the result of get_first_related
2552
-            //on a relation which should have an array of objects (because the cache might have an array of objects)
2553
-            if ($query_params
2554
-                || ! $model->related_settings_for($relationName)
2555
-                     instanceof
2556
-                     EE_Belongs_To_Relation
2557
-            ) {
2558
-                $related_model_object = $model->get_first_related(
2559
-                    $this,
2560
-                    $relationName,
2561
-                    $query_params
2562
-                );
2563
-            } else {
2564
-                //first, check if we've already cached the result of this query
2565
-                $cached_result = $this->get_one_from_cache($relationName);
2566
-                if (! $cached_result) {
2567
-                    $related_model_object = $model->get_first_related(
2568
-                        $this,
2569
-                        $relationName,
2570
-                        $query_params
2571
-                    );
2572
-                    $this->cache($relationName, $related_model_object);
2573
-                } else {
2574
-                    $related_model_object = $cached_result;
2575
-                }
2576
-            }
2577
-        } else {
2578
-            $related_model_object = null;
2579
-            // this doesn't exist in the Db,
2580
-            // but maybe the relation is of type belongs to, and so the related thing might
2581
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2582
-                $related_model_object = $model->get_first_related(
2583
-                    $this,
2584
-                    $relationName,
2585
-                    $query_params
2586
-                );
2587
-            }
2588
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2589
-            // just get what's cached on this object
2590
-            if (! $related_model_object) {
2591
-                $related_model_object = $this->get_one_from_cache($relationName);
2592
-            }
2593
-        }
2594
-        return $related_model_object;
2595
-    }
2596
-
2597
-
2598
-    /**
2599
-     * Does a delete on all related objects of type $relationName and removes
2600
-     * the current model object's relation to them. If they can't be deleted (because
2601
-     * of blocking related model objects) does nothing. If the related model objects are
2602
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2603
-     * If this model object doesn't exist yet in the DB, just removes its related things
2604
-     *
2605
-     * @param string $relationName
2606
-     * @param array  $query_params like EEM_Base::get_all's
2607
-     * @return int how many deleted
2608
-     * @throws ReflectionException
2609
-     * @throws InvalidArgumentException
2610
-     * @throws InvalidInterfaceException
2611
-     * @throws InvalidDataTypeException
2612
-     * @throws EE_Error
2613
-     */
2614
-    public function delete_related($relationName, $query_params = array())
2615
-    {
2616
-        if ($this->ID()) {
2617
-            $count = $this->get_model()->delete_related(
2618
-                $this,
2619
-                $relationName,
2620
-                $query_params
2621
-            );
2622
-        } else {
2623
-            $count = count($this->get_all_from_cache($relationName));
2624
-            $this->clear_cache($relationName, null, true);
2625
-        }
2626
-        return $count;
2627
-    }
2628
-
2629
-
2630
-    /**
2631
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2632
-     * the current model object's relation to them. If they can't be deleted (because
2633
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2634
-     * If the related thing isn't a soft-deletable model object, this function is identical
2635
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2636
-     *
2637
-     * @param string $relationName
2638
-     * @param array  $query_params like EEM_Base::get_all's
2639
-     * @return int how many deleted (including those soft deleted)
2640
-     * @throws ReflectionException
2641
-     * @throws InvalidArgumentException
2642
-     * @throws InvalidInterfaceException
2643
-     * @throws InvalidDataTypeException
2644
-     * @throws EE_Error
2645
-     */
2646
-    public function delete_related_permanently($relationName, $query_params = array())
2647
-    {
2648
-        if ($this->ID()) {
2649
-            $count = $this->get_model()->delete_related_permanently(
2650
-                $this,
2651
-                $relationName,
2652
-                $query_params
2653
-            );
2654
-        } else {
2655
-            $count = count($this->get_all_from_cache($relationName));
2656
-        }
2657
-        $this->clear_cache($relationName, null, true);
2658
-        return $count;
2659
-    }
2660
-
2661
-
2662
-    /**
2663
-     * is_set
2664
-     * Just a simple utility function children can use for checking if property exists
2665
-     *
2666
-     * @access  public
2667
-     * @param  string $field_name property to check
2668
-     * @return bool                              TRUE if existing,FALSE if not.
2669
-     */
2670
-    public function is_set($field_name)
2671
-    {
2672
-        return isset($this->_fields[ $field_name ]);
2673
-    }
2674
-
2675
-
2676
-    /**
2677
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2678
-     * EE_Error exception if they don't
2679
-     *
2680
-     * @param  mixed (string|array) $properties properties to check
2681
-     * @throws EE_Error
2682
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2683
-     */
2684
-    protected function _property_exists($properties)
2685
-    {
2686
-        foreach ((array) $properties as $property_name) {
2687
-            //first make sure this property exists
2688
-            if (! $this->_fields[ $property_name ]) {
2689
-                throw new EE_Error(
2690
-                    sprintf(
2691
-                        esc_html__(
2692
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2693
-                            'event_espresso'
2694
-                        ),
2695
-                        $property_name
2696
-                    )
2697
-                );
2698
-            }
2699
-        }
2700
-        return true;
2701
-    }
2702
-
2703
-
2704
-    /**
2705
-     * This simply returns an array of model fields for this object
2706
-     *
2707
-     * @return array
2708
-     * @throws ReflectionException
2709
-     * @throws InvalidArgumentException
2710
-     * @throws InvalidInterfaceException
2711
-     * @throws InvalidDataTypeException
2712
-     * @throws EE_Error
2713
-     */
2714
-    public function model_field_array()
2715
-    {
2716
-        $fields     = $this->get_model()->field_settings(false);
2717
-        $properties = array();
2718
-        //remove prepended underscore
2719
-        foreach ($fields as $field_name => $settings) {
2720
-            $properties[ $field_name ] = $this->get($field_name);
2721
-        }
2722
-        return $properties;
2723
-    }
2724
-
2725
-
2726
-    /**
2727
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2728
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2729
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2730
-     * Instead of requiring a plugin to extend the EE_Base_Class
2731
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2732
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2733
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2734
-     * and accepts 2 arguments: the object on which the function was called,
2735
-     * and an array of the original arguments passed to the function.
2736
-     * Whatever their callback function returns will be returned by this function.
2737
-     * Example: in functions.php (or in a plugin):
2738
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2739
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2740
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2741
-     *          return $previousReturnValue.$returnString;
2742
-     *      }
2743
-     * require('EE_Answer.class.php');
2744
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2745
-     * echo $answer->my_callback('monkeys',100);
2746
-     * //will output "you called my_callback! and passed args:monkeys,100"
2747
-     *
2748
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2749
-     * @param array  $args       array of original arguments passed to the function
2750
-     * @throws EE_Error
2751
-     * @return mixed whatever the plugin which calls add_filter decides
2752
-     */
2753
-    public function __call($methodName, $args)
2754
-    {
2755
-        $className = get_class($this);
2756
-        $tagName   = "FHEE__{$className}__{$methodName}";
2757
-        if (! has_filter($tagName)) {
2758
-            throw new EE_Error(
2759
-                sprintf(
2760
-                    esc_html__(
2761
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2762
-                        'event_espresso'
2763
-                    ),
2764
-                    $methodName,
2765
-                    $className,
2766
-                    $tagName
2767
-                )
2768
-            );
2769
-        }
2770
-        return apply_filters($tagName, null, $this, $args);
2771
-    }
2772
-
2773
-
2774
-    /**
2775
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2776
-     * A $previous_value can be specified in case there are many meta rows with the same key
2777
-     *
2778
-     * @param string $meta_key
2779
-     * @param mixed  $meta_value
2780
-     * @param mixed  $previous_value
2781
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2782
-     *                  NOTE: if the values haven't changed, returns 0
2783
-     * @throws InvalidArgumentException
2784
-     * @throws InvalidInterfaceException
2785
-     * @throws InvalidDataTypeException
2786
-     * @throws EE_Error
2787
-     * @throws ReflectionException
2788
-     */
2789
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2790
-    {
2791
-        $query_params = array(
2792
-            array(
2793
-                'EXM_key'  => $meta_key,
2794
-                'OBJ_ID'   => $this->ID(),
2795
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2796
-            ),
2797
-        );
2798
-        if ($previous_value !== null) {
2799
-            $query_params[0]['EXM_value'] = $meta_value;
2800
-        }
2801
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2802
-        if (! $existing_rows_like_that) {
2803
-            return $this->add_extra_meta($meta_key, $meta_value);
2804
-        }
2805
-        foreach ($existing_rows_like_that as $existing_row) {
2806
-            $existing_row->save(array('EXM_value' => $meta_value));
2807
-        }
2808
-        return count($existing_rows_like_that);
2809
-    }
2810
-
2811
-
2812
-    /**
2813
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2814
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2815
-     * extra meta row was entered, false if not
2816
-     *
2817
-     * @param string  $meta_key
2818
-     * @param mixed   $meta_value
2819
-     * @param boolean $unique
2820
-     * @return boolean
2821
-     * @throws InvalidArgumentException
2822
-     * @throws InvalidInterfaceException
2823
-     * @throws InvalidDataTypeException
2824
-     * @throws EE_Error
2825
-     * @throws ReflectionException
2826
-     * @throws ReflectionException
2827
-     */
2828
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2829
-    {
2830
-        if ($unique) {
2831
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2832
-                array(
2833
-                    array(
2834
-                        'EXM_key'  => $meta_key,
2835
-                        'OBJ_ID'   => $this->ID(),
2836
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2837
-                    ),
2838
-                )
2839
-            );
2840
-            if ($existing_extra_meta) {
2841
-                return false;
2842
-            }
2843
-        }
2844
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2845
-            array(
2846
-                'EXM_key'   => $meta_key,
2847
-                'EXM_value' => $meta_value,
2848
-                'OBJ_ID'    => $this->ID(),
2849
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2850
-            )
2851
-        );
2852
-        $new_extra_meta->save();
2853
-        return true;
2854
-    }
2855
-
2856
-
2857
-    /**
2858
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2859
-     * is specified, only deletes extra meta records with that value.
2860
-     *
2861
-     * @param string $meta_key
2862
-     * @param mixed  $meta_value
2863
-     * @return int number of extra meta rows deleted
2864
-     * @throws InvalidArgumentException
2865
-     * @throws InvalidInterfaceException
2866
-     * @throws InvalidDataTypeException
2867
-     * @throws EE_Error
2868
-     * @throws ReflectionException
2869
-     */
2870
-    public function delete_extra_meta($meta_key, $meta_value = null)
2871
-    {
2872
-        $query_params = array(
2873
-            array(
2874
-                'EXM_key'  => $meta_key,
2875
-                'OBJ_ID'   => $this->ID(),
2876
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2877
-            ),
2878
-        );
2879
-        if ($meta_value !== null) {
2880
-            $query_params[0]['EXM_value'] = $meta_value;
2881
-        }
2882
-        return EEM_Extra_Meta::instance()->delete($query_params);
2883
-    }
2884
-
2885
-
2886
-    /**
2887
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2888
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2889
-     * You can specify $default is case you haven't found the extra meta
2890
-     *
2891
-     * @param string  $meta_key
2892
-     * @param boolean $single
2893
-     * @param mixed   $default if we don't find anything, what should we return?
2894
-     * @return mixed single value if $single; array if ! $single
2895
-     * @throws ReflectionException
2896
-     * @throws InvalidArgumentException
2897
-     * @throws InvalidInterfaceException
2898
-     * @throws InvalidDataTypeException
2899
-     * @throws EE_Error
2900
-     */
2901
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2902
-    {
2903
-        if ($single) {
2904
-            $result = $this->get_first_related(
2905
-                'Extra_Meta',
2906
-                array(array('EXM_key' => $meta_key))
2907
-            );
2908
-            if ($result instanceof EE_Extra_Meta) {
2909
-                return $result->value();
2910
-            }
2911
-        } else {
2912
-            $results = $this->get_many_related(
2913
-                'Extra_Meta',
2914
-                array(array('EXM_key' => $meta_key))
2915
-            );
2916
-            if ($results) {
2917
-                $values = array();
2918
-                foreach ($results as $result) {
2919
-                    if ($result instanceof EE_Extra_Meta) {
2920
-                        $values[ $result->ID() ] = $result->value();
2921
-                    }
2922
-                }
2923
-                return $values;
2924
-            }
2925
-        }
2926
-        //if nothing discovered yet return default.
2927
-        return apply_filters(
2928
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2929
-            $default,
2930
-            $meta_key,
2931
-            $single,
2932
-            $this
2933
-        );
2934
-    }
2935
-
2936
-
2937
-    /**
2938
-     * Returns a simple array of all the extra meta associated with this model object.
2939
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2940
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2941
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2942
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2943
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2944
-     * finally the extra meta's value as each sub-value. (eg
2945
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2946
-     *
2947
-     * @param boolean $one_of_each_key
2948
-     * @return array
2949
-     * @throws ReflectionException
2950
-     * @throws InvalidArgumentException
2951
-     * @throws InvalidInterfaceException
2952
-     * @throws InvalidDataTypeException
2953
-     * @throws EE_Error
2954
-     */
2955
-    public function all_extra_meta_array($one_of_each_key = true)
2956
-    {
2957
-        $return_array = array();
2958
-        if ($one_of_each_key) {
2959
-            $extra_meta_objs = $this->get_many_related(
2960
-                'Extra_Meta',
2961
-                array('group_by' => 'EXM_key')
2962
-            );
2963
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2964
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2965
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2966
-                }
2967
-            }
2968
-        } else {
2969
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2970
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2971
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2972
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2973
-                        $return_array[ $extra_meta_obj->key() ] = array();
2974
-                    }
2975
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2976
-                }
2977
-            }
2978
-        }
2979
-        return $return_array;
2980
-    }
2981
-
2982
-
2983
-    /**
2984
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2985
-     *
2986
-     * @return string
2987
-     * @throws ReflectionException
2988
-     * @throws InvalidArgumentException
2989
-     * @throws InvalidInterfaceException
2990
-     * @throws InvalidDataTypeException
2991
-     * @throws EE_Error
2992
-     */
2993
-    public function name()
2994
-    {
2995
-        //find a field that's not a text field
2996
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2997
-        if ($field_we_can_use) {
2998
-            return $this->get($field_we_can_use->get_name());
2999
-        }
3000
-        $first_few_properties = $this->model_field_array();
3001
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3002
-        $name_parts           = array();
3003
-        foreach ($first_few_properties as $name => $value) {
3004
-            $name_parts[] = "$name:$value";
3005
-        }
3006
-        return implode(',', $name_parts);
3007
-    }
3008
-
3009
-
3010
-    /**
3011
-     * in_entity_map
3012
-     * Checks if this model object has been proven to already be in the entity map
3013
-     *
3014
-     * @return boolean
3015
-     * @throws ReflectionException
3016
-     * @throws InvalidArgumentException
3017
-     * @throws InvalidInterfaceException
3018
-     * @throws InvalidDataTypeException
3019
-     * @throws EE_Error
3020
-     */
3021
-    public function in_entity_map()
3022
-    {
3023
-        // well, if we looked, did we find it in the entity map?
3024
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3025
-    }
3026
-
3027
-
3028
-    /**
3029
-     * refresh_from_db
3030
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3031
-     *
3032
-     * @throws ReflectionException
3033
-     * @throws InvalidArgumentException
3034
-     * @throws InvalidInterfaceException
3035
-     * @throws InvalidDataTypeException
3036
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3037
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3038
-     */
3039
-    public function refresh_from_db()
3040
-    {
3041
-        if ($this->ID() && $this->in_entity_map()) {
3042
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3043
-        } else {
3044
-            //if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3045
-            //if it has an ID but it's not in the map, and you're asking me to refresh it
3046
-            //that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3047
-            //absolutely nothing in it for this ID
3048
-            if (WP_DEBUG) {
3049
-                throw new EE_Error(
3050
-                    sprintf(
3051
-                        esc_html__('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3052
-                            'event_espresso'),
3053
-                        $this->ID(),
3054
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3055
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3056
-                    )
3057
-                );
3058
-            }
3059
-        }
3060
-    }
3061
-
3062
-
3063
-    /**
3064
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3065
-     * (probably a bad assumption they have made, oh well)
3066
-     *
3067
-     * @return string
3068
-     */
3069
-    public function __toString()
3070
-    {
3071
-        try {
3072
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3073
-        } catch (Exception $e) {
3074
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3075
-            return '';
3076
-        }
3077
-    }
3078
-
3079
-
3080
-    /**
3081
-     * Clear related model objects if they're already in the DB, because otherwise when we
3082
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3083
-     * This means if we have made changes to those related model objects, and want to unserialize
3084
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3085
-     * Instead, those related model objects should be directly serialized and stored.
3086
-     * Eg, the following won't work:
3087
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3088
-     * $att = $reg->attendee();
3089
-     * $att->set( 'ATT_fname', 'Dirk' );
3090
-     * update_option( 'my_option', serialize( $reg ) );
3091
-     * //END REQUEST
3092
-     * //START NEXT REQUEST
3093
-     * $reg = get_option( 'my_option' );
3094
-     * $reg->attendee()->save();
3095
-     * And would need to be replace with:
3096
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3097
-     * $att = $reg->attendee();
3098
-     * $att->set( 'ATT_fname', 'Dirk' );
3099
-     * update_option( 'my_option', serialize( $reg ) );
3100
-     * //END REQUEST
3101
-     * //START NEXT REQUEST
3102
-     * $att = get_option( 'my_option' );
3103
-     * $att->save();
3104
-     *
3105
-     * @return array
3106
-     * @throws ReflectionException
3107
-     * @throws InvalidArgumentException
3108
-     * @throws InvalidInterfaceException
3109
-     * @throws InvalidDataTypeException
3110
-     * @throws EE_Error
3111
-     */
3112
-    public function __sleep()
3113
-    {
3114
-        $model = $this->get_model();
3115
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3116
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3117
-                $classname = 'EE_' . $model->get_this_model_name();
3118
-                if (
3119
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3120
-                    && $this->get_one_from_cache($relation_name)->ID()
3121
-                ) {
3122
-                    $this->clear_cache(
3123
-                        $relation_name,
3124
-                        $this->get_one_from_cache($relation_name)->ID()
3125
-                    );
3126
-                }
3127
-            }
3128
-        }
3129
-        $this->_props_n_values_provided_in_constructor = array();
3130
-        $properties_to_serialize                       = get_object_vars($this);
3131
-        //don't serialize the model. It's big and that risks recursion
3132
-        unset($properties_to_serialize['_model']);
3133
-        return array_keys($properties_to_serialize);
3134
-    }
3135
-
3136
-
3137
-    /**
3138
-     * restore _props_n_values_provided_in_constructor
3139
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3140
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3141
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3142
-     */
3143
-    public function __wakeup()
3144
-    {
3145
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3146
-    }
3147
-
3148
-
3149
-    /**
3150
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3151
-     * distinct with the clone host instance are also cloned.
3152
-     */
3153
-    public function __clone()
3154
-    {
3155
-        //handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3156
-        foreach ($this->_fields as $field => $value) {
3157
-            if ($value instanceof DateTime) {
3158
-                $this->_fields[$field] = clone $value;
3159
-            }
3160
-        }
3161
-    }
18
+	/**
19
+	 * This is an array of the original properties and values provided during construction
20
+	 * of this model object. (keys are model field names, values are their values).
21
+	 * This list is important to remember so that when we are merging data from the db, we know
22
+	 * which values to override and which to not override.
23
+	 *
24
+	 * @var array
25
+	 */
26
+	protected $_props_n_values_provided_in_constructor;
27
+
28
+	/**
29
+	 * Timezone
30
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
31
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
32
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
33
+	 * access to it.
34
+	 *
35
+	 * @var string
36
+	 */
37
+	protected $_timezone;
38
+
39
+	/**
40
+	 * date format
41
+	 * pattern or format for displaying dates
42
+	 *
43
+	 * @var string $_dt_frmt
44
+	 */
45
+	protected $_dt_frmt;
46
+
47
+	/**
48
+	 * time format
49
+	 * pattern or format for displaying time
50
+	 *
51
+	 * @var string $_tm_frmt
52
+	 */
53
+	protected $_tm_frmt;
54
+
55
+	/**
56
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
57
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
58
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
59
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
60
+	 *
61
+	 * @var array
62
+	 */
63
+	protected $_cached_properties = array();
64
+
65
+	/**
66
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
67
+	 * single
68
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
69
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
70
+	 * all others have an array)
71
+	 *
72
+	 * @var array
73
+	 */
74
+	protected $_model_relations = array();
75
+
76
+	/**
77
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
78
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
79
+	 *
80
+	 * @var array
81
+	 */
82
+	protected $_fields = array();
83
+
84
+	/**
85
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
86
+	 * For example, we might create model objects intended to only be used for the duration
87
+	 * of this request and to be thrown away, and if they were accidentally saved
88
+	 * it would be a bug.
89
+	 */
90
+	protected $_allow_persist = true;
91
+
92
+	/**
93
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
94
+	 */
95
+	protected $_has_changes = false;
96
+
97
+	/**
98
+	 * @var EEM_Base
99
+	 */
100
+	protected $_model;
101
+
102
+	/**
103
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
104
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
105
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
106
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
107
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
108
+	 * array as:
109
+	 * array(
110
+	 *  'Registration_Count' => 24
111
+	 * );
112
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
113
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
114
+	 * info)
115
+	 *
116
+	 * @var array
117
+	 */
118
+	protected $custom_selection_results = array();
119
+
120
+
121
+	/**
122
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
123
+	 * play nice
124
+	 *
125
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
126
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
127
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
128
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
129
+	 *                                                         corresponding db model or not.
130
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
131
+	 *                                                         be in when instantiating a EE_Base_Class object.
132
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
133
+	 *                                                         value is the date_format and second value is the time
134
+	 *                                                         format.
135
+	 * @throws InvalidArgumentException
136
+	 * @throws InvalidInterfaceException
137
+	 * @throws InvalidDataTypeException
138
+	 * @throws EE_Error
139
+	 * @throws ReflectionException
140
+	 */
141
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
142
+	{
143
+		$className = get_class($this);
144
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
145
+		$model        = $this->get_model();
146
+		$model_fields = $model->field_settings(false);
147
+		// ensure $fieldValues is an array
148
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
149
+		// verify client code has not passed any invalid field names
150
+		foreach ($fieldValues as $field_name => $field_value) {
151
+			if (! isset($model_fields[ $field_name ])) {
152
+				throw new EE_Error(
153
+					sprintf(
154
+						esc_html__(
155
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
156
+							'event_espresso'
157
+						),
158
+						$field_name,
159
+						get_class($this),
160
+						implode(', ', array_keys($model_fields))
161
+					)
162
+				);
163
+			}
164
+		}
165
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
166
+		if (! empty($date_formats) && is_array($date_formats)) {
167
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
168
+		} else {
169
+			//set default formats for date and time
170
+			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
171
+			$this->_tm_frmt = (string) get_option('time_format', 'g:i a');
172
+		}
173
+		//if db model is instantiating
174
+		if ($bydb) {
175
+			//client code has indicated these field values are from the database
176
+			foreach ($model_fields as $fieldName => $field) {
177
+				$this->set_from_db(
178
+					$fieldName,
179
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
180
+				);
181
+			}
182
+		} else {
183
+			//we're constructing a brand
184
+			//new instance of the model object. Generally, this means we'll need to do more field validation
185
+			foreach ($model_fields as $fieldName => $field) {
186
+				$this->set(
187
+					$fieldName,
188
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null, true
189
+				);
190
+			}
191
+		}
192
+		//remember what values were passed to this constructor
193
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
194
+		//remember in entity mapper
195
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
196
+			$model->add_to_entity_map($this);
197
+		}
198
+		//setup all the relations
199
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
+				$this->_model_relations[ $relation_name ] = null;
202
+			} else {
203
+				$this->_model_relations[ $relation_name ] = array();
204
+			}
205
+		}
206
+		/**
207
+		 * Action done at the end of each model object construction
208
+		 *
209
+		 * @param EE_Base_Class $this the model object just created
210
+		 */
211
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
+	}
213
+
214
+
215
+	/**
216
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
217
+	 *
218
+	 * @return boolean
219
+	 */
220
+	public function allow_persist()
221
+	{
222
+		return $this->_allow_persist;
223
+	}
224
+
225
+
226
+	/**
227
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
228
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
229
+	 * you got new information that somehow made you change your mind.
230
+	 *
231
+	 * @param boolean $allow_persist
232
+	 * @return boolean
233
+	 */
234
+	public function set_allow_persist($allow_persist)
235
+	{
236
+		return $this->_allow_persist = $allow_persist;
237
+	}
238
+
239
+
240
+	/**
241
+	 * Gets the field's original value when this object was constructed during this request.
242
+	 * This can be helpful when determining if a model object has changed or not
243
+	 *
244
+	 * @param string $field_name
245
+	 * @return mixed|null
246
+	 * @throws ReflectionException
247
+	 * @throws InvalidArgumentException
248
+	 * @throws InvalidInterfaceException
249
+	 * @throws InvalidDataTypeException
250
+	 * @throws EE_Error
251
+	 */
252
+	public function get_original($field_name)
253
+	{
254
+		if (isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
256
+		) {
257
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
+		}
259
+		return null;
260
+	}
261
+
262
+
263
+	/**
264
+	 * @param EE_Base_Class $obj
265
+	 * @return string
266
+	 */
267
+	public function get_class($obj)
268
+	{
269
+		return get_class($obj);
270
+	}
271
+
272
+
273
+	/**
274
+	 * Overrides parent because parent expects old models.
275
+	 * This also doesn't do any validation, and won't work for serialized arrays
276
+	 *
277
+	 * @param    string $field_name
278
+	 * @param    mixed  $field_value
279
+	 * @param bool      $use_default
280
+	 * @throws InvalidArgumentException
281
+	 * @throws InvalidInterfaceException
282
+	 * @throws InvalidDataTypeException
283
+	 * @throws EE_Error
284
+	 * @throws ReflectionException
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 */
288
+	public function set($field_name, $field_value, $use_default = false)
289
+	{
290
+		// if not using default and nothing has changed, and object has already been setup (has ID),
291
+		// then don't do anything
292
+		if (
293
+			! $use_default
294
+			&& $this->_fields[ $field_name ] === $field_value
295
+			&& $this->ID()
296
+		) {
297
+			return;
298
+		}
299
+		$model              = $this->get_model();
300
+		$this->_has_changes = true;
301
+		$field_obj          = $model->field_settings_for($field_name);
302
+		if ($field_obj instanceof EE_Model_Field_Base) {
303
+			//			if ( method_exists( $field_obj, 'set_timezone' )) {
304
+			if ($field_obj instanceof EE_Datetime_Field) {
305
+				$field_obj->set_timezone($this->_timezone);
306
+				$field_obj->set_date_format($this->_dt_frmt);
307
+				$field_obj->set_time_format($this->_tm_frmt);
308
+			}
309
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
310
+			//should the value be null?
311
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
313
+				/**
314
+				 * To save having to refactor all the models, if a default value is used for a
315
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
+				 * object.
318
+				 *
319
+				 * @since 4.6.10+
320
+				 */
321
+				if (
322
+					$field_obj instanceof EE_Datetime_Field
323
+					&& $this->_fields[ $field_name ] !== null
324
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
325
+				) {
326
+					empty($this->_fields[ $field_name ])
327
+						? $this->set($field_name, time())
328
+						: $this->set($field_name, $this->_fields[ $field_name ]);
329
+				}
330
+			} else {
331
+				$this->_fields[ $field_name ] = $holder_of_value;
332
+			}
333
+			//if we're not in the constructor...
334
+			//now check if what we set was a primary key
335
+			if (
336
+				//note: props_n_values_provided_in_constructor is only set at the END of the constructor
337
+				$this->_props_n_values_provided_in_constructor
338
+				&& $field_value
339
+				&& $field_name === $model->primary_key_name()
340
+			) {
341
+				//if so, we want all this object's fields to be filled either with
342
+				//what we've explicitly set on this model
343
+				//or what we have in the db
344
+				// echo "setting primary key!";
345
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
346
+				$obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
+				foreach ($fields_on_model as $field_obj) {
348
+					if (! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
349
+						&& $field_obj->get_name() !== $field_name
350
+					) {
351
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
352
+					}
353
+				}
354
+				//oh this model object has an ID? well make sure its in the entity mapper
355
+				$model->add_to_entity_map($this);
356
+			}
357
+			//let's unset any cache for this field_name from the $_cached_properties property.
358
+			$this->_clear_cached_property($field_name);
359
+		} else {
360
+			throw new EE_Error(
361
+				sprintf(
362
+					esc_html__(
363
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
364
+						'event_espresso'
365
+					),
366
+					$field_name
367
+				)
368
+			);
369
+		}
370
+	}
371
+
372
+
373
+	/**
374
+	 * Set custom select values for model.
375
+	 *
376
+	 * @param array $custom_select_values
377
+	 */
378
+	public function setCustomSelectsValues(array $custom_select_values)
379
+	{
380
+		$this->custom_selection_results = $custom_select_values;
381
+	}
382
+
383
+
384
+	/**
385
+	 * Returns the custom select value for the provided alias if its set.
386
+	 * If not set, returns null.
387
+	 *
388
+	 * @param string $alias
389
+	 * @return string|int|float|null
390
+	 */
391
+	public function getCustomSelect($alias)
392
+	{
393
+		return isset($this->custom_selection_results[ $alias ])
394
+			? $this->custom_selection_results[ $alias ]
395
+			: null;
396
+	}
397
+
398
+
399
+	/**
400
+	 * This sets the field value on the db column if it exists for the given $column_name or
401
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
402
+	 *
403
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
404
+	 * @param string $field_name  Must be the exact column name.
405
+	 * @param mixed  $field_value The value to set.
406
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
407
+	 * @throws InvalidArgumentException
408
+	 * @throws InvalidInterfaceException
409
+	 * @throws InvalidDataTypeException
410
+	 * @throws EE_Error
411
+	 * @throws ReflectionException
412
+	 */
413
+	public function set_field_or_extra_meta($field_name, $field_value)
414
+	{
415
+		if ($this->get_model()->has_field($field_name)) {
416
+			$this->set($field_name, $field_value);
417
+			return true;
418
+		}
419
+		//ensure this object is saved first so that extra meta can be properly related.
420
+		$this->save();
421
+		return $this->update_extra_meta($field_name, $field_value);
422
+	}
423
+
424
+
425
+	/**
426
+	 * This retrieves the value of the db column set on this class or if that's not present
427
+	 * it will attempt to retrieve from extra_meta if found.
428
+	 * Example Usage:
429
+	 * Via EE_Message child class:
430
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
431
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
432
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
433
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
434
+	 * value for those extra fields dynamically via the EE_message object.
435
+	 *
436
+	 * @param  string $field_name expecting the fully qualified field name.
437
+	 * @return mixed|null  value for the field if found.  null if not found.
438
+	 * @throws ReflectionException
439
+	 * @throws InvalidArgumentException
440
+	 * @throws InvalidInterfaceException
441
+	 * @throws InvalidDataTypeException
442
+	 * @throws EE_Error
443
+	 */
444
+	public function get_field_or_extra_meta($field_name)
445
+	{
446
+		if ($this->get_model()->has_field($field_name)) {
447
+			$column_value = $this->get($field_name);
448
+		} else {
449
+			//This isn't a column in the main table, let's see if it is in the extra meta.
450
+			$column_value = $this->get_extra_meta($field_name, true, null);
451
+		}
452
+		return $column_value;
453
+	}
454
+
455
+
456
+	/**
457
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
458
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
459
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
460
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
461
+	 *
462
+	 * @access public
463
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
464
+	 * @return void
465
+	 * @throws InvalidArgumentException
466
+	 * @throws InvalidInterfaceException
467
+	 * @throws InvalidDataTypeException
468
+	 * @throws EE_Error
469
+	 * @throws ReflectionException
470
+	 */
471
+	public function set_timezone($timezone = '')
472
+	{
473
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
474
+		//make sure we clear all cached properties because they won't be relevant now
475
+		$this->_clear_cached_properties();
476
+		//make sure we update field settings and the date for all EE_Datetime_Fields
477
+		$model_fields = $this->get_model()->field_settings(false);
478
+		foreach ($model_fields as $field_name => $field_obj) {
479
+			if ($field_obj instanceof EE_Datetime_Field) {
480
+				$field_obj->set_timezone($this->_timezone);
481
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
482
+					$this->_fields[ $field_name ]->setTimezone(new DateTimeZone($this->_timezone));
483
+					// workaround for php datetime bug
484
+					// @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
485
+					$this->_fields[$field_name]->getTimestamp();
486
+				}
487
+			}
488
+		}
489
+	}
490
+
491
+
492
+	/**
493
+	 * This just returns whatever is set for the current timezone.
494
+	 *
495
+	 * @access public
496
+	 * @return string timezone string
497
+	 */
498
+	public function get_timezone()
499
+	{
500
+		return $this->_timezone;
501
+	}
502
+
503
+
504
+	/**
505
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
506
+	 * internally instead of wp set date format options
507
+	 *
508
+	 * @since 4.6
509
+	 * @param string $format should be a format recognizable by PHP date() functions.
510
+	 */
511
+	public function set_date_format($format)
512
+	{
513
+		$this->_dt_frmt = $format;
514
+		//clear cached_properties because they won't be relevant now.
515
+		$this->_clear_cached_properties();
516
+	}
517
+
518
+
519
+	/**
520
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
521
+	 * class internally instead of wp set time format options.
522
+	 *
523
+	 * @since 4.6
524
+	 * @param string $format should be a format recognizable by PHP date() functions.
525
+	 */
526
+	public function set_time_format($format)
527
+	{
528
+		$this->_tm_frmt = $format;
529
+		//clear cached_properties because they won't be relevant now.
530
+		$this->_clear_cached_properties();
531
+	}
532
+
533
+
534
+	/**
535
+	 * This returns the current internal set format for the date and time formats.
536
+	 *
537
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
538
+	 *                             where the first value is the date format and the second value is the time format.
539
+	 * @return mixed string|array
540
+	 */
541
+	public function get_format($full = true)
542
+	{
543
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
544
+	}
545
+
546
+
547
+	/**
548
+	 * cache
549
+	 * stores the passed model object on the current model object.
550
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
551
+	 *
552
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
553
+	 *                                       'Registration' associated with this model object
554
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
555
+	 *                                       that could be a payment or a registration)
556
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
557
+	 *                                       items which will be stored in an array on this object
558
+	 * @throws ReflectionException
559
+	 * @throws InvalidArgumentException
560
+	 * @throws InvalidInterfaceException
561
+	 * @throws InvalidDataTypeException
562
+	 * @throws EE_Error
563
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
564
+	 *                                       related thing, no array)
565
+	 */
566
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
567
+	{
568
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
569
+		if (! $object_to_cache instanceof EE_Base_Class) {
570
+			return false;
571
+		}
572
+		// also get "how" the object is related, or throw an error
573
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
574
+			throw new EE_Error(
575
+				sprintf(
576
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
577
+					$relationName,
578
+					get_class($this)
579
+				)
580
+			);
581
+		}
582
+		// how many things are related ?
583
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
584
+			// if it's a "belongs to" relationship, then there's only one related model object
585
+			// eg, if this is a registration, there's only 1 attendee for it
586
+			// so for these model objects just set it to be cached
587
+			$this->_model_relations[ $relationName ] = $object_to_cache;
588
+			$return                                  = true;
589
+		} else {
590
+			// otherwise, this is the "many" side of a one to many relationship,
591
+			// so we'll add the object to the array of related objects for that type.
592
+			// eg: if this is an event, there are many registrations for that event,
593
+			// so we cache the registrations in an array
594
+			if (! is_array($this->_model_relations[ $relationName ])) {
595
+				// if for some reason, the cached item is a model object,
596
+				// then stick that in the array, otherwise start with an empty array
597
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
598
+														   instanceof
599
+														   EE_Base_Class
600
+					? array($this->_model_relations[ $relationName ]) : array();
601
+			}
602
+			// first check for a cache_id which is normally empty
603
+			if (! empty($cache_id)) {
604
+				// if the cache_id exists, then it means we are purposely trying to cache this
605
+				// with a known key that can then be used to retrieve the object later on
606
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
607
+				$return                                               = $cache_id;
608
+			} elseif ($object_to_cache->ID()) {
609
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
610
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
611
+				$return                                                            = $object_to_cache->ID();
612
+			} else {
613
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
614
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
615
+				// move the internal pointer to the end of the array
616
+				end($this->_model_relations[ $relationName ]);
617
+				// and grab the key so that we can return it
618
+				$return = key($this->_model_relations[ $relationName ]);
619
+			}
620
+		}
621
+		return $return;
622
+	}
623
+
624
+
625
+	/**
626
+	 * For adding an item to the cached_properties property.
627
+	 *
628
+	 * @access protected
629
+	 * @param string      $fieldname the property item the corresponding value is for.
630
+	 * @param mixed       $value     The value we are caching.
631
+	 * @param string|null $cache_type
632
+	 * @return void
633
+	 * @throws ReflectionException
634
+	 * @throws InvalidArgumentException
635
+	 * @throws InvalidInterfaceException
636
+	 * @throws InvalidDataTypeException
637
+	 * @throws EE_Error
638
+	 */
639
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
640
+	{
641
+		//first make sure this property exists
642
+		$this->get_model()->field_settings_for($fieldname);
643
+		$cache_type                                            = empty($cache_type) ? 'standard' : $cache_type;
644
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
645
+	}
646
+
647
+
648
+	/**
649
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
650
+	 * This also SETS the cache if we return the actual property!
651
+	 *
652
+	 * @param string $fieldname        the name of the property we're trying to retrieve
653
+	 * @param bool   $pretty
654
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
655
+	 *                                 (in cases where the same property may be used for different outputs
656
+	 *                                 - i.e. datetime, money etc.)
657
+	 *                                 It can also accept certain pre-defined "schema" strings
658
+	 *                                 to define how to output the property.
659
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
660
+	 * @return mixed                   whatever the value for the property is we're retrieving
661
+	 * @throws ReflectionException
662
+	 * @throws InvalidArgumentException
663
+	 * @throws InvalidInterfaceException
664
+	 * @throws InvalidDataTypeException
665
+	 * @throws EE_Error
666
+	 */
667
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
668
+	{
669
+		//verify the field exists
670
+		$model = $this->get_model();
671
+		$model->field_settings_for($fieldname);
672
+		$cache_type = $pretty ? 'pretty' : 'standard';
673
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
674
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
675
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
676
+		}
677
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
678
+		$this->_set_cached_property($fieldname, $value, $cache_type);
679
+		return $value;
680
+	}
681
+
682
+
683
+	/**
684
+	 * If the cache didn't fetch the needed item, this fetches it.
685
+	 *
686
+	 * @param string $fieldname
687
+	 * @param bool   $pretty
688
+	 * @param string $extra_cache_ref
689
+	 * @return mixed
690
+	 * @throws InvalidArgumentException
691
+	 * @throws InvalidInterfaceException
692
+	 * @throws InvalidDataTypeException
693
+	 * @throws EE_Error
694
+	 * @throws ReflectionException
695
+	 */
696
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
697
+	{
698
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
699
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
700
+		if ($field_obj instanceof EE_Datetime_Field) {
701
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
702
+		}
703
+		if (! isset($this->_fields[ $fieldname ])) {
704
+			$this->_fields[ $fieldname ] = null;
705
+		}
706
+		$value = $pretty
707
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
708
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
709
+		return $value;
710
+	}
711
+
712
+
713
+	/**
714
+	 * set timezone, formats, and output for EE_Datetime_Field objects
715
+	 *
716
+	 * @param \EE_Datetime_Field $datetime_field
717
+	 * @param bool               $pretty
718
+	 * @param null               $date_or_time
719
+	 * @return void
720
+	 * @throws InvalidArgumentException
721
+	 * @throws InvalidInterfaceException
722
+	 * @throws InvalidDataTypeException
723
+	 * @throws EE_Error
724
+	 */
725
+	protected function _prepare_datetime_field(
726
+		EE_Datetime_Field $datetime_field,
727
+		$pretty = false,
728
+		$date_or_time = null
729
+	) {
730
+		$datetime_field->set_timezone($this->_timezone);
731
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
732
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
733
+		//set the output returned
734
+		switch ($date_or_time) {
735
+			case 'D' :
736
+				$datetime_field->set_date_time_output('date');
737
+				break;
738
+			case 'T' :
739
+				$datetime_field->set_date_time_output('time');
740
+				break;
741
+			default :
742
+				$datetime_field->set_date_time_output();
743
+		}
744
+	}
745
+
746
+
747
+	/**
748
+	 * This just takes care of clearing out the cached_properties
749
+	 *
750
+	 * @return void
751
+	 */
752
+	protected function _clear_cached_properties()
753
+	{
754
+		$this->_cached_properties = array();
755
+	}
756
+
757
+
758
+	/**
759
+	 * This just clears out ONE property if it exists in the cache
760
+	 *
761
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
762
+	 * @return void
763
+	 */
764
+	protected function _clear_cached_property($property_name)
765
+	{
766
+		if (isset($this->_cached_properties[ $property_name ])) {
767
+			unset($this->_cached_properties[ $property_name ]);
768
+		}
769
+	}
770
+
771
+
772
+	/**
773
+	 * Ensures that this related thing is a model object.
774
+	 *
775
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
776
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
777
+	 * @return EE_Base_Class
778
+	 * @throws ReflectionException
779
+	 * @throws InvalidArgumentException
780
+	 * @throws InvalidInterfaceException
781
+	 * @throws InvalidDataTypeException
782
+	 * @throws EE_Error
783
+	 */
784
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
785
+	{
786
+		$other_model_instance = self::_get_model_instance_with_name(
787
+			self::_get_model_classname($model_name),
788
+			$this->_timezone
789
+		);
790
+		return $other_model_instance->ensure_is_obj($object_or_id);
791
+	}
792
+
793
+
794
+	/**
795
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
796
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
797
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
798
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
799
+	 *
800
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
801
+	 *                                                     Eg 'Registration'
802
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
803
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
804
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
805
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
806
+	 *                                                     this is HasMany or HABTM.
807
+	 * @throws ReflectionException
808
+	 * @throws InvalidArgumentException
809
+	 * @throws InvalidInterfaceException
810
+	 * @throws InvalidDataTypeException
811
+	 * @throws EE_Error
812
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
813
+	 *                                                     relation from all
814
+	 */
815
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
816
+	{
817
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
818
+		$index_in_cache        = '';
819
+		if (! $relationship_to_model) {
820
+			throw new EE_Error(
821
+				sprintf(
822
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
823
+					$relationName,
824
+					get_class($this)
825
+				)
826
+			);
827
+		}
828
+		if ($clear_all) {
829
+			$obj_removed                             = true;
830
+			$this->_model_relations[ $relationName ] = null;
831
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
832
+			$obj_removed                             = $this->_model_relations[ $relationName ];
833
+			$this->_model_relations[ $relationName ] = null;
834
+		} else {
835
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
836
+				&& $object_to_remove_or_index_into_array->ID()
837
+			) {
838
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
839
+				if (is_array($this->_model_relations[ $relationName ])
840
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
841
+				) {
842
+					$index_found_at = null;
843
+					//find this object in the array even though it has a different key
844
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
845
+						/** @noinspection TypeUnsafeComparisonInspection */
846
+						if (
847
+							$obj instanceof EE_Base_Class
848
+							&& (
849
+								$obj == $object_to_remove_or_index_into_array
850
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
851
+							)
852
+						) {
853
+							$index_found_at = $index;
854
+							break;
855
+						}
856
+					}
857
+					if ($index_found_at) {
858
+						$index_in_cache = $index_found_at;
859
+					} else {
860
+						//it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
861
+						//if it wasn't in it to begin with. So we're done
862
+						return $object_to_remove_or_index_into_array;
863
+					}
864
+				}
865
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
866
+				//so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
867
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
868
+					/** @noinspection TypeUnsafeComparisonInspection */
869
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
870
+						$index_in_cache = $index;
871
+					}
872
+				}
873
+			} else {
874
+				$index_in_cache = $object_to_remove_or_index_into_array;
875
+			}
876
+			//supposedly we've found it. But it could just be that the client code
877
+			//provided a bad index/object
878
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
879
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
880
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
881
+			} else {
882
+				//that thing was never cached anyways.
883
+				$obj_removed = null;
884
+			}
885
+		}
886
+		return $obj_removed;
887
+	}
888
+
889
+
890
+	/**
891
+	 * update_cache_after_object_save
892
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
893
+	 * obtained after being saved to the db
894
+	 *
895
+	 * @param string        $relationName       - the type of object that is cached
896
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
897
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
898
+	 * @return boolean TRUE on success, FALSE on fail
899
+	 * @throws ReflectionException
900
+	 * @throws InvalidArgumentException
901
+	 * @throws InvalidInterfaceException
902
+	 * @throws InvalidDataTypeException
903
+	 * @throws EE_Error
904
+	 */
905
+	public function update_cache_after_object_save(
906
+		$relationName,
907
+		EE_Base_Class $newly_saved_object,
908
+		$current_cache_id = ''
909
+	) {
910
+		// verify that incoming object is of the correct type
911
+		$obj_class = 'EE_' . $relationName;
912
+		if ($newly_saved_object instanceof $obj_class) {
913
+			/* @type EE_Base_Class $newly_saved_object */
914
+			// now get the type of relation
915
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
916
+			// if this is a 1:1 relationship
917
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
918
+				// then just replace the cached object with the newly saved object
919
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
920
+				return true;
921
+				// or if it's some kind of sordid feral polyamorous relationship...
922
+			}
923
+			if (is_array($this->_model_relations[ $relationName ])
924
+					  && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
925
+			) {
926
+				// then remove the current cached item
927
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
928
+				// and cache the newly saved object using it's new ID
929
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
930
+				return true;
931
+			}
932
+		}
933
+		return false;
934
+	}
935
+
936
+
937
+	/**
938
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
939
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
940
+	 *
941
+	 * @param string $relationName
942
+	 * @return EE_Base_Class
943
+	 */
944
+	public function get_one_from_cache($relationName)
945
+	{
946
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
947
+			? $this->_model_relations[ $relationName ]
948
+			: null;
949
+		if (is_array($cached_array_or_object)) {
950
+			return array_shift($cached_array_or_object);
951
+		}
952
+		return $cached_array_or_object;
953
+	}
954
+
955
+
956
+	/**
957
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
958
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
959
+	 *
960
+	 * @param string $relationName
961
+	 * @throws ReflectionException
962
+	 * @throws InvalidArgumentException
963
+	 * @throws InvalidInterfaceException
964
+	 * @throws InvalidDataTypeException
965
+	 * @throws EE_Error
966
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
967
+	 */
968
+	public function get_all_from_cache($relationName)
969
+	{
970
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
971
+		// if the result is not an array, but exists, make it an array
972
+		$objects = is_array($objects) ? $objects : array($objects);
973
+		//bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
974
+		//basically, if this model object was stored in the session, and these cached model objects
975
+		//already have IDs, let's make sure they're in their model's entity mapper
976
+		//otherwise we will have duplicates next time we call
977
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
978
+		$model = EE_Registry::instance()->load_model($relationName);
979
+		foreach ($objects as $model_object) {
980
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
981
+				//ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
982
+				if ($model_object->ID()) {
983
+					$model->add_to_entity_map($model_object);
984
+				}
985
+			} else {
986
+				throw new EE_Error(
987
+					sprintf(
988
+						esc_html__(
989
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
990
+							'event_espresso'
991
+						),
992
+						$relationName,
993
+						gettype($model_object)
994
+					)
995
+				);
996
+			}
997
+		}
998
+		return $objects;
999
+	}
1000
+
1001
+
1002
+	/**
1003
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1004
+	 * matching the given query conditions.
1005
+	 *
1006
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1007
+	 * @param int   $limit              How many objects to return.
1008
+	 * @param array $query_params       Any additional conditions on the query.
1009
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1010
+	 *                                  you can indicate just the columns you want returned
1011
+	 * @return array|EE_Base_Class[]
1012
+	 * @throws ReflectionException
1013
+	 * @throws InvalidArgumentException
1014
+	 * @throws InvalidInterfaceException
1015
+	 * @throws InvalidDataTypeException
1016
+	 * @throws EE_Error
1017
+	 */
1018
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1019
+	{
1020
+		$model         = $this->get_model();
1021
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1022
+			? $model->get_primary_key_field()->get_name()
1023
+			: $field_to_order_by;
1024
+		$current_value = ! empty($field) ? $this->get($field) : null;
1025
+		if (empty($field) || empty($current_value)) {
1026
+			return array();
1027
+		}
1028
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1029
+	}
1030
+
1031
+
1032
+	/**
1033
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1034
+	 * matching the given query conditions.
1035
+	 *
1036
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1037
+	 * @param int   $limit              How many objects to return.
1038
+	 * @param array $query_params       Any additional conditions on the query.
1039
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1040
+	 *                                  you can indicate just the columns you want returned
1041
+	 * @return array|EE_Base_Class[]
1042
+	 * @throws ReflectionException
1043
+	 * @throws InvalidArgumentException
1044
+	 * @throws InvalidInterfaceException
1045
+	 * @throws InvalidDataTypeException
1046
+	 * @throws EE_Error
1047
+	 */
1048
+	public function previous_x(
1049
+		$field_to_order_by = null,
1050
+		$limit = 1,
1051
+		$query_params = array(),
1052
+		$columns_to_select = null
1053
+	) {
1054
+		$model         = $this->get_model();
1055
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1056
+			? $model->get_primary_key_field()->get_name()
1057
+			: $field_to_order_by;
1058
+		$current_value = ! empty($field) ? $this->get($field) : null;
1059
+		if (empty($field) || empty($current_value)) {
1060
+			return array();
1061
+		}
1062
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1063
+	}
1064
+
1065
+
1066
+	/**
1067
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1068
+	 * matching the given query conditions.
1069
+	 *
1070
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1071
+	 * @param array $query_params       Any additional conditions on the query.
1072
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1073
+	 *                                  you can indicate just the columns you want returned
1074
+	 * @return array|EE_Base_Class
1075
+	 * @throws ReflectionException
1076
+	 * @throws InvalidArgumentException
1077
+	 * @throws InvalidInterfaceException
1078
+	 * @throws InvalidDataTypeException
1079
+	 * @throws EE_Error
1080
+	 */
1081
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1082
+	{
1083
+		$model         = $this->get_model();
1084
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1085
+			? $model->get_primary_key_field()->get_name()
1086
+			: $field_to_order_by;
1087
+		$current_value = ! empty($field) ? $this->get($field) : null;
1088
+		if (empty($field) || empty($current_value)) {
1089
+			return array();
1090
+		}
1091
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1092
+	}
1093
+
1094
+
1095
+	/**
1096
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1097
+	 * matching the given query conditions.
1098
+	 *
1099
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1100
+	 * @param array $query_params       Any additional conditions on the query.
1101
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1102
+	 *                                  you can indicate just the column you want returned
1103
+	 * @return array|EE_Base_Class
1104
+	 * @throws ReflectionException
1105
+	 * @throws InvalidArgumentException
1106
+	 * @throws InvalidInterfaceException
1107
+	 * @throws InvalidDataTypeException
1108
+	 * @throws EE_Error
1109
+	 */
1110
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1111
+	{
1112
+		$model         = $this->get_model();
1113
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1114
+			? $model->get_primary_key_field()->get_name()
1115
+			: $field_to_order_by;
1116
+		$current_value = ! empty($field) ? $this->get($field) : null;
1117
+		if (empty($field) || empty($current_value)) {
1118
+			return array();
1119
+		}
1120
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1121
+	}
1122
+
1123
+
1124
+	/**
1125
+	 * Overrides parent because parent expects old models.
1126
+	 * This also doesn't do any validation, and won't work for serialized arrays
1127
+	 *
1128
+	 * @param string $field_name
1129
+	 * @param mixed  $field_value_from_db
1130
+	 * @throws ReflectionException
1131
+	 * @throws InvalidArgumentException
1132
+	 * @throws InvalidInterfaceException
1133
+	 * @throws InvalidDataTypeException
1134
+	 * @throws EE_Error
1135
+	 */
1136
+	public function set_from_db($field_name, $field_value_from_db)
1137
+	{
1138
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1139
+		if ($field_obj instanceof EE_Model_Field_Base) {
1140
+			//you would think the DB has no NULLs for non-null label fields right? wrong!
1141
+			//eg, a CPT model object could have an entry in the posts table, but no
1142
+			//entry in the meta table. Meaning that all its columns in the meta table
1143
+			//are null! yikes! so when we find one like that, use defaults for its meta columns
1144
+			if ($field_value_from_db === null) {
1145
+				if ($field_obj->is_nullable()) {
1146
+					//if the field allows nulls, then let it be null
1147
+					$field_value = null;
1148
+				} else {
1149
+					$field_value = $field_obj->get_default_value();
1150
+				}
1151
+			} else {
1152
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1153
+			}
1154
+			$this->_fields[ $field_name ] = $field_value;
1155
+			$this->_clear_cached_property($field_name);
1156
+		}
1157
+	}
1158
+
1159
+
1160
+	/**
1161
+	 * verifies that the specified field is of the correct type
1162
+	 *
1163
+	 * @param string $field_name
1164
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1165
+	 *                                (in cases where the same property may be used for different outputs
1166
+	 *                                - i.e. datetime, money etc.)
1167
+	 * @return mixed
1168
+	 * @throws ReflectionException
1169
+	 * @throws InvalidArgumentException
1170
+	 * @throws InvalidInterfaceException
1171
+	 * @throws InvalidDataTypeException
1172
+	 * @throws EE_Error
1173
+	 */
1174
+	public function get($field_name, $extra_cache_ref = null)
1175
+	{
1176
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1177
+	}
1178
+
1179
+
1180
+	/**
1181
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1182
+	 *
1183
+	 * @param  string $field_name A valid fieldname
1184
+	 * @return mixed              Whatever the raw value stored on the property is.
1185
+	 * @throws ReflectionException
1186
+	 * @throws InvalidArgumentException
1187
+	 * @throws InvalidInterfaceException
1188
+	 * @throws InvalidDataTypeException
1189
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1190
+	 */
1191
+	public function get_raw($field_name)
1192
+	{
1193
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1194
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1195
+			? $this->_fields[ $field_name ]->format('U')
1196
+			: $this->_fields[ $field_name ];
1197
+	}
1198
+
1199
+
1200
+	/**
1201
+	 * This is used to return the internal DateTime object used for a field that is a
1202
+	 * EE_Datetime_Field.
1203
+	 *
1204
+	 * @param string $field_name               The field name retrieving the DateTime object.
1205
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1206
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1207
+	 *                                         EE_Datetime_Field and but the field value is null, then
1208
+	 *                                         just null is returned (because that indicates that likely
1209
+	 *                                         this field is nullable).
1210
+	 * @throws InvalidArgumentException
1211
+	 * @throws InvalidDataTypeException
1212
+	 * @throws InvalidInterfaceException
1213
+	 * @throws ReflectionException
1214
+	 */
1215
+	public function get_DateTime_object($field_name)
1216
+	{
1217
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1218
+		if (! $field_settings instanceof EE_Datetime_Field) {
1219
+			EE_Error::add_error(
1220
+				sprintf(
1221
+					esc_html__(
1222
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1223
+						'event_espresso'
1224
+					),
1225
+					$field_name
1226
+				),
1227
+				__FILE__,
1228
+				__FUNCTION__,
1229
+				__LINE__
1230
+			);
1231
+			return false;
1232
+		}
1233
+		return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1234
+			? clone $this->_fields[$field_name]
1235
+			: null;
1236
+	}
1237
+
1238
+
1239
+	/**
1240
+	 * To be used in template to immediately echo out the value, and format it for output.
1241
+	 * Eg, should call stripslashes and whatnot before echoing
1242
+	 *
1243
+	 * @param string $field_name      the name of the field as it appears in the DB
1244
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1245
+	 *                                (in cases where the same property may be used for different outputs
1246
+	 *                                - i.e. datetime, money etc.)
1247
+	 * @return void
1248
+	 * @throws ReflectionException
1249
+	 * @throws InvalidArgumentException
1250
+	 * @throws InvalidInterfaceException
1251
+	 * @throws InvalidDataTypeException
1252
+	 * @throws EE_Error
1253
+	 */
1254
+	public function e($field_name, $extra_cache_ref = null)
1255
+	{
1256
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1257
+	}
1258
+
1259
+
1260
+	/**
1261
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1262
+	 * can be easily used as the value of form input.
1263
+	 *
1264
+	 * @param string $field_name
1265
+	 * @return void
1266
+	 * @throws ReflectionException
1267
+	 * @throws InvalidArgumentException
1268
+	 * @throws InvalidInterfaceException
1269
+	 * @throws InvalidDataTypeException
1270
+	 * @throws EE_Error
1271
+	 */
1272
+	public function f($field_name)
1273
+	{
1274
+		$this->e($field_name, 'form_input');
1275
+	}
1276
+
1277
+
1278
+	/**
1279
+	 * Same as `f()` but just returns the value instead of echoing it
1280
+	 *
1281
+	 * @param string $field_name
1282
+	 * @return string
1283
+	 * @throws ReflectionException
1284
+	 * @throws InvalidArgumentException
1285
+	 * @throws InvalidInterfaceException
1286
+	 * @throws InvalidDataTypeException
1287
+	 * @throws EE_Error
1288
+	 */
1289
+	public function get_f($field_name)
1290
+	{
1291
+		return (string) $this->get_pretty($field_name, 'form_input');
1292
+	}
1293
+
1294
+
1295
+	/**
1296
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1297
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1298
+	 * to see what options are available.
1299
+	 *
1300
+	 * @param string $field_name
1301
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1302
+	 *                                (in cases where the same property may be used for different outputs
1303
+	 *                                - i.e. datetime, money etc.)
1304
+	 * @return mixed
1305
+	 * @throws ReflectionException
1306
+	 * @throws InvalidArgumentException
1307
+	 * @throws InvalidInterfaceException
1308
+	 * @throws InvalidDataTypeException
1309
+	 * @throws EE_Error
1310
+	 */
1311
+	public function get_pretty($field_name, $extra_cache_ref = null)
1312
+	{
1313
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1314
+	}
1315
+
1316
+
1317
+	/**
1318
+	 * This simply returns the datetime for the given field name
1319
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1320
+	 * (and the equivalent e_date, e_time, e_datetime).
1321
+	 *
1322
+	 * @access   protected
1323
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1324
+	 * @param string   $dt_frmt      valid datetime format used for date
1325
+	 *                               (if '' then we just use the default on the field,
1326
+	 *                               if NULL we use the last-used format)
1327
+	 * @param string   $tm_frmt      Same as above except this is for time format
1328
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1329
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1330
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1331
+	 *                               if field is not a valid dtt field, or void if echoing
1332
+	 * @throws ReflectionException
1333
+	 * @throws InvalidArgumentException
1334
+	 * @throws InvalidInterfaceException
1335
+	 * @throws InvalidDataTypeException
1336
+	 * @throws EE_Error
1337
+	 */
1338
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1339
+	{
1340
+		// clear cached property
1341
+		$this->_clear_cached_property($field_name);
1342
+		//reset format properties because they are used in get()
1343
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1344
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1345
+		if ($echo) {
1346
+			$this->e($field_name, $date_or_time);
1347
+			return '';
1348
+		}
1349
+		return $this->get($field_name, $date_or_time);
1350
+	}
1351
+
1352
+
1353
+	/**
1354
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1355
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1356
+	 * other echoes the pretty value for dtt)
1357
+	 *
1358
+	 * @param  string $field_name name of model object datetime field holding the value
1359
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1360
+	 * @return string            datetime value formatted
1361
+	 * @throws ReflectionException
1362
+	 * @throws InvalidArgumentException
1363
+	 * @throws InvalidInterfaceException
1364
+	 * @throws InvalidDataTypeException
1365
+	 * @throws EE_Error
1366
+	 */
1367
+	public function get_date($field_name, $format = '')
1368
+	{
1369
+		return $this->_get_datetime($field_name, $format, null, 'D');
1370
+	}
1371
+
1372
+
1373
+	/**
1374
+	 * @param        $field_name
1375
+	 * @param string $format
1376
+	 * @throws ReflectionException
1377
+	 * @throws InvalidArgumentException
1378
+	 * @throws InvalidInterfaceException
1379
+	 * @throws InvalidDataTypeException
1380
+	 * @throws EE_Error
1381
+	 */
1382
+	public function e_date($field_name, $format = '')
1383
+	{
1384
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1385
+	}
1386
+
1387
+
1388
+	/**
1389
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1390
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1391
+	 * other echoes the pretty value for dtt)
1392
+	 *
1393
+	 * @param  string $field_name name of model object datetime field holding the value
1394
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1395
+	 * @return string             datetime value formatted
1396
+	 * @throws ReflectionException
1397
+	 * @throws InvalidArgumentException
1398
+	 * @throws InvalidInterfaceException
1399
+	 * @throws InvalidDataTypeException
1400
+	 * @throws EE_Error
1401
+	 */
1402
+	public function get_time($field_name, $format = '')
1403
+	{
1404
+		return $this->_get_datetime($field_name, null, $format, 'T');
1405
+	}
1406
+
1407
+
1408
+	/**
1409
+	 * @param        $field_name
1410
+	 * @param string $format
1411
+	 * @throws ReflectionException
1412
+	 * @throws InvalidArgumentException
1413
+	 * @throws InvalidInterfaceException
1414
+	 * @throws InvalidDataTypeException
1415
+	 * @throws EE_Error
1416
+	 */
1417
+	public function e_time($field_name, $format = '')
1418
+	{
1419
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1420
+	}
1421
+
1422
+
1423
+	/**
1424
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1425
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1426
+	 * other echoes the pretty value for dtt)
1427
+	 *
1428
+	 * @param  string $field_name name of model object datetime field holding the value
1429
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1430
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1431
+	 * @return string             datetime value formatted
1432
+	 * @throws ReflectionException
1433
+	 * @throws InvalidArgumentException
1434
+	 * @throws InvalidInterfaceException
1435
+	 * @throws InvalidDataTypeException
1436
+	 * @throws EE_Error
1437
+	 */
1438
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1439
+	{
1440
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1441
+	}
1442
+
1443
+
1444
+	/**
1445
+	 * @param string $field_name
1446
+	 * @param string $dt_frmt
1447
+	 * @param string $tm_frmt
1448
+	 * @throws ReflectionException
1449
+	 * @throws InvalidArgumentException
1450
+	 * @throws InvalidInterfaceException
1451
+	 * @throws InvalidDataTypeException
1452
+	 * @throws EE_Error
1453
+	 */
1454
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1455
+	{
1456
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1457
+	}
1458
+
1459
+
1460
+	/**
1461
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1462
+	 *
1463
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1464
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1465
+	 *                           on the object will be used.
1466
+	 * @return string Date and time string in set locale or false if no field exists for the given
1467
+	 * @throws ReflectionException
1468
+	 * @throws InvalidArgumentException
1469
+	 * @throws InvalidInterfaceException
1470
+	 * @throws InvalidDataTypeException
1471
+	 * @throws EE_Error
1472
+	 *                           field name.
1473
+	 */
1474
+	public function get_i18n_datetime($field_name, $format = '')
1475
+	{
1476
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1477
+		return date_i18n(
1478
+			$format,
1479
+			EEH_DTT_Helper::get_timestamp_with_offset(
1480
+				$this->get_raw($field_name),
1481
+				$this->_timezone
1482
+			)
1483
+		);
1484
+	}
1485
+
1486
+
1487
+	/**
1488
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1489
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1490
+	 * thrown.
1491
+	 *
1492
+	 * @param  string $field_name The field name being checked
1493
+	 * @throws ReflectionException
1494
+	 * @throws InvalidArgumentException
1495
+	 * @throws InvalidInterfaceException
1496
+	 * @throws InvalidDataTypeException
1497
+	 * @throws EE_Error
1498
+	 * @return EE_Datetime_Field
1499
+	 */
1500
+	protected function _get_dtt_field_settings($field_name)
1501
+	{
1502
+		$field = $this->get_model()->field_settings_for($field_name);
1503
+		//check if field is dtt
1504
+		if ($field instanceof EE_Datetime_Field) {
1505
+			return $field;
1506
+		}
1507
+		throw new EE_Error(
1508
+			sprintf(
1509
+				esc_html__(
1510
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1511
+					'event_espresso'
1512
+				),
1513
+				$field_name,
1514
+				self::_get_model_classname(get_class($this))
1515
+			)
1516
+		);
1517
+	}
1518
+
1519
+
1520
+
1521
+
1522
+	/**
1523
+	 * NOTE ABOUT BELOW:
1524
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1525
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1526
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1527
+	 * method and make sure you send the entire datetime value for setting.
1528
+	 */
1529
+	/**
1530
+	 * sets the time on a datetime property
1531
+	 *
1532
+	 * @access protected
1533
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1534
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1535
+	 * @throws ReflectionException
1536
+	 * @throws InvalidArgumentException
1537
+	 * @throws InvalidInterfaceException
1538
+	 * @throws InvalidDataTypeException
1539
+	 * @throws EE_Error
1540
+	 */
1541
+	protected function _set_time_for($time, $fieldname)
1542
+	{
1543
+		$this->_set_date_time('T', $time, $fieldname);
1544
+	}
1545
+
1546
+
1547
+	/**
1548
+	 * sets the date on a datetime property
1549
+	 *
1550
+	 * @access protected
1551
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1552
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1553
+	 * @throws ReflectionException
1554
+	 * @throws InvalidArgumentException
1555
+	 * @throws InvalidInterfaceException
1556
+	 * @throws InvalidDataTypeException
1557
+	 * @throws EE_Error
1558
+	 */
1559
+	protected function _set_date_for($date, $fieldname)
1560
+	{
1561
+		$this->_set_date_time('D', $date, $fieldname);
1562
+	}
1563
+
1564
+
1565
+	/**
1566
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1567
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1568
+	 *
1569
+	 * @access protected
1570
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1571
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1572
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1573
+	 *                                        EE_Datetime_Field property)
1574
+	 * @throws ReflectionException
1575
+	 * @throws InvalidArgumentException
1576
+	 * @throws InvalidInterfaceException
1577
+	 * @throws InvalidDataTypeException
1578
+	 * @throws EE_Error
1579
+	 */
1580
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1581
+	{
1582
+		$field = $this->_get_dtt_field_settings($fieldname);
1583
+		$field->set_timezone($this->_timezone);
1584
+		$field->set_date_format($this->_dt_frmt);
1585
+		$field->set_time_format($this->_tm_frmt);
1586
+		switch ($what) {
1587
+			case 'T' :
1588
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1589
+					$datetime_value,
1590
+					$this->_fields[ $fieldname ]
1591
+				);
1592
+				break;
1593
+			case 'D' :
1594
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1595
+					$datetime_value,
1596
+					$this->_fields[ $fieldname ]
1597
+				);
1598
+				break;
1599
+			case 'B' :
1600
+				$this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1601
+				break;
1602
+		}
1603
+		$this->_clear_cached_property($fieldname);
1604
+	}
1605
+
1606
+
1607
+	/**
1608
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1609
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1610
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1611
+	 * that could lead to some unexpected results!
1612
+	 *
1613
+	 * @access public
1614
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1615
+	 *                                         value being returned.
1616
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1617
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1618
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1619
+	 * @param string $append                   You can include something to append on the timestamp
1620
+	 * @throws ReflectionException
1621
+	 * @throws InvalidArgumentException
1622
+	 * @throws InvalidInterfaceException
1623
+	 * @throws InvalidDataTypeException
1624
+	 * @throws EE_Error
1625
+	 * @return string timestamp
1626
+	 */
1627
+	public function display_in_my_timezone(
1628
+		$field_name,
1629
+		$callback = 'get_datetime',
1630
+		$args = null,
1631
+		$prepend = '',
1632
+		$append = ''
1633
+	) {
1634
+		$timezone = EEH_DTT_Helper::get_timezone();
1635
+		if ($timezone === $this->_timezone) {
1636
+			return '';
1637
+		}
1638
+		$original_timezone = $this->_timezone;
1639
+		$this->set_timezone($timezone);
1640
+		$fn   = (array) $field_name;
1641
+		$args = array_merge($fn, (array) $args);
1642
+		if (! method_exists($this, $callback)) {
1643
+			throw new EE_Error(
1644
+				sprintf(
1645
+					esc_html__(
1646
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1647
+						'event_espresso'
1648
+					),
1649
+					$callback
1650
+				)
1651
+			);
1652
+		}
1653
+		$args   = (array) $args;
1654
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1655
+		$this->set_timezone($original_timezone);
1656
+		return $return;
1657
+	}
1658
+
1659
+
1660
+	/**
1661
+	 * Deletes this model object.
1662
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1663
+	 * override
1664
+	 * `EE_Base_Class::_delete` NOT this class.
1665
+	 *
1666
+	 * @return boolean | int
1667
+	 * @throws ReflectionException
1668
+	 * @throws InvalidArgumentException
1669
+	 * @throws InvalidInterfaceException
1670
+	 * @throws InvalidDataTypeException
1671
+	 * @throws EE_Error
1672
+	 */
1673
+	public function delete()
1674
+	{
1675
+		/**
1676
+		 * Called just before the `EE_Base_Class::_delete` method call.
1677
+		 * Note:
1678
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1679
+		 * should be aware that `_delete` may not always result in a permanent delete.
1680
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1681
+		 * soft deletes (trash) the object and does not permanently delete it.
1682
+		 *
1683
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1684
+		 */
1685
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1686
+		$result = $this->_delete();
1687
+		/**
1688
+		 * Called just after the `EE_Base_Class::_delete` method call.
1689
+		 * Note:
1690
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1691
+		 * should be aware that `_delete` may not always result in a permanent delete.
1692
+		 * For example `EE_Soft_Base_Class::_delete`
1693
+		 * soft deletes (trash) the object and does not permanently delete it.
1694
+		 *
1695
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1696
+		 * @param boolean       $result
1697
+		 */
1698
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1699
+		return $result;
1700
+	}
1701
+
1702
+
1703
+	/**
1704
+	 * Calls the specific delete method for the instantiated class.
1705
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1706
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1707
+	 * `EE_Base_Class::delete`
1708
+	 *
1709
+	 * @return bool|int
1710
+	 * @throws ReflectionException
1711
+	 * @throws InvalidArgumentException
1712
+	 * @throws InvalidInterfaceException
1713
+	 * @throws InvalidDataTypeException
1714
+	 * @throws EE_Error
1715
+	 */
1716
+	protected function _delete()
1717
+	{
1718
+		return $this->delete_permanently();
1719
+	}
1720
+
1721
+
1722
+	/**
1723
+	 * Deletes this model object permanently from db
1724
+	 * (but keep in mind related models may block the delete and return an error)
1725
+	 *
1726
+	 * @return bool | int
1727
+	 * @throws ReflectionException
1728
+	 * @throws InvalidArgumentException
1729
+	 * @throws InvalidInterfaceException
1730
+	 * @throws InvalidDataTypeException
1731
+	 * @throws EE_Error
1732
+	 */
1733
+	public function delete_permanently()
1734
+	{
1735
+		/**
1736
+		 * Called just before HARD deleting a model object
1737
+		 *
1738
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1739
+		 */
1740
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1741
+		$model  = $this->get_model();
1742
+		$result = $model->delete_permanently_by_ID($this->ID());
1743
+		$this->refresh_cache_of_related_objects();
1744
+		/**
1745
+		 * Called just after HARD deleting a model object
1746
+		 *
1747
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1748
+		 * @param boolean       $result
1749
+		 */
1750
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1751
+		return $result;
1752
+	}
1753
+
1754
+
1755
+	/**
1756
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1757
+	 * related model objects
1758
+	 *
1759
+	 * @throws ReflectionException
1760
+	 * @throws InvalidArgumentException
1761
+	 * @throws InvalidInterfaceException
1762
+	 * @throws InvalidDataTypeException
1763
+	 * @throws EE_Error
1764
+	 */
1765
+	public function refresh_cache_of_related_objects()
1766
+	{
1767
+		$model = $this->get_model();
1768
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1769
+			if (! empty($this->_model_relations[ $relation_name ])) {
1770
+				$related_objects = $this->_model_relations[ $relation_name ];
1771
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1772
+					//this relation only stores a single model object, not an array
1773
+					//but let's make it consistent
1774
+					$related_objects = array($related_objects);
1775
+				}
1776
+				foreach ($related_objects as $related_object) {
1777
+					//only refresh their cache if they're in memory
1778
+					if ($related_object instanceof EE_Base_Class) {
1779
+						$related_object->clear_cache(
1780
+							$model->get_this_model_name(),
1781
+							$this
1782
+						);
1783
+					}
1784
+				}
1785
+			}
1786
+		}
1787
+	}
1788
+
1789
+
1790
+	/**
1791
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1792
+	 * object just before saving.
1793
+	 *
1794
+	 * @access public
1795
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1796
+	 *                                 if provided during the save() method (often client code will change the fields'
1797
+	 *                                 values before calling save)
1798
+	 * @throws InvalidArgumentException
1799
+	 * @throws InvalidInterfaceException
1800
+	 * @throws InvalidDataTypeException
1801
+	 * @throws EE_Error
1802
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1803
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1804
+	 * @throws ReflectionException
1805
+	 * @throws ReflectionException
1806
+	 * @throws ReflectionException
1807
+	 */
1808
+	public function save($set_cols_n_values = array())
1809
+	{
1810
+		$model = $this->get_model();
1811
+		/**
1812
+		 * Filters the fields we're about to save on the model object
1813
+		 *
1814
+		 * @param array         $set_cols_n_values
1815
+		 * @param EE_Base_Class $model_object
1816
+		 */
1817
+		$set_cols_n_values = (array) apply_filters(
1818
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1819
+			$set_cols_n_values,
1820
+			$this
1821
+		);
1822
+		//set attributes as provided in $set_cols_n_values
1823
+		foreach ($set_cols_n_values as $column => $value) {
1824
+			$this->set($column, $value);
1825
+		}
1826
+		// no changes ? then don't do anything
1827
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1828
+			return 0;
1829
+		}
1830
+		/**
1831
+		 * Saving a model object.
1832
+		 * Before we perform a save, this action is fired.
1833
+		 *
1834
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1835
+		 */
1836
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1837
+		if (! $this->allow_persist()) {
1838
+			return 0;
1839
+		}
1840
+		// now get current attribute values
1841
+		$save_cols_n_values = $this->_fields;
1842
+		// if the object already has an ID, update it. Otherwise, insert it
1843
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1844
+		// They have been
1845
+		$old_assumption_concerning_value_preparation = $model
1846
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1847
+		$model->assume_values_already_prepared_by_model_object(true);
1848
+		//does this model have an autoincrement PK?
1849
+		if ($model->has_primary_key_field()) {
1850
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1851
+				//ok check if it's set, if so: update; if not, insert
1852
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1853
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1854
+				} else {
1855
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1856
+					$results = $model->insert($save_cols_n_values);
1857
+					if ($results) {
1858
+						//if successful, set the primary key
1859
+						//but don't use the normal SET method, because it will check if
1860
+						//an item with the same ID exists in the mapper & db, then
1861
+						//will find it in the db (because we just added it) and THAT object
1862
+						//will get added to the mapper before we can add this one!
1863
+						//but if we just avoid using the SET method, all that headache can be avoided
1864
+						$pk_field_name                   = $model->primary_key_name();
1865
+						$this->_fields[ $pk_field_name ] = $results;
1866
+						$this->_clear_cached_property($pk_field_name);
1867
+						$model->add_to_entity_map($this);
1868
+						$this->_update_cached_related_model_objs_fks();
1869
+					}
1870
+				}
1871
+			} else {//PK is NOT auto-increment
1872
+				//so check if one like it already exists in the db
1873
+				if ($model->exists_by_ID($this->ID())) {
1874
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1875
+						throw new EE_Error(
1876
+							sprintf(
1877
+								esc_html__(
1878
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1879
+									'event_espresso'
1880
+								),
1881
+								get_class($this),
1882
+								get_class($model) . '::instance()->add_to_entity_map()',
1883
+								get_class($model) . '::instance()->get_one_by_ID()',
1884
+								'<br />'
1885
+							)
1886
+						);
1887
+					}
1888
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1889
+				} else {
1890
+					$results = $model->insert($save_cols_n_values);
1891
+					$this->_update_cached_related_model_objs_fks();
1892
+				}
1893
+			}
1894
+		} else {//there is NO primary key
1895
+			$already_in_db = false;
1896
+			foreach ($model->unique_indexes() as $index) {
1897
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1898
+				if ($model->exists(array($uniqueness_where_params))) {
1899
+					$already_in_db = true;
1900
+				}
1901
+			}
1902
+			if ($already_in_db) {
1903
+				$combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1904
+					$model->get_combined_primary_key_fields());
1905
+				$results                     = $model->update(
1906
+					$save_cols_n_values,
1907
+					$combined_pk_fields_n_values
1908
+				);
1909
+			} else {
1910
+				$results = $model->insert($save_cols_n_values);
1911
+			}
1912
+		}
1913
+		//restore the old assumption about values being prepared by the model object
1914
+		$model->assume_values_already_prepared_by_model_object(
1915
+				$old_assumption_concerning_value_preparation
1916
+			);
1917
+		/**
1918
+		 * After saving the model object this action is called
1919
+		 *
1920
+		 * @param EE_Base_Class $model_object which was just saved
1921
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1922
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1923
+		 */
1924
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1925
+		$this->_has_changes = false;
1926
+		return $results;
1927
+	}
1928
+
1929
+
1930
+	/**
1931
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1932
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1933
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1934
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1935
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1936
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1937
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1938
+	 *
1939
+	 * @return void
1940
+	 * @throws ReflectionException
1941
+	 * @throws InvalidArgumentException
1942
+	 * @throws InvalidInterfaceException
1943
+	 * @throws InvalidDataTypeException
1944
+	 * @throws EE_Error
1945
+	 */
1946
+	protected function _update_cached_related_model_objs_fks()
1947
+	{
1948
+		$model = $this->get_model();
1949
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1950
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1951
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1952
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1953
+						$model->get_this_model_name()
1954
+					);
1955
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1956
+					if ($related_model_obj_in_cache->ID()) {
1957
+						$related_model_obj_in_cache->save();
1958
+					}
1959
+				}
1960
+			}
1961
+		}
1962
+	}
1963
+
1964
+
1965
+	/**
1966
+	 * Saves this model object and its NEW cached relations to the database.
1967
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1968
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1969
+	 * because otherwise, there's a potential for infinite looping of saving
1970
+	 * Saves the cached related model objects, and ensures the relation between them
1971
+	 * and this object and properly setup
1972
+	 *
1973
+	 * @return int ID of new model object on save; 0 on failure+
1974
+	 * @throws ReflectionException
1975
+	 * @throws InvalidArgumentException
1976
+	 * @throws InvalidInterfaceException
1977
+	 * @throws InvalidDataTypeException
1978
+	 * @throws EE_Error
1979
+	 */
1980
+	public function save_new_cached_related_model_objs()
1981
+	{
1982
+		//make sure this has been saved
1983
+		if (! $this->ID()) {
1984
+			$id = $this->save();
1985
+		} else {
1986
+			$id = $this->ID();
1987
+		}
1988
+		//now save all the NEW cached model objects  (ie they don't exist in the DB)
1989
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1990
+			if ($this->_model_relations[ $relationName ]) {
1991
+				//is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1992
+				//or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1993
+				/* @var $related_model_obj EE_Base_Class */
1994
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1995
+					//add a relation to that relation type (which saves the appropriate thing in the process)
1996
+					//but ONLY if it DOES NOT exist in the DB
1997
+					$related_model_obj = $this->_model_relations[ $relationName ];
1998
+					//					if( ! $related_model_obj->ID()){
1999
+					$this->_add_relation_to($related_model_obj, $relationName);
2000
+					$related_model_obj->save_new_cached_related_model_objs();
2001
+					//					}
2002
+				} else {
2003
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2004
+						//add a relation to that relation type (which saves the appropriate thing in the process)
2005
+						//but ONLY if it DOES NOT exist in the DB
2006
+						//						if( ! $related_model_obj->ID()){
2007
+						$this->_add_relation_to($related_model_obj, $relationName);
2008
+						$related_model_obj->save_new_cached_related_model_objs();
2009
+						//						}
2010
+					}
2011
+				}
2012
+			}
2013
+		}
2014
+		return $id;
2015
+	}
2016
+
2017
+
2018
+	/**
2019
+	 * for getting a model while instantiated.
2020
+	 *
2021
+	 * @return EEM_Base | EEM_CPT_Base
2022
+	 * @throws ReflectionException
2023
+	 * @throws InvalidArgumentException
2024
+	 * @throws InvalidInterfaceException
2025
+	 * @throws InvalidDataTypeException
2026
+	 * @throws EE_Error
2027
+	 */
2028
+	public function get_model()
2029
+	{
2030
+		if (! $this->_model) {
2031
+			$modelName    = self::_get_model_classname(get_class($this));
2032
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2033
+		} else {
2034
+			$this->_model->set_timezone($this->_timezone);
2035
+		}
2036
+		return $this->_model;
2037
+	}
2038
+
2039
+
2040
+	/**
2041
+	 * @param $props_n_values
2042
+	 * @param $classname
2043
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2044
+	 * @throws ReflectionException
2045
+	 * @throws InvalidArgumentException
2046
+	 * @throws InvalidInterfaceException
2047
+	 * @throws InvalidDataTypeException
2048
+	 * @throws EE_Error
2049
+	 */
2050
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2051
+	{
2052
+		//TODO: will not work for Term_Relationships because they have no PK!
2053
+		$primary_id_ref = self::_get_primary_key_name($classname);
2054
+		if (
2055
+			array_key_exists($primary_id_ref, $props_n_values)
2056
+			&& ! empty($props_n_values[ $primary_id_ref ])
2057
+		) {
2058
+			$id = $props_n_values[ $primary_id_ref ];
2059
+			return self::_get_model($classname)->get_from_entity_map($id);
2060
+		}
2061
+		return false;
2062
+	}
2063
+
2064
+
2065
+	/**
2066
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2067
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2068
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2069
+	 * we return false.
2070
+	 *
2071
+	 * @param  array  $props_n_values   incoming array of properties and their values
2072
+	 * @param  string $classname        the classname of the child class
2073
+	 * @param null    $timezone
2074
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2075
+	 *                                  date_format and the second value is the time format
2076
+	 * @return mixed (EE_Base_Class|bool)
2077
+	 * @throws InvalidArgumentException
2078
+	 * @throws InvalidInterfaceException
2079
+	 * @throws InvalidDataTypeException
2080
+	 * @throws EE_Error
2081
+	 * @throws ReflectionException
2082
+	 * @throws ReflectionException
2083
+	 * @throws ReflectionException
2084
+	 */
2085
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2086
+	{
2087
+		$existing = null;
2088
+		$model    = self::_get_model($classname, $timezone);
2089
+		if ($model->has_primary_key_field()) {
2090
+			$primary_id_ref = self::_get_primary_key_name($classname);
2091
+			if (array_key_exists($primary_id_ref, $props_n_values)
2092
+				&& ! empty($props_n_values[ $primary_id_ref ])
2093
+			) {
2094
+				$existing = $model->get_one_by_ID(
2095
+					$props_n_values[ $primary_id_ref ]
2096
+				);
2097
+			}
2098
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2099
+			//no primary key on this model, but there's still a matching item in the DB
2100
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2101
+				self::_get_model($classname, $timezone)
2102
+					->get_index_primary_key_string($props_n_values)
2103
+			);
2104
+		}
2105
+		if ($existing) {
2106
+			//set date formats if present before setting values
2107
+			if (! empty($date_formats) && is_array($date_formats)) {
2108
+				$existing->set_date_format($date_formats[0]);
2109
+				$existing->set_time_format($date_formats[1]);
2110
+			} else {
2111
+				//set default formats for date and time
2112
+				$existing->set_date_format(get_option('date_format'));
2113
+				$existing->set_time_format(get_option('time_format'));
2114
+			}
2115
+			foreach ($props_n_values as $property => $field_value) {
2116
+				$existing->set($property, $field_value);
2117
+			}
2118
+			return $existing;
2119
+		}
2120
+		return false;
2121
+	}
2122
+
2123
+
2124
+	/**
2125
+	 * Gets the EEM_*_Model for this class
2126
+	 *
2127
+	 * @access public now, as this is more convenient
2128
+	 * @param      $classname
2129
+	 * @param null $timezone
2130
+	 * @throws ReflectionException
2131
+	 * @throws InvalidArgumentException
2132
+	 * @throws InvalidInterfaceException
2133
+	 * @throws InvalidDataTypeException
2134
+	 * @throws EE_Error
2135
+	 * @return EEM_Base
2136
+	 */
2137
+	protected static function _get_model($classname, $timezone = null)
2138
+	{
2139
+		//find model for this class
2140
+		if (! $classname) {
2141
+			throw new EE_Error(
2142
+				sprintf(
2143
+					esc_html__(
2144
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2145
+						'event_espresso'
2146
+					),
2147
+					$classname
2148
+				)
2149
+			);
2150
+		}
2151
+		$modelName = self::_get_model_classname($classname);
2152
+		return self::_get_model_instance_with_name($modelName, $timezone);
2153
+	}
2154
+
2155
+
2156
+	/**
2157
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2158
+	 *
2159
+	 * @param string $model_classname
2160
+	 * @param null   $timezone
2161
+	 * @return EEM_Base
2162
+	 * @throws ReflectionException
2163
+	 * @throws InvalidArgumentException
2164
+	 * @throws InvalidInterfaceException
2165
+	 * @throws InvalidDataTypeException
2166
+	 * @throws EE_Error
2167
+	 */
2168
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2169
+	{
2170
+		$model_classname = str_replace('EEM_', '', $model_classname);
2171
+		$model           = EE_Registry::instance()->load_model($model_classname);
2172
+		$model->set_timezone($timezone);
2173
+		return $model;
2174
+	}
2175
+
2176
+
2177
+	/**
2178
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2179
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2180
+	 *
2181
+	 * @param null $model_name
2182
+	 * @return string like EEM_Attendee
2183
+	 */
2184
+	private static function _get_model_classname($model_name = null)
2185
+	{
2186
+		if (strpos($model_name, 'EE_') === 0) {
2187
+			$model_classname = str_replace('EE_', 'EEM_', $model_name);
2188
+		} else {
2189
+			$model_classname = 'EEM_' . $model_name;
2190
+		}
2191
+		return $model_classname;
2192
+	}
2193
+
2194
+
2195
+	/**
2196
+	 * returns the name of the primary key attribute
2197
+	 *
2198
+	 * @param null $classname
2199
+	 * @throws ReflectionException
2200
+	 * @throws InvalidArgumentException
2201
+	 * @throws InvalidInterfaceException
2202
+	 * @throws InvalidDataTypeException
2203
+	 * @throws EE_Error
2204
+	 * @return string
2205
+	 */
2206
+	protected static function _get_primary_key_name($classname = null)
2207
+	{
2208
+		if (! $classname) {
2209
+			throw new EE_Error(
2210
+				sprintf(
2211
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2212
+					$classname
2213
+				)
2214
+			);
2215
+		}
2216
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2217
+	}
2218
+
2219
+
2220
+	/**
2221
+	 * Gets the value of the primary key.
2222
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2223
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2224
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2225
+	 *
2226
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2227
+	 * @throws ReflectionException
2228
+	 * @throws InvalidArgumentException
2229
+	 * @throws InvalidInterfaceException
2230
+	 * @throws InvalidDataTypeException
2231
+	 * @throws EE_Error
2232
+	 */
2233
+	public function ID()
2234
+	{
2235
+		$model = $this->get_model();
2236
+		//now that we know the name of the variable, use a variable variable to get its value and return its
2237
+		if ($model->has_primary_key_field()) {
2238
+			return $this->_fields[ $model->primary_key_name() ];
2239
+		}
2240
+		return $model->get_index_primary_key_string($this->_fields);
2241
+	}
2242
+
2243
+
2244
+	/**
2245
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2246
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2247
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2248
+	 *
2249
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2250
+	 * @param string $relationName                     eg 'Events','Question',etc.
2251
+	 *                                                 an attendee to a group, you also want to specify which role they
2252
+	 *                                                 will have in that group. So you would use this parameter to
2253
+	 *                                                 specify array('role-column-name'=>'role-id')
2254
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2255
+	 *                                                 allow you to further constrict the relation to being added.
2256
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2257
+	 *                                                 column on the JOIN table and currently only the HABTM models
2258
+	 *                                                 accept these additional conditions.  Also remember that if an
2259
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2260
+	 *                                                 NEW row is created in the join table.
2261
+	 * @param null   $cache_id
2262
+	 * @throws ReflectionException
2263
+	 * @throws InvalidArgumentException
2264
+	 * @throws InvalidInterfaceException
2265
+	 * @throws InvalidDataTypeException
2266
+	 * @throws EE_Error
2267
+	 * @return EE_Base_Class the object the relation was added to
2268
+	 */
2269
+	public function _add_relation_to(
2270
+		$otherObjectModelObjectOrID,
2271
+		$relationName,
2272
+		$extra_join_model_fields_n_values = array(),
2273
+		$cache_id = null
2274
+	) {
2275
+		$model = $this->get_model();
2276
+		//if this thing exists in the DB, save the relation to the DB
2277
+		if ($this->ID()) {
2278
+			$otherObject = $model->add_relationship_to(
2279
+				$this,
2280
+				$otherObjectModelObjectOrID,
2281
+				$relationName,
2282
+				$extra_join_model_fields_n_values
2283
+			);
2284
+			//clear cache so future get_many_related and get_first_related() return new results.
2285
+			$this->clear_cache($relationName, $otherObject, true);
2286
+			if ($otherObject instanceof EE_Base_Class) {
2287
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2288
+			}
2289
+		} else {
2290
+			//this thing doesn't exist in the DB,  so just cache it
2291
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2292
+				throw new EE_Error(
2293
+					sprintf(
2294
+						esc_html__(
2295
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2296
+							'event_espresso'
2297
+						),
2298
+						$otherObjectModelObjectOrID,
2299
+						get_class($this)
2300
+					)
2301
+				);
2302
+			}
2303
+			$otherObject = $otherObjectModelObjectOrID;
2304
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2305
+		}
2306
+		if ($otherObject instanceof EE_Base_Class) {
2307
+			//fix the reciprocal relation too
2308
+			if ($otherObject->ID()) {
2309
+				//its saved so assumed relations exist in the DB, so we can just
2310
+				//clear the cache so future queries use the updated info in the DB
2311
+				$otherObject->clear_cache(
2312
+					$model->get_this_model_name(),
2313
+					null,
2314
+					true
2315
+				);
2316
+			} else {
2317
+				//it's not saved, so it caches relations like this
2318
+				$otherObject->cache($model->get_this_model_name(), $this);
2319
+			}
2320
+		}
2321
+		return $otherObject;
2322
+	}
2323
+
2324
+
2325
+	/**
2326
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2327
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2328
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2329
+	 * from the cache
2330
+	 *
2331
+	 * @param mixed  $otherObjectModelObjectOrID
2332
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2333
+	 *                to the DB yet
2334
+	 * @param string $relationName
2335
+	 * @param array  $where_query
2336
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2337
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2338
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2339
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2340
+	 *                created in the join table.
2341
+	 * @return EE_Base_Class the relation was removed from
2342
+	 * @throws ReflectionException
2343
+	 * @throws InvalidArgumentException
2344
+	 * @throws InvalidInterfaceException
2345
+	 * @throws InvalidDataTypeException
2346
+	 * @throws EE_Error
2347
+	 */
2348
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2349
+	{
2350
+		if ($this->ID()) {
2351
+			//if this exists in the DB, save the relation change to the DB too
2352
+			$otherObject = $this->get_model()->remove_relationship_to(
2353
+				$this,
2354
+				$otherObjectModelObjectOrID,
2355
+				$relationName,
2356
+				$where_query
2357
+			);
2358
+			$this->clear_cache(
2359
+				$relationName,
2360
+				$otherObject
2361
+			);
2362
+		} else {
2363
+			//this doesn't exist in the DB, just remove it from the cache
2364
+			$otherObject = $this->clear_cache(
2365
+				$relationName,
2366
+				$otherObjectModelObjectOrID
2367
+			);
2368
+		}
2369
+		if ($otherObject instanceof EE_Base_Class) {
2370
+			$otherObject->clear_cache(
2371
+				$this->get_model()->get_this_model_name(),
2372
+				$this
2373
+			);
2374
+		}
2375
+		return $otherObject;
2376
+	}
2377
+
2378
+
2379
+	/**
2380
+	 * Removes ALL the related things for the $relationName.
2381
+	 *
2382
+	 * @param string $relationName
2383
+	 * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2384
+	 * @return EE_Base_Class
2385
+	 * @throws ReflectionException
2386
+	 * @throws InvalidArgumentException
2387
+	 * @throws InvalidInterfaceException
2388
+	 * @throws InvalidDataTypeException
2389
+	 * @throws EE_Error
2390
+	 */
2391
+	public function _remove_relations($relationName, $where_query_params = array())
2392
+	{
2393
+		if ($this->ID()) {
2394
+			//if this exists in the DB, save the relation change to the DB too
2395
+			$otherObjects = $this->get_model()->remove_relations(
2396
+				$this,
2397
+				$relationName,
2398
+				$where_query_params
2399
+			);
2400
+			$this->clear_cache(
2401
+				$relationName,
2402
+				null,
2403
+				true
2404
+			);
2405
+		} else {
2406
+			//this doesn't exist in the DB, just remove it from the cache
2407
+			$otherObjects = $this->clear_cache(
2408
+				$relationName,
2409
+				null,
2410
+				true
2411
+			);
2412
+		}
2413
+		if (is_array($otherObjects)) {
2414
+			foreach ($otherObjects as $otherObject) {
2415
+				$otherObject->clear_cache(
2416
+					$this->get_model()->get_this_model_name(),
2417
+					$this
2418
+				);
2419
+			}
2420
+		}
2421
+		return $otherObjects;
2422
+	}
2423
+
2424
+
2425
+	/**
2426
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2427
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2428
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2429
+	 * because we want to get even deleted items etc.
2430
+	 *
2431
+	 * @param string $relationName key in the model's _model_relations array
2432
+	 * @param array  $query_params like EEM_Base::get_all
2433
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2434
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2435
+	 *                             results if you want IDs
2436
+	 * @throws ReflectionException
2437
+	 * @throws InvalidArgumentException
2438
+	 * @throws InvalidInterfaceException
2439
+	 * @throws InvalidDataTypeException
2440
+	 * @throws EE_Error
2441
+	 */
2442
+	public function get_many_related($relationName, $query_params = array())
2443
+	{
2444
+		if ($this->ID()) {
2445
+			//this exists in the DB, so get the related things from either the cache or the DB
2446
+			//if there are query parameters, forget about caching the related model objects.
2447
+			if ($query_params) {
2448
+				$related_model_objects = $this->get_model()->get_all_related(
2449
+					$this,
2450
+					$relationName,
2451
+					$query_params
2452
+				);
2453
+			} else {
2454
+				//did we already cache the result of this query?
2455
+				$cached_results = $this->get_all_from_cache($relationName);
2456
+				if (! $cached_results) {
2457
+					$related_model_objects = $this->get_model()->get_all_related(
2458
+						$this,
2459
+						$relationName,
2460
+						$query_params
2461
+					);
2462
+					//if no query parameters were passed, then we got all the related model objects
2463
+					//for that relation. We can cache them then.
2464
+					foreach ($related_model_objects as $related_model_object) {
2465
+						$this->cache($relationName, $related_model_object);
2466
+					}
2467
+				} else {
2468
+					$related_model_objects = $cached_results;
2469
+				}
2470
+			}
2471
+		} else {
2472
+			//this doesn't exist in the DB, so just get the related things from the cache
2473
+			$related_model_objects = $this->get_all_from_cache($relationName);
2474
+		}
2475
+		return $related_model_objects;
2476
+	}
2477
+
2478
+
2479
+	/**
2480
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2481
+	 * unless otherwise specified in the $query_params
2482
+	 *
2483
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2484
+	 * @param array  $query_params   like EEM_Base::get_all's
2485
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2486
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2487
+	 *                               that by the setting $distinct to TRUE;
2488
+	 * @return int
2489
+	 * @throws ReflectionException
2490
+	 * @throws InvalidArgumentException
2491
+	 * @throws InvalidInterfaceException
2492
+	 * @throws InvalidDataTypeException
2493
+	 * @throws EE_Error
2494
+	 */
2495
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2496
+	{
2497
+		return $this->get_model()->count_related(
2498
+			$this,
2499
+			$relation_name,
2500
+			$query_params,
2501
+			$field_to_count,
2502
+			$distinct
2503
+		);
2504
+	}
2505
+
2506
+
2507
+	/**
2508
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2509
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2510
+	 *
2511
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2512
+	 * @param array  $query_params  like EEM_Base::get_all's
2513
+	 * @param string $field_to_sum  name of field to count by.
2514
+	 *                              By default, uses primary key
2515
+	 *                              (which doesn't make much sense, so you should probably change it)
2516
+	 * @return int
2517
+	 * @throws ReflectionException
2518
+	 * @throws InvalidArgumentException
2519
+	 * @throws InvalidInterfaceException
2520
+	 * @throws InvalidDataTypeException
2521
+	 * @throws EE_Error
2522
+	 */
2523
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2524
+	{
2525
+		return $this->get_model()->sum_related(
2526
+			$this,
2527
+			$relation_name,
2528
+			$query_params,
2529
+			$field_to_sum
2530
+		);
2531
+	}
2532
+
2533
+
2534
+	/**
2535
+	 * Gets the first (ie, one) related model object of the specified type.
2536
+	 *
2537
+	 * @param string $relationName key in the model's _model_relations array
2538
+	 * @param array  $query_params like EEM_Base::get_all
2539
+	 * @return EE_Base_Class (not an array, a single object)
2540
+	 * @throws ReflectionException
2541
+	 * @throws InvalidArgumentException
2542
+	 * @throws InvalidInterfaceException
2543
+	 * @throws InvalidDataTypeException
2544
+	 * @throws EE_Error
2545
+	 */
2546
+	public function get_first_related($relationName, $query_params = array())
2547
+	{
2548
+		$model = $this->get_model();
2549
+		if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2550
+			//if they've provided some query parameters, don't bother trying to cache the result
2551
+			//also make sure we're not caching the result of get_first_related
2552
+			//on a relation which should have an array of objects (because the cache might have an array of objects)
2553
+			if ($query_params
2554
+				|| ! $model->related_settings_for($relationName)
2555
+					 instanceof
2556
+					 EE_Belongs_To_Relation
2557
+			) {
2558
+				$related_model_object = $model->get_first_related(
2559
+					$this,
2560
+					$relationName,
2561
+					$query_params
2562
+				);
2563
+			} else {
2564
+				//first, check if we've already cached the result of this query
2565
+				$cached_result = $this->get_one_from_cache($relationName);
2566
+				if (! $cached_result) {
2567
+					$related_model_object = $model->get_first_related(
2568
+						$this,
2569
+						$relationName,
2570
+						$query_params
2571
+					);
2572
+					$this->cache($relationName, $related_model_object);
2573
+				} else {
2574
+					$related_model_object = $cached_result;
2575
+				}
2576
+			}
2577
+		} else {
2578
+			$related_model_object = null;
2579
+			// this doesn't exist in the Db,
2580
+			// but maybe the relation is of type belongs to, and so the related thing might
2581
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2582
+				$related_model_object = $model->get_first_related(
2583
+					$this,
2584
+					$relationName,
2585
+					$query_params
2586
+				);
2587
+			}
2588
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2589
+			// just get what's cached on this object
2590
+			if (! $related_model_object) {
2591
+				$related_model_object = $this->get_one_from_cache($relationName);
2592
+			}
2593
+		}
2594
+		return $related_model_object;
2595
+	}
2596
+
2597
+
2598
+	/**
2599
+	 * Does a delete on all related objects of type $relationName and removes
2600
+	 * the current model object's relation to them. If they can't be deleted (because
2601
+	 * of blocking related model objects) does nothing. If the related model objects are
2602
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2603
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2604
+	 *
2605
+	 * @param string $relationName
2606
+	 * @param array  $query_params like EEM_Base::get_all's
2607
+	 * @return int how many deleted
2608
+	 * @throws ReflectionException
2609
+	 * @throws InvalidArgumentException
2610
+	 * @throws InvalidInterfaceException
2611
+	 * @throws InvalidDataTypeException
2612
+	 * @throws EE_Error
2613
+	 */
2614
+	public function delete_related($relationName, $query_params = array())
2615
+	{
2616
+		if ($this->ID()) {
2617
+			$count = $this->get_model()->delete_related(
2618
+				$this,
2619
+				$relationName,
2620
+				$query_params
2621
+			);
2622
+		} else {
2623
+			$count = count($this->get_all_from_cache($relationName));
2624
+			$this->clear_cache($relationName, null, true);
2625
+		}
2626
+		return $count;
2627
+	}
2628
+
2629
+
2630
+	/**
2631
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2632
+	 * the current model object's relation to them. If they can't be deleted (because
2633
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2634
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2635
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2636
+	 *
2637
+	 * @param string $relationName
2638
+	 * @param array  $query_params like EEM_Base::get_all's
2639
+	 * @return int how many deleted (including those soft deleted)
2640
+	 * @throws ReflectionException
2641
+	 * @throws InvalidArgumentException
2642
+	 * @throws InvalidInterfaceException
2643
+	 * @throws InvalidDataTypeException
2644
+	 * @throws EE_Error
2645
+	 */
2646
+	public function delete_related_permanently($relationName, $query_params = array())
2647
+	{
2648
+		if ($this->ID()) {
2649
+			$count = $this->get_model()->delete_related_permanently(
2650
+				$this,
2651
+				$relationName,
2652
+				$query_params
2653
+			);
2654
+		} else {
2655
+			$count = count($this->get_all_from_cache($relationName));
2656
+		}
2657
+		$this->clear_cache($relationName, null, true);
2658
+		return $count;
2659
+	}
2660
+
2661
+
2662
+	/**
2663
+	 * is_set
2664
+	 * Just a simple utility function children can use for checking if property exists
2665
+	 *
2666
+	 * @access  public
2667
+	 * @param  string $field_name property to check
2668
+	 * @return bool                              TRUE if existing,FALSE if not.
2669
+	 */
2670
+	public function is_set($field_name)
2671
+	{
2672
+		return isset($this->_fields[ $field_name ]);
2673
+	}
2674
+
2675
+
2676
+	/**
2677
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2678
+	 * EE_Error exception if they don't
2679
+	 *
2680
+	 * @param  mixed (string|array) $properties properties to check
2681
+	 * @throws EE_Error
2682
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2683
+	 */
2684
+	protected function _property_exists($properties)
2685
+	{
2686
+		foreach ((array) $properties as $property_name) {
2687
+			//first make sure this property exists
2688
+			if (! $this->_fields[ $property_name ]) {
2689
+				throw new EE_Error(
2690
+					sprintf(
2691
+						esc_html__(
2692
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2693
+							'event_espresso'
2694
+						),
2695
+						$property_name
2696
+					)
2697
+				);
2698
+			}
2699
+		}
2700
+		return true;
2701
+	}
2702
+
2703
+
2704
+	/**
2705
+	 * This simply returns an array of model fields for this object
2706
+	 *
2707
+	 * @return array
2708
+	 * @throws ReflectionException
2709
+	 * @throws InvalidArgumentException
2710
+	 * @throws InvalidInterfaceException
2711
+	 * @throws InvalidDataTypeException
2712
+	 * @throws EE_Error
2713
+	 */
2714
+	public function model_field_array()
2715
+	{
2716
+		$fields     = $this->get_model()->field_settings(false);
2717
+		$properties = array();
2718
+		//remove prepended underscore
2719
+		foreach ($fields as $field_name => $settings) {
2720
+			$properties[ $field_name ] = $this->get($field_name);
2721
+		}
2722
+		return $properties;
2723
+	}
2724
+
2725
+
2726
+	/**
2727
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2728
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2729
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2730
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2731
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2732
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2733
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2734
+	 * and accepts 2 arguments: the object on which the function was called,
2735
+	 * and an array of the original arguments passed to the function.
2736
+	 * Whatever their callback function returns will be returned by this function.
2737
+	 * Example: in functions.php (or in a plugin):
2738
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2739
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2740
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2741
+	 *          return $previousReturnValue.$returnString;
2742
+	 *      }
2743
+	 * require('EE_Answer.class.php');
2744
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2745
+	 * echo $answer->my_callback('monkeys',100);
2746
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2747
+	 *
2748
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2749
+	 * @param array  $args       array of original arguments passed to the function
2750
+	 * @throws EE_Error
2751
+	 * @return mixed whatever the plugin which calls add_filter decides
2752
+	 */
2753
+	public function __call($methodName, $args)
2754
+	{
2755
+		$className = get_class($this);
2756
+		$tagName   = "FHEE__{$className}__{$methodName}";
2757
+		if (! has_filter($tagName)) {
2758
+			throw new EE_Error(
2759
+				sprintf(
2760
+					esc_html__(
2761
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2762
+						'event_espresso'
2763
+					),
2764
+					$methodName,
2765
+					$className,
2766
+					$tagName
2767
+				)
2768
+			);
2769
+		}
2770
+		return apply_filters($tagName, null, $this, $args);
2771
+	}
2772
+
2773
+
2774
+	/**
2775
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2776
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2777
+	 *
2778
+	 * @param string $meta_key
2779
+	 * @param mixed  $meta_value
2780
+	 * @param mixed  $previous_value
2781
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2782
+	 *                  NOTE: if the values haven't changed, returns 0
2783
+	 * @throws InvalidArgumentException
2784
+	 * @throws InvalidInterfaceException
2785
+	 * @throws InvalidDataTypeException
2786
+	 * @throws EE_Error
2787
+	 * @throws ReflectionException
2788
+	 */
2789
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2790
+	{
2791
+		$query_params = array(
2792
+			array(
2793
+				'EXM_key'  => $meta_key,
2794
+				'OBJ_ID'   => $this->ID(),
2795
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2796
+			),
2797
+		);
2798
+		if ($previous_value !== null) {
2799
+			$query_params[0]['EXM_value'] = $meta_value;
2800
+		}
2801
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2802
+		if (! $existing_rows_like_that) {
2803
+			return $this->add_extra_meta($meta_key, $meta_value);
2804
+		}
2805
+		foreach ($existing_rows_like_that as $existing_row) {
2806
+			$existing_row->save(array('EXM_value' => $meta_value));
2807
+		}
2808
+		return count($existing_rows_like_that);
2809
+	}
2810
+
2811
+
2812
+	/**
2813
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2814
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2815
+	 * extra meta row was entered, false if not
2816
+	 *
2817
+	 * @param string  $meta_key
2818
+	 * @param mixed   $meta_value
2819
+	 * @param boolean $unique
2820
+	 * @return boolean
2821
+	 * @throws InvalidArgumentException
2822
+	 * @throws InvalidInterfaceException
2823
+	 * @throws InvalidDataTypeException
2824
+	 * @throws EE_Error
2825
+	 * @throws ReflectionException
2826
+	 * @throws ReflectionException
2827
+	 */
2828
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2829
+	{
2830
+		if ($unique) {
2831
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2832
+				array(
2833
+					array(
2834
+						'EXM_key'  => $meta_key,
2835
+						'OBJ_ID'   => $this->ID(),
2836
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2837
+					),
2838
+				)
2839
+			);
2840
+			if ($existing_extra_meta) {
2841
+				return false;
2842
+			}
2843
+		}
2844
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2845
+			array(
2846
+				'EXM_key'   => $meta_key,
2847
+				'EXM_value' => $meta_value,
2848
+				'OBJ_ID'    => $this->ID(),
2849
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2850
+			)
2851
+		);
2852
+		$new_extra_meta->save();
2853
+		return true;
2854
+	}
2855
+
2856
+
2857
+	/**
2858
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2859
+	 * is specified, only deletes extra meta records with that value.
2860
+	 *
2861
+	 * @param string $meta_key
2862
+	 * @param mixed  $meta_value
2863
+	 * @return int number of extra meta rows deleted
2864
+	 * @throws InvalidArgumentException
2865
+	 * @throws InvalidInterfaceException
2866
+	 * @throws InvalidDataTypeException
2867
+	 * @throws EE_Error
2868
+	 * @throws ReflectionException
2869
+	 */
2870
+	public function delete_extra_meta($meta_key, $meta_value = null)
2871
+	{
2872
+		$query_params = array(
2873
+			array(
2874
+				'EXM_key'  => $meta_key,
2875
+				'OBJ_ID'   => $this->ID(),
2876
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2877
+			),
2878
+		);
2879
+		if ($meta_value !== null) {
2880
+			$query_params[0]['EXM_value'] = $meta_value;
2881
+		}
2882
+		return EEM_Extra_Meta::instance()->delete($query_params);
2883
+	}
2884
+
2885
+
2886
+	/**
2887
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2888
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2889
+	 * You can specify $default is case you haven't found the extra meta
2890
+	 *
2891
+	 * @param string  $meta_key
2892
+	 * @param boolean $single
2893
+	 * @param mixed   $default if we don't find anything, what should we return?
2894
+	 * @return mixed single value if $single; array if ! $single
2895
+	 * @throws ReflectionException
2896
+	 * @throws InvalidArgumentException
2897
+	 * @throws InvalidInterfaceException
2898
+	 * @throws InvalidDataTypeException
2899
+	 * @throws EE_Error
2900
+	 */
2901
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2902
+	{
2903
+		if ($single) {
2904
+			$result = $this->get_first_related(
2905
+				'Extra_Meta',
2906
+				array(array('EXM_key' => $meta_key))
2907
+			);
2908
+			if ($result instanceof EE_Extra_Meta) {
2909
+				return $result->value();
2910
+			}
2911
+		} else {
2912
+			$results = $this->get_many_related(
2913
+				'Extra_Meta',
2914
+				array(array('EXM_key' => $meta_key))
2915
+			);
2916
+			if ($results) {
2917
+				$values = array();
2918
+				foreach ($results as $result) {
2919
+					if ($result instanceof EE_Extra_Meta) {
2920
+						$values[ $result->ID() ] = $result->value();
2921
+					}
2922
+				}
2923
+				return $values;
2924
+			}
2925
+		}
2926
+		//if nothing discovered yet return default.
2927
+		return apply_filters(
2928
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2929
+			$default,
2930
+			$meta_key,
2931
+			$single,
2932
+			$this
2933
+		);
2934
+	}
2935
+
2936
+
2937
+	/**
2938
+	 * Returns a simple array of all the extra meta associated with this model object.
2939
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2940
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2941
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2942
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2943
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2944
+	 * finally the extra meta's value as each sub-value. (eg
2945
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2946
+	 *
2947
+	 * @param boolean $one_of_each_key
2948
+	 * @return array
2949
+	 * @throws ReflectionException
2950
+	 * @throws InvalidArgumentException
2951
+	 * @throws InvalidInterfaceException
2952
+	 * @throws InvalidDataTypeException
2953
+	 * @throws EE_Error
2954
+	 */
2955
+	public function all_extra_meta_array($one_of_each_key = true)
2956
+	{
2957
+		$return_array = array();
2958
+		if ($one_of_each_key) {
2959
+			$extra_meta_objs = $this->get_many_related(
2960
+				'Extra_Meta',
2961
+				array('group_by' => 'EXM_key')
2962
+			);
2963
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2964
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2965
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2966
+				}
2967
+			}
2968
+		} else {
2969
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2970
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2971
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2972
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2973
+						$return_array[ $extra_meta_obj->key() ] = array();
2974
+					}
2975
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2976
+				}
2977
+			}
2978
+		}
2979
+		return $return_array;
2980
+	}
2981
+
2982
+
2983
+	/**
2984
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2985
+	 *
2986
+	 * @return string
2987
+	 * @throws ReflectionException
2988
+	 * @throws InvalidArgumentException
2989
+	 * @throws InvalidInterfaceException
2990
+	 * @throws InvalidDataTypeException
2991
+	 * @throws EE_Error
2992
+	 */
2993
+	public function name()
2994
+	{
2995
+		//find a field that's not a text field
2996
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2997
+		if ($field_we_can_use) {
2998
+			return $this->get($field_we_can_use->get_name());
2999
+		}
3000
+		$first_few_properties = $this->model_field_array();
3001
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3002
+		$name_parts           = array();
3003
+		foreach ($first_few_properties as $name => $value) {
3004
+			$name_parts[] = "$name:$value";
3005
+		}
3006
+		return implode(',', $name_parts);
3007
+	}
3008
+
3009
+
3010
+	/**
3011
+	 * in_entity_map
3012
+	 * Checks if this model object has been proven to already be in the entity map
3013
+	 *
3014
+	 * @return boolean
3015
+	 * @throws ReflectionException
3016
+	 * @throws InvalidArgumentException
3017
+	 * @throws InvalidInterfaceException
3018
+	 * @throws InvalidDataTypeException
3019
+	 * @throws EE_Error
3020
+	 */
3021
+	public function in_entity_map()
3022
+	{
3023
+		// well, if we looked, did we find it in the entity map?
3024
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3025
+	}
3026
+
3027
+
3028
+	/**
3029
+	 * refresh_from_db
3030
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3031
+	 *
3032
+	 * @throws ReflectionException
3033
+	 * @throws InvalidArgumentException
3034
+	 * @throws InvalidInterfaceException
3035
+	 * @throws InvalidDataTypeException
3036
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3037
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3038
+	 */
3039
+	public function refresh_from_db()
3040
+	{
3041
+		if ($this->ID() && $this->in_entity_map()) {
3042
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3043
+		} else {
3044
+			//if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3045
+			//if it has an ID but it's not in the map, and you're asking me to refresh it
3046
+			//that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3047
+			//absolutely nothing in it for this ID
3048
+			if (WP_DEBUG) {
3049
+				throw new EE_Error(
3050
+					sprintf(
3051
+						esc_html__('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3052
+							'event_espresso'),
3053
+						$this->ID(),
3054
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3055
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3056
+					)
3057
+				);
3058
+			}
3059
+		}
3060
+	}
3061
+
3062
+
3063
+	/**
3064
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3065
+	 * (probably a bad assumption they have made, oh well)
3066
+	 *
3067
+	 * @return string
3068
+	 */
3069
+	public function __toString()
3070
+	{
3071
+		try {
3072
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3073
+		} catch (Exception $e) {
3074
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3075
+			return '';
3076
+		}
3077
+	}
3078
+
3079
+
3080
+	/**
3081
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3082
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3083
+	 * This means if we have made changes to those related model objects, and want to unserialize
3084
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3085
+	 * Instead, those related model objects should be directly serialized and stored.
3086
+	 * Eg, the following won't work:
3087
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3088
+	 * $att = $reg->attendee();
3089
+	 * $att->set( 'ATT_fname', 'Dirk' );
3090
+	 * update_option( 'my_option', serialize( $reg ) );
3091
+	 * //END REQUEST
3092
+	 * //START NEXT REQUEST
3093
+	 * $reg = get_option( 'my_option' );
3094
+	 * $reg->attendee()->save();
3095
+	 * And would need to be replace with:
3096
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3097
+	 * $att = $reg->attendee();
3098
+	 * $att->set( 'ATT_fname', 'Dirk' );
3099
+	 * update_option( 'my_option', serialize( $reg ) );
3100
+	 * //END REQUEST
3101
+	 * //START NEXT REQUEST
3102
+	 * $att = get_option( 'my_option' );
3103
+	 * $att->save();
3104
+	 *
3105
+	 * @return array
3106
+	 * @throws ReflectionException
3107
+	 * @throws InvalidArgumentException
3108
+	 * @throws InvalidInterfaceException
3109
+	 * @throws InvalidDataTypeException
3110
+	 * @throws EE_Error
3111
+	 */
3112
+	public function __sleep()
3113
+	{
3114
+		$model = $this->get_model();
3115
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3116
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3117
+				$classname = 'EE_' . $model->get_this_model_name();
3118
+				if (
3119
+					$this->get_one_from_cache($relation_name) instanceof $classname
3120
+					&& $this->get_one_from_cache($relation_name)->ID()
3121
+				) {
3122
+					$this->clear_cache(
3123
+						$relation_name,
3124
+						$this->get_one_from_cache($relation_name)->ID()
3125
+					);
3126
+				}
3127
+			}
3128
+		}
3129
+		$this->_props_n_values_provided_in_constructor = array();
3130
+		$properties_to_serialize                       = get_object_vars($this);
3131
+		//don't serialize the model. It's big and that risks recursion
3132
+		unset($properties_to_serialize['_model']);
3133
+		return array_keys($properties_to_serialize);
3134
+	}
3135
+
3136
+
3137
+	/**
3138
+	 * restore _props_n_values_provided_in_constructor
3139
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3140
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3141
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3142
+	 */
3143
+	public function __wakeup()
3144
+	{
3145
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3146
+	}
3147
+
3148
+
3149
+	/**
3150
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3151
+	 * distinct with the clone host instance are also cloned.
3152
+	 */
3153
+	public function __clone()
3154
+	{
3155
+		//handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3156
+		foreach ($this->_fields as $field => $value) {
3157
+			if ($value instanceof DateTime) {
3158
+				$this->_fields[$field] = clone $value;
3159
+			}
3160
+		}
3161
+	}
3162 3162
 }
3163 3163
 
3164 3164
 
Please login to merge, or discard this patch.
Spacing   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
         $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
149 149
         // verify client code has not passed any invalid field names
150 150
         foreach ($fieldValues as $field_name => $field_value) {
151
-            if (! isset($model_fields[ $field_name ])) {
151
+            if ( ! isset($model_fields[$field_name])) {
152 152
                 throw new EE_Error(
153 153
                     sprintf(
154 154
                         esc_html__(
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
             }
164 164
         }
165 165
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
166
-        if (! empty($date_formats) && is_array($date_formats)) {
166
+        if ( ! empty($date_formats) && is_array($date_formats)) {
167 167
             list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
168 168
         } else {
169 169
             //set default formats for date and time
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
             foreach ($model_fields as $fieldName => $field) {
177 177
                 $this->set_from_db(
178 178
                     $fieldName,
179
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
179
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null
180 180
                 );
181 181
             }
182 182
         } else {
@@ -185,22 +185,22 @@  discard block
 block discarded – undo
185 185
             foreach ($model_fields as $fieldName => $field) {
186 186
                 $this->set(
187 187
                     $fieldName,
188
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null, true
188
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true
189 189
                 );
190 190
             }
191 191
         }
192 192
         //remember what values were passed to this constructor
193 193
         $this->_props_n_values_provided_in_constructor = $fieldValues;
194 194
         //remember in entity mapper
195
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
+        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
196 196
             $model->add_to_entity_map($this);
197 197
         }
198 198
         //setup all the relations
199 199
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200 200
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
-                $this->_model_relations[ $relation_name ] = null;
201
+                $this->_model_relations[$relation_name] = null;
202 202
             } else {
203
-                $this->_model_relations[ $relation_name ] = array();
203
+                $this->_model_relations[$relation_name] = array();
204 204
             }
205 205
         }
206 206
         /**
@@ -251,10 +251,10 @@  discard block
 block discarded – undo
251 251
      */
252 252
     public function get_original($field_name)
253 253
     {
254
-        if (isset($this->_props_n_values_provided_in_constructor[ $field_name ])
254
+        if (isset($this->_props_n_values_provided_in_constructor[$field_name])
255 255
             && $field_settings = $this->get_model()->field_settings_for($field_name)
256 256
         ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
257
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
258 258
         }
259 259
         return null;
260 260
     }
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
         // then don't do anything
292 292
         if (
293 293
             ! $use_default
294
-            && $this->_fields[ $field_name ] === $field_value
294
+            && $this->_fields[$field_name] === $field_value
295 295
             && $this->ID()
296 296
         ) {
297 297
             return;
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
             $holder_of_value = $field_obj->prepare_for_set($field_value);
310 310
             //should the value be null?
311 311
             if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
312
+                $this->_fields[$field_name] = $field_obj->get_default_value();
313 313
                 /**
314 314
                  * To save having to refactor all the models, if a default value is used for a
315 315
                  * EE_Datetime_Field, and that value is not null nor is it a DateTime
@@ -320,15 +320,15 @@  discard block
 block discarded – undo
320 320
                  */
321 321
                 if (
322 322
                     $field_obj instanceof EE_Datetime_Field
323
-                    && $this->_fields[ $field_name ] !== null
324
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
323
+                    && $this->_fields[$field_name] !== null
324
+                    && ! $this->_fields[$field_name] instanceof DateTime
325 325
                 ) {
326
-                    empty($this->_fields[ $field_name ])
326
+                    empty($this->_fields[$field_name])
327 327
                         ? $this->set($field_name, time())
328
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
328
+                        : $this->set($field_name, $this->_fields[$field_name]);
329 329
                 }
330 330
             } else {
331
-                $this->_fields[ $field_name ] = $holder_of_value;
331
+                $this->_fields[$field_name] = $holder_of_value;
332 332
             }
333 333
             //if we're not in the constructor...
334 334
             //now check if what we set was a primary key
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
                 $fields_on_model = self::_get_model(get_class($this))->field_settings();
346 346
                 $obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347 347
                 foreach ($fields_on_model as $field_obj) {
348
-                    if (! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
348
+                    if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
349 349
                         && $field_obj->get_name() !== $field_name
350 350
                     ) {
351 351
                         $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
@@ -390,8 +390,8 @@  discard block
 block discarded – undo
390 390
      */
391 391
     public function getCustomSelect($alias)
392 392
     {
393
-        return isset($this->custom_selection_results[ $alias ])
394
-            ? $this->custom_selection_results[ $alias ]
393
+        return isset($this->custom_selection_results[$alias])
394
+            ? $this->custom_selection_results[$alias]
395 395
             : null;
396 396
     }
397 397
 
@@ -478,8 +478,8 @@  discard block
 block discarded – undo
478 478
         foreach ($model_fields as $field_name => $field_obj) {
479 479
             if ($field_obj instanceof EE_Datetime_Field) {
480 480
                 $field_obj->set_timezone($this->_timezone);
481
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
482
-                    $this->_fields[ $field_name ]->setTimezone(new DateTimeZone($this->_timezone));
481
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
482
+                    $this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
483 483
                     // workaround for php datetime bug
484 484
                     // @see https://events.codebasehq.com/projects/event-espresso/tickets/11407
485 485
                     $this->_fields[$field_name]->getTimestamp();
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
      */
541 541
     public function get_format($full = true)
542 542
     {
543
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
543
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
544 544
     }
545 545
 
546 546
 
@@ -566,11 +566,11 @@  discard block
 block discarded – undo
566 566
     public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
567 567
     {
568 568
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
569
-        if (! $object_to_cache instanceof EE_Base_Class) {
569
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
570 570
             return false;
571 571
         }
572 572
         // also get "how" the object is related, or throw an error
573
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
573
+        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
574 574
             throw new EE_Error(
575 575
                 sprintf(
576 576
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -584,38 +584,38 @@  discard block
 block discarded – undo
584 584
             // if it's a "belongs to" relationship, then there's only one related model object
585 585
             // eg, if this is a registration, there's only 1 attendee for it
586 586
             // so for these model objects just set it to be cached
587
-            $this->_model_relations[ $relationName ] = $object_to_cache;
587
+            $this->_model_relations[$relationName] = $object_to_cache;
588 588
             $return                                  = true;
589 589
         } else {
590 590
             // otherwise, this is the "many" side of a one to many relationship,
591 591
             // so we'll add the object to the array of related objects for that type.
592 592
             // eg: if this is an event, there are many registrations for that event,
593 593
             // so we cache the registrations in an array
594
-            if (! is_array($this->_model_relations[ $relationName ])) {
594
+            if ( ! is_array($this->_model_relations[$relationName])) {
595 595
                 // if for some reason, the cached item is a model object,
596 596
                 // then stick that in the array, otherwise start with an empty array
597
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
597
+                $this->_model_relations[$relationName] = $this->_model_relations[$relationName]
598 598
                                                            instanceof
599 599
                                                            EE_Base_Class
600
-                    ? array($this->_model_relations[ $relationName ]) : array();
600
+                    ? array($this->_model_relations[$relationName]) : array();
601 601
             }
602 602
             // first check for a cache_id which is normally empty
603
-            if (! empty($cache_id)) {
603
+            if ( ! empty($cache_id)) {
604 604
                 // if the cache_id exists, then it means we are purposely trying to cache this
605 605
                 // with a known key that can then be used to retrieve the object later on
606
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
606
+                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
607 607
                 $return                                               = $cache_id;
608 608
             } elseif ($object_to_cache->ID()) {
609 609
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
610
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
610
+                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
611 611
                 $return                                                            = $object_to_cache->ID();
612 612
             } else {
613 613
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
614
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
614
+                $this->_model_relations[$relationName][] = $object_to_cache;
615 615
                 // move the internal pointer to the end of the array
616
-                end($this->_model_relations[ $relationName ]);
616
+                end($this->_model_relations[$relationName]);
617 617
                 // and grab the key so that we can return it
618
-                $return = key($this->_model_relations[ $relationName ]);
618
+                $return = key($this->_model_relations[$relationName]);
619 619
             }
620 620
         }
621 621
         return $return;
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
         //first make sure this property exists
642 642
         $this->get_model()->field_settings_for($fieldname);
643 643
         $cache_type                                            = empty($cache_type) ? 'standard' : $cache_type;
644
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
644
+        $this->_cached_properties[$fieldname][$cache_type] = $value;
645 645
     }
646 646
 
647 647
 
@@ -670,9 +670,9 @@  discard block
 block discarded – undo
670 670
         $model = $this->get_model();
671 671
         $model->field_settings_for($fieldname);
672 672
         $cache_type = $pretty ? 'pretty' : 'standard';
673
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
674
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
675
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
673
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
674
+        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
675
+            return $this->_cached_properties[$fieldname][$cache_type];
676 676
         }
677 677
         $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
678 678
         $this->_set_cached_property($fieldname, $value, $cache_type);
@@ -700,12 +700,12 @@  discard block
 block discarded – undo
700 700
         if ($field_obj instanceof EE_Datetime_Field) {
701 701
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
702 702
         }
703
-        if (! isset($this->_fields[ $fieldname ])) {
704
-            $this->_fields[ $fieldname ] = null;
703
+        if ( ! isset($this->_fields[$fieldname])) {
704
+            $this->_fields[$fieldname] = null;
705 705
         }
706 706
         $value = $pretty
707
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
708
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
708
+            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
709 709
         return $value;
710 710
     }
711 711
 
@@ -763,8 +763,8 @@  discard block
 block discarded – undo
763 763
      */
764 764
     protected function _clear_cached_property($property_name)
765 765
     {
766
-        if (isset($this->_cached_properties[ $property_name ])) {
767
-            unset($this->_cached_properties[ $property_name ]);
766
+        if (isset($this->_cached_properties[$property_name])) {
767
+            unset($this->_cached_properties[$property_name]);
768 768
         }
769 769
     }
770 770
 
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
     {
817 817
         $relationship_to_model = $this->get_model()->related_settings_for($relationName);
818 818
         $index_in_cache        = '';
819
-        if (! $relationship_to_model) {
819
+        if ( ! $relationship_to_model) {
820 820
             throw new EE_Error(
821 821
                 sprintf(
822 822
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -827,21 +827,21 @@  discard block
 block discarded – undo
827 827
         }
828 828
         if ($clear_all) {
829 829
             $obj_removed                             = true;
830
-            $this->_model_relations[ $relationName ] = null;
830
+            $this->_model_relations[$relationName] = null;
831 831
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
832
-            $obj_removed                             = $this->_model_relations[ $relationName ];
833
-            $this->_model_relations[ $relationName ] = null;
832
+            $obj_removed                             = $this->_model_relations[$relationName];
833
+            $this->_model_relations[$relationName] = null;
834 834
         } else {
835 835
             if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
836 836
                 && $object_to_remove_or_index_into_array->ID()
837 837
             ) {
838 838
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
839
-                if (is_array($this->_model_relations[ $relationName ])
840
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
839
+                if (is_array($this->_model_relations[$relationName])
840
+                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
841 841
                 ) {
842 842
                     $index_found_at = null;
843 843
                     //find this object in the array even though it has a different key
844
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
844
+                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
845 845
                         /** @noinspection TypeUnsafeComparisonInspection */
846 846
                         if (
847 847
                             $obj instanceof EE_Base_Class
@@ -875,9 +875,9 @@  discard block
 block discarded – undo
875 875
             }
876 876
             //supposedly we've found it. But it could just be that the client code
877 877
             //provided a bad index/object
878
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
879
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
880
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
878
+            if (isset($this->_model_relations[$relationName][$index_in_cache])) {
879
+                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
880
+                unset($this->_model_relations[$relationName][$index_in_cache]);
881 881
             } else {
882 882
                 //that thing was never cached anyways.
883 883
                 $obj_removed = null;
@@ -908,7 +908,7 @@  discard block
 block discarded – undo
908 908
         $current_cache_id = ''
909 909
     ) {
910 910
         // verify that incoming object is of the correct type
911
-        $obj_class = 'EE_' . $relationName;
911
+        $obj_class = 'EE_'.$relationName;
912 912
         if ($newly_saved_object instanceof $obj_class) {
913 913
             /* @type EE_Base_Class $newly_saved_object */
914 914
             // now get the type of relation
@@ -916,17 +916,17 @@  discard block
 block discarded – undo
916 916
             // if this is a 1:1 relationship
917 917
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
918 918
                 // then just replace the cached object with the newly saved object
919
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
919
+                $this->_model_relations[$relationName] = $newly_saved_object;
920 920
                 return true;
921 921
                 // or if it's some kind of sordid feral polyamorous relationship...
922 922
             }
923
-            if (is_array($this->_model_relations[ $relationName ])
924
-                      && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
923
+            if (is_array($this->_model_relations[$relationName])
924
+                      && isset($this->_model_relations[$relationName][$current_cache_id])
925 925
             ) {
926 926
                 // then remove the current cached item
927
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
927
+                unset($this->_model_relations[$relationName][$current_cache_id]);
928 928
                 // and cache the newly saved object using it's new ID
929
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
929
+                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
930 930
                 return true;
931 931
             }
932 932
         }
@@ -943,8 +943,8 @@  discard block
 block discarded – undo
943 943
      */
944 944
     public function get_one_from_cache($relationName)
945 945
     {
946
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
947
-            ? $this->_model_relations[ $relationName ]
946
+        $cached_array_or_object = isset($this->_model_relations[$relationName])
947
+            ? $this->_model_relations[$relationName]
948 948
             : null;
949 949
         if (is_array($cached_array_or_object)) {
950 950
             return array_shift($cached_array_or_object);
@@ -967,7 +967,7 @@  discard block
 block discarded – undo
967 967
      */
968 968
     public function get_all_from_cache($relationName)
969 969
     {
970
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
970
+        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
971 971
         // if the result is not an array, but exists, make it an array
972 972
         $objects = is_array($objects) ? $objects : array($objects);
973 973
         //bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
@@ -1151,7 +1151,7 @@  discard block
 block discarded – undo
1151 1151
             } else {
1152 1152
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1153 1153
             }
1154
-            $this->_fields[ $field_name ] = $field_value;
1154
+            $this->_fields[$field_name] = $field_value;
1155 1155
             $this->_clear_cached_property($field_name);
1156 1156
         }
1157 1157
     }
@@ -1191,9 +1191,9 @@  discard block
 block discarded – undo
1191 1191
     public function get_raw($field_name)
1192 1192
     {
1193 1193
         $field_settings = $this->get_model()->field_settings_for($field_name);
1194
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1195
-            ? $this->_fields[ $field_name ]->format('U')
1196
-            : $this->_fields[ $field_name ];
1194
+        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1195
+            ? $this->_fields[$field_name]->format('U')
1196
+            : $this->_fields[$field_name];
1197 1197
     }
1198 1198
 
1199 1199
 
@@ -1215,7 +1215,7 @@  discard block
 block discarded – undo
1215 1215
     public function get_DateTime_object($field_name)
1216 1216
     {
1217 1217
         $field_settings = $this->get_model()->field_settings_for($field_name);
1218
-        if (! $field_settings instanceof EE_Datetime_Field) {
1218
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1219 1219
             EE_Error::add_error(
1220 1220
                 sprintf(
1221 1221
                     esc_html__(
@@ -1473,7 +1473,7 @@  discard block
 block discarded – undo
1473 1473
      */
1474 1474
     public function get_i18n_datetime($field_name, $format = '')
1475 1475
     {
1476
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1476
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1477 1477
         return date_i18n(
1478 1478
             $format,
1479 1479
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -1585,19 +1585,19 @@  discard block
 block discarded – undo
1585 1585
         $field->set_time_format($this->_tm_frmt);
1586 1586
         switch ($what) {
1587 1587
             case 'T' :
1588
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1588
+                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1589 1589
                     $datetime_value,
1590
-                    $this->_fields[ $fieldname ]
1590
+                    $this->_fields[$fieldname]
1591 1591
                 );
1592 1592
                 break;
1593 1593
             case 'D' :
1594
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1594
+                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1595 1595
                     $datetime_value,
1596
-                    $this->_fields[ $fieldname ]
1596
+                    $this->_fields[$fieldname]
1597 1597
                 );
1598 1598
                 break;
1599 1599
             case 'B' :
1600
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1600
+                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1601 1601
                 break;
1602 1602
         }
1603 1603
         $this->_clear_cached_property($fieldname);
@@ -1639,7 +1639,7 @@  discard block
 block discarded – undo
1639 1639
         $this->set_timezone($timezone);
1640 1640
         $fn   = (array) $field_name;
1641 1641
         $args = array_merge($fn, (array) $args);
1642
-        if (! method_exists($this, $callback)) {
1642
+        if ( ! method_exists($this, $callback)) {
1643 1643
             throw new EE_Error(
1644 1644
                 sprintf(
1645 1645
                     esc_html__(
@@ -1651,7 +1651,7 @@  discard block
 block discarded – undo
1651 1651
             );
1652 1652
         }
1653 1653
         $args   = (array) $args;
1654
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1654
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1655 1655
         $this->set_timezone($original_timezone);
1656 1656
         return $return;
1657 1657
     }
@@ -1766,8 +1766,8 @@  discard block
 block discarded – undo
1766 1766
     {
1767 1767
         $model = $this->get_model();
1768 1768
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1769
-            if (! empty($this->_model_relations[ $relation_name ])) {
1770
-                $related_objects = $this->_model_relations[ $relation_name ];
1769
+            if ( ! empty($this->_model_relations[$relation_name])) {
1770
+                $related_objects = $this->_model_relations[$relation_name];
1771 1771
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
1772 1772
                     //this relation only stores a single model object, not an array
1773 1773
                     //but let's make it consistent
@@ -1824,7 +1824,7 @@  discard block
 block discarded – undo
1824 1824
             $this->set($column, $value);
1825 1825
         }
1826 1826
         // no changes ? then don't do anything
1827
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1827
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1828 1828
             return 0;
1829 1829
         }
1830 1830
         /**
@@ -1834,7 +1834,7 @@  discard block
 block discarded – undo
1834 1834
          * @param EE_Base_Class $model_object the model object about to be saved.
1835 1835
          */
1836 1836
         do_action('AHEE__EE_Base_Class__save__begin', $this);
1837
-        if (! $this->allow_persist()) {
1837
+        if ( ! $this->allow_persist()) {
1838 1838
             return 0;
1839 1839
         }
1840 1840
         // now get current attribute values
@@ -1849,10 +1849,10 @@  discard block
 block discarded – undo
1849 1849
         if ($model->has_primary_key_field()) {
1850 1850
             if ($model->get_primary_key_field()->is_auto_increment()) {
1851 1851
                 //ok check if it's set, if so: update; if not, insert
1852
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1852
+                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1853 1853
                     $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1854 1854
                 } else {
1855
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1855
+                    unset($save_cols_n_values[$model->primary_key_name()]);
1856 1856
                     $results = $model->insert($save_cols_n_values);
1857 1857
                     if ($results) {
1858 1858
                         //if successful, set the primary key
@@ -1862,7 +1862,7 @@  discard block
 block discarded – undo
1862 1862
                         //will get added to the mapper before we can add this one!
1863 1863
                         //but if we just avoid using the SET method, all that headache can be avoided
1864 1864
                         $pk_field_name                   = $model->primary_key_name();
1865
-                        $this->_fields[ $pk_field_name ] = $results;
1865
+                        $this->_fields[$pk_field_name] = $results;
1866 1866
                         $this->_clear_cached_property($pk_field_name);
1867 1867
                         $model->add_to_entity_map($this);
1868 1868
                         $this->_update_cached_related_model_objs_fks();
@@ -1879,8 +1879,8 @@  discard block
 block discarded – undo
1879 1879
                                     'event_espresso'
1880 1880
                                 ),
1881 1881
                                 get_class($this),
1882
-                                get_class($model) . '::instance()->add_to_entity_map()',
1883
-                                get_class($model) . '::instance()->get_one_by_ID()',
1882
+                                get_class($model).'::instance()->add_to_entity_map()',
1883
+                                get_class($model).'::instance()->get_one_by_ID()',
1884 1884
                                 '<br />'
1885 1885
                             )
1886 1886
                         );
@@ -1980,27 +1980,27 @@  discard block
 block discarded – undo
1980 1980
     public function save_new_cached_related_model_objs()
1981 1981
     {
1982 1982
         //make sure this has been saved
1983
-        if (! $this->ID()) {
1983
+        if ( ! $this->ID()) {
1984 1984
             $id = $this->save();
1985 1985
         } else {
1986 1986
             $id = $this->ID();
1987 1987
         }
1988 1988
         //now save all the NEW cached model objects  (ie they don't exist in the DB)
1989 1989
         foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1990
-            if ($this->_model_relations[ $relationName ]) {
1990
+            if ($this->_model_relations[$relationName]) {
1991 1991
                 //is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1992 1992
                 //or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1993 1993
                 /* @var $related_model_obj EE_Base_Class */
1994 1994
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
1995 1995
                     //add a relation to that relation type (which saves the appropriate thing in the process)
1996 1996
                     //but ONLY if it DOES NOT exist in the DB
1997
-                    $related_model_obj = $this->_model_relations[ $relationName ];
1997
+                    $related_model_obj = $this->_model_relations[$relationName];
1998 1998
                     //					if( ! $related_model_obj->ID()){
1999 1999
                     $this->_add_relation_to($related_model_obj, $relationName);
2000 2000
                     $related_model_obj->save_new_cached_related_model_objs();
2001 2001
                     //					}
2002 2002
                 } else {
2003
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2003
+                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
2004 2004
                         //add a relation to that relation type (which saves the appropriate thing in the process)
2005 2005
                         //but ONLY if it DOES NOT exist in the DB
2006 2006
                         //						if( ! $related_model_obj->ID()){
@@ -2027,7 +2027,7 @@  discard block
 block discarded – undo
2027 2027
      */
2028 2028
     public function get_model()
2029 2029
     {
2030
-        if (! $this->_model) {
2030
+        if ( ! $this->_model) {
2031 2031
             $modelName    = self::_get_model_classname(get_class($this));
2032 2032
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2033 2033
         } else {
@@ -2053,9 +2053,9 @@  discard block
 block discarded – undo
2053 2053
         $primary_id_ref = self::_get_primary_key_name($classname);
2054 2054
         if (
2055 2055
             array_key_exists($primary_id_ref, $props_n_values)
2056
-            && ! empty($props_n_values[ $primary_id_ref ])
2056
+            && ! empty($props_n_values[$primary_id_ref])
2057 2057
         ) {
2058
-            $id = $props_n_values[ $primary_id_ref ];
2058
+            $id = $props_n_values[$primary_id_ref];
2059 2059
             return self::_get_model($classname)->get_from_entity_map($id);
2060 2060
         }
2061 2061
         return false;
@@ -2089,10 +2089,10 @@  discard block
 block discarded – undo
2089 2089
         if ($model->has_primary_key_field()) {
2090 2090
             $primary_id_ref = self::_get_primary_key_name($classname);
2091 2091
             if (array_key_exists($primary_id_ref, $props_n_values)
2092
-                && ! empty($props_n_values[ $primary_id_ref ])
2092
+                && ! empty($props_n_values[$primary_id_ref])
2093 2093
             ) {
2094 2094
                 $existing = $model->get_one_by_ID(
2095
-                    $props_n_values[ $primary_id_ref ]
2095
+                    $props_n_values[$primary_id_ref]
2096 2096
                 );
2097 2097
             }
2098 2098
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -2104,7 +2104,7 @@  discard block
 block discarded – undo
2104 2104
         }
2105 2105
         if ($existing) {
2106 2106
             //set date formats if present before setting values
2107
-            if (! empty($date_formats) && is_array($date_formats)) {
2107
+            if ( ! empty($date_formats) && is_array($date_formats)) {
2108 2108
                 $existing->set_date_format($date_formats[0]);
2109 2109
                 $existing->set_time_format($date_formats[1]);
2110 2110
             } else {
@@ -2137,7 +2137,7 @@  discard block
 block discarded – undo
2137 2137
     protected static function _get_model($classname, $timezone = null)
2138 2138
     {
2139 2139
         //find model for this class
2140
-        if (! $classname) {
2140
+        if ( ! $classname) {
2141 2141
             throw new EE_Error(
2142 2142
                 sprintf(
2143 2143
                     esc_html__(
@@ -2186,7 +2186,7 @@  discard block
 block discarded – undo
2186 2186
         if (strpos($model_name, 'EE_') === 0) {
2187 2187
             $model_classname = str_replace('EE_', 'EEM_', $model_name);
2188 2188
         } else {
2189
-            $model_classname = 'EEM_' . $model_name;
2189
+            $model_classname = 'EEM_'.$model_name;
2190 2190
         }
2191 2191
         return $model_classname;
2192 2192
     }
@@ -2205,7 +2205,7 @@  discard block
 block discarded – undo
2205 2205
      */
2206 2206
     protected static function _get_primary_key_name($classname = null)
2207 2207
     {
2208
-        if (! $classname) {
2208
+        if ( ! $classname) {
2209 2209
             throw new EE_Error(
2210 2210
                 sprintf(
2211 2211
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -2235,7 +2235,7 @@  discard block
 block discarded – undo
2235 2235
         $model = $this->get_model();
2236 2236
         //now that we know the name of the variable, use a variable variable to get its value and return its
2237 2237
         if ($model->has_primary_key_field()) {
2238
-            return $this->_fields[ $model->primary_key_name() ];
2238
+            return $this->_fields[$model->primary_key_name()];
2239 2239
         }
2240 2240
         return $model->get_index_primary_key_string($this->_fields);
2241 2241
     }
@@ -2288,7 +2288,7 @@  discard block
 block discarded – undo
2288 2288
             }
2289 2289
         } else {
2290 2290
             //this thing doesn't exist in the DB,  so just cache it
2291
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2291
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2292 2292
                 throw new EE_Error(
2293 2293
                     sprintf(
2294 2294
                         esc_html__(
@@ -2453,7 +2453,7 @@  discard block
 block discarded – undo
2453 2453
             } else {
2454 2454
                 //did we already cache the result of this query?
2455 2455
                 $cached_results = $this->get_all_from_cache($relationName);
2456
-                if (! $cached_results) {
2456
+                if ( ! $cached_results) {
2457 2457
                     $related_model_objects = $this->get_model()->get_all_related(
2458 2458
                         $this,
2459 2459
                         $relationName,
@@ -2563,7 +2563,7 @@  discard block
 block discarded – undo
2563 2563
             } else {
2564 2564
                 //first, check if we've already cached the result of this query
2565 2565
                 $cached_result = $this->get_one_from_cache($relationName);
2566
-                if (! $cached_result) {
2566
+                if ( ! $cached_result) {
2567 2567
                     $related_model_object = $model->get_first_related(
2568 2568
                         $this,
2569 2569
                         $relationName,
@@ -2587,7 +2587,7 @@  discard block
 block discarded – undo
2587 2587
             }
2588 2588
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2589 2589
             // just get what's cached on this object
2590
-            if (! $related_model_object) {
2590
+            if ( ! $related_model_object) {
2591 2591
                 $related_model_object = $this->get_one_from_cache($relationName);
2592 2592
             }
2593 2593
         }
@@ -2669,7 +2669,7 @@  discard block
 block discarded – undo
2669 2669
      */
2670 2670
     public function is_set($field_name)
2671 2671
     {
2672
-        return isset($this->_fields[ $field_name ]);
2672
+        return isset($this->_fields[$field_name]);
2673 2673
     }
2674 2674
 
2675 2675
 
@@ -2685,7 +2685,7 @@  discard block
 block discarded – undo
2685 2685
     {
2686 2686
         foreach ((array) $properties as $property_name) {
2687 2687
             //first make sure this property exists
2688
-            if (! $this->_fields[ $property_name ]) {
2688
+            if ( ! $this->_fields[$property_name]) {
2689 2689
                 throw new EE_Error(
2690 2690
                     sprintf(
2691 2691
                         esc_html__(
@@ -2717,7 +2717,7 @@  discard block
 block discarded – undo
2717 2717
         $properties = array();
2718 2718
         //remove prepended underscore
2719 2719
         foreach ($fields as $field_name => $settings) {
2720
-            $properties[ $field_name ] = $this->get($field_name);
2720
+            $properties[$field_name] = $this->get($field_name);
2721 2721
         }
2722 2722
         return $properties;
2723 2723
     }
@@ -2754,7 +2754,7 @@  discard block
 block discarded – undo
2754 2754
     {
2755 2755
         $className = get_class($this);
2756 2756
         $tagName   = "FHEE__{$className}__{$methodName}";
2757
-        if (! has_filter($tagName)) {
2757
+        if ( ! has_filter($tagName)) {
2758 2758
             throw new EE_Error(
2759 2759
                 sprintf(
2760 2760
                     esc_html__(
@@ -2799,7 +2799,7 @@  discard block
 block discarded – undo
2799 2799
             $query_params[0]['EXM_value'] = $meta_value;
2800 2800
         }
2801 2801
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2802
-        if (! $existing_rows_like_that) {
2802
+        if ( ! $existing_rows_like_that) {
2803 2803
             return $this->add_extra_meta($meta_key, $meta_value);
2804 2804
         }
2805 2805
         foreach ($existing_rows_like_that as $existing_row) {
@@ -2917,7 +2917,7 @@  discard block
 block discarded – undo
2917 2917
                 $values = array();
2918 2918
                 foreach ($results as $result) {
2919 2919
                     if ($result instanceof EE_Extra_Meta) {
2920
-                        $values[ $result->ID() ] = $result->value();
2920
+                        $values[$result->ID()] = $result->value();
2921 2921
                     }
2922 2922
                 }
2923 2923
                 return $values;
@@ -2962,17 +2962,17 @@  discard block
 block discarded – undo
2962 2962
             );
2963 2963
             foreach ($extra_meta_objs as $extra_meta_obj) {
2964 2964
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2965
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2965
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2966 2966
                 }
2967 2967
             }
2968 2968
         } else {
2969 2969
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
2970 2970
             foreach ($extra_meta_objs as $extra_meta_obj) {
2971 2971
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2972
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2973
-                        $return_array[ $extra_meta_obj->key() ] = array();
2972
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2973
+                        $return_array[$extra_meta_obj->key()] = array();
2974 2974
                     }
2975
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2975
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2976 2976
                 }
2977 2977
             }
2978 2978
         }
@@ -3051,8 +3051,8 @@  discard block
 block discarded – undo
3051 3051
                         esc_html__('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3052 3052
                             'event_espresso'),
3053 3053
                         $this->ID(),
3054
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3055
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3054
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
3055
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
3056 3056
                     )
3057 3057
                 );
3058 3058
             }
@@ -3114,7 +3114,7 @@  discard block
 block discarded – undo
3114 3114
         $model = $this->get_model();
3115 3115
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3116 3116
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3117
-                $classname = 'EE_' . $model->get_this_model_name();
3117
+                $classname = 'EE_'.$model->get_this_model_name();
3118 3118
                 if (
3119 3119
                     $this->get_one_from_cache($relation_name) instanceof $classname
3120 3120
                     && $this->get_one_from_cache($relation_name)->ID()
Please login to merge, or discard this patch.