Completed
Branch FET-10785-ee-system-loader (19068c)
by
unknown
129:11 queued 116:44
created
core/libraries/rest_api/Model_Data_Translator.php 2 patches
Indentation   +521 added lines, -521 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 namespace EventEspresso\core\libraries\rest_api;
3 3
 
4 4
 if (! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 
8 8
 
@@ -26,525 +26,525 @@  discard block
 block discarded – undo
26 26
 class Model_Data_Translator
27 27
 {
28 28
 
29
-    /**
30
-     * We used to use -1 for infinity in the rest api, but that's ambiguous for
31
-     * fields that COULD contain -1; so we use null
32
-     */
33
-    const ee_inf_in_rest = null;
34
-
35
-
36
-
37
-    /**
38
-     * Prepares a possible array of input values from JSON for use by the models
39
-     *
40
-     * @param \EE_Model_Field_Base $field_obj
41
-     * @param mixed                $original_value_maybe_array
42
-     * @param string               $requested_version
43
-     * @param string               $timezone_string treat values as being in this timezone
44
-     * @return mixed
45
-     * @throws \DomainException
46
-     */
47
-    public static function prepare_field_values_from_json(
48
-        $field_obj,
49
-        $original_value_maybe_array,
50
-        $requested_version,
51
-        $timezone_string = 'UTC'
52
-    ) {
53
-        if (is_array($original_value_maybe_array)) {
54
-            $new_value_maybe_array = array();
55
-            foreach ($original_value_maybe_array as $array_key => $array_item) {
56
-                $new_value_maybe_array[$array_key] = Model_Data_Translator::prepare_field_value_from_json(
57
-                    $field_obj,
58
-                    $array_item,
59
-                    $requested_version,
60
-                    $timezone_string
61
-                );
62
-            }
63
-        } else {
64
-            $new_value_maybe_array = Model_Data_Translator::prepare_field_value_from_json(
65
-                $field_obj,
66
-                $original_value_maybe_array,
67
-                $requested_version,
68
-                $timezone_string
69
-            );
70
-        }
71
-        return $new_value_maybe_array;
72
-    }
73
-
74
-
75
-
76
-    /**
77
-     * Prepares an array of field values FOR use in JSON/REST API
78
-     *
79
-     * @param \EE_Model_Field_Base $field_obj
80
-     * @param mixed                $original_value_maybe_array
81
-     * @param string               $request_version (eg 4.8.36)
82
-     * @return array
83
-     */
84
-    public static function prepare_field_values_for_json($field_obj, $original_value_maybe_array, $request_version)
85
-    {
86
-        if (is_array($original_value_maybe_array)) {
87
-            $new_value_maybe_array = array();
88
-            foreach ($original_value_maybe_array as $array_key => $array_item) {
89
-                $new_value_maybe_array[$array_key] = Model_Data_Translator::prepare_field_value_for_json(
90
-                    $field_obj,
91
-                    $array_item,
92
-                    $request_version
93
-                );
94
-            }
95
-        } else {
96
-            $new_value_maybe_array = Model_Data_Translator::prepare_field_value_for_json(
97
-                $field_obj,
98
-                $original_value_maybe_array,
99
-                $request_version
100
-            );
101
-        }
102
-        return $new_value_maybe_array;
103
-    }
104
-
105
-
106
-
107
-    /**
108
-     * Prepares incoming data from the json or $_REQUEST parameters for the models'
109
-     * "$query_params".
110
-     *
111
-     * @param \EE_Model_Field_Base $field_obj
112
-     * @param mixed                $original_value
113
-     * @param string               $requested_version
114
-     * @param string               $timezone_string treat values as being in this timezone
115
-     * @return mixed
116
-     * @throws \DomainException
117
-     */
118
-    public static function prepare_field_value_from_json(
119
-        $field_obj,
120
-        $original_value,
121
-        $requested_version,
122
-        $timezone_string = 'UTC' // UTC
123
-    )
124
-    {
125
-        $timezone_string = $timezone_string !== '' ? $timezone_string : get_option('timezone_string', '');
126
-        $new_value = null;
127
-        if ($field_obj instanceof \EE_Infinite_Integer_Field
128
-            && in_array($original_value, array(null, ''), true)
129
-        ) {
130
-            $new_value = EE_INF;
131
-        } elseif ($field_obj instanceof \EE_Datetime_Field) {
132
-            list($offset_sign, $offset_secs) = Model_Data_Translator::parse_timezone_offset(
133
-                $field_obj->get_timezone_offset(
134
-                    new \DateTimeZone($timezone_string)
135
-                )
136
-            );
137
-            $offset_string =
138
-                str_pad(
139
-                    floor($offset_secs / HOUR_IN_SECONDS),
140
-                    2,
141
-                    '0',
142
-                    STR_PAD_LEFT
143
-                )
144
-                . ':'
145
-                . str_pad(
146
-                    ($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
147
-                    2,
148
-                    '0',
149
-                    STR_PAD_LEFT
150
-                );
151
-            $new_value = rest_parse_date($original_value . $offset_sign . $offset_string);
152
-        } else {
153
-            $new_value = $original_value;
154
-        }
155
-        return $new_value;
156
-    }
157
-
158
-
159
-
160
-    /**
161
-     * determines what's going on with them timezone strings
162
-     *
163
-     * @param int $timezone_offset
164
-     * @return array
165
-     */
166
-    private static function parse_timezone_offset($timezone_offset)
167
-    {
168
-        $first_char = substr((string)$timezone_offset, 0, 1);
169
-        if ($first_char === '+' || $first_char === '-') {
170
-            $offset_sign = $first_char;
171
-            $offset_secs = substr((string)$timezone_offset, 1);
172
-        } else {
173
-            $offset_sign = '+';
174
-            $offset_secs = $timezone_offset;
175
-        }
176
-        return array($offset_sign, $offset_secs);
177
-    }
178
-
179
-
180
-
181
-    /**
182
-     * Prepares a field's value for display in the API.
183
-     * The $original_value should be in the model object's domain of values, see the explanation at the top of EEM_Base.
184
-     * However, for backward compatibility, we also attempt to handle $original_values from the
185
-     * model client-code domain, and from the database domain.
186
-     * E.g., when working with EE_Datetime_Fields, $original_value should be a DateTime or DbSafeDateTime
187
-     * (model object domain). However, for backward compatibility, we also accept a unix timestamp
188
-     * (old model object domain), MySQL datetime string (database domain) or string formatted according to the
189
-     * WP Datetime format (model client-code domain)
190
-     *
191
-     * @param \EE_Model_Field_Base $field_obj
192
-     * @param mixed                $original_value
193
-     * @param string               $requested_version
194
-     * @return mixed
195
-     */
196
-    public static function prepare_field_value_for_json($field_obj, $original_value, $requested_version)
197
-    {
198
-        if ($original_value === EE_INF) {
199
-            $new_value = Model_Data_Translator::ee_inf_in_rest;
200
-        } elseif ($field_obj instanceof \EE_Datetime_Field) {
201
-            if (is_string($original_value)) {
202
-                //did they submit a string of a unix timestamp?
203
-                if (is_numeric($original_value)) {
204
-                    $datetime_obj = new \DateTime();
205
-                    $datetime_obj->setTimestamp((int)$original_value);
206
-                } else {
207
-                    //first, check if its a MySQL timestamp in GMT
208
-                    $datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
209
-                }
210
-                if (! $datetime_obj instanceof \DateTime) {
211
-                    //so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
212
-                    $datetime_obj = $field_obj->prepare_for_set($original_value);
213
-                }
214
-                $original_value = $datetime_obj;
215
-            }
216
-            if ($original_value instanceof \DateTime) {
217
-                $new_value = $original_value->format('Y-m-d H:i:s');
218
-            } elseif (is_int($original_value)) {
219
-                $new_value = date('Y-m-d H:i:s', $original_value);
220
-            } elseif($original_value === null || $original_value === '') {
221
-                $new_value = null;
222
-            } else {
223
-                //so it's not a datetime object, unix timestamp (as string or int),
224
-                //MySQL timestamp, or even a string in the field object's format. So no idea what it is
225
-                throw new \EE_Error(
226
-                    sprintf(
227
-                        esc_html__(
228
-                            // @codingStandardsIgnoreStart
229
-                            'The value "%1$s" for the field "%2$s" on model "%3$s" could not be understood. It should be a PHP DateTime, unix timestamp, MySQL date, or string in the format "%4$s".',
230
-                            // @codingStandardsIgnoreEnd
231
-                            'event_espressso'
232
-                        ),
233
-                        $original_value,
234
-                        $field_obj->get_name(),
235
-                        $field_obj->get_model_name(),
236
-                        $field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
237
-                    )
238
-                );
239
-            }
240
-            $new_value = mysql_to_rfc3339($new_value);
241
-        } else {
242
-            $new_value = $original_value;
243
-        }
244
-        return apply_filters(
245
-            'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
246
-            $new_value,
247
-            $field_obj,
248
-            $original_value,
249
-            $requested_version
250
-        );
251
-    }
252
-
253
-
254
-
255
-    /**
256
-     * Prepares condition-query-parameters (like what's in where and having) from
257
-     * the format expected in the API to use in the models
258
-     *
259
-     * @param array     $inputted_query_params_of_this_type
260
-     * @param \EEM_Base $model
261
-     * @param string    $requested_version
262
-     * @return array
263
-     * @throws \DomainException
264
-     * @throws \EE_Error
265
-     */
266
-    public static function prepare_conditions_query_params_for_models(
267
-        $inputted_query_params_of_this_type,
268
-        \EEM_Base $model,
269
-        $requested_version
270
-    ) {
271
-        $query_param_for_models = array();
272
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
273
-            $query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($query_param_key);
274
-            $field = Model_Data_Translator::deduce_field_from_query_param(
275
-                $query_param_sans_stars,
276
-                $model
277
-            );
278
-            //double-check is it a *_gmt field?
279
-            if (! $field instanceof \EE_Model_Field_Base
280
-                && Model_Data_Translator::is_gmt_date_field_name($query_param_sans_stars)
281
-            ) {
282
-                //yep, take off '_gmt', and find the field
283
-                $query_param_key = Model_Data_Translator::remove_gmt_from_field_name($query_param_sans_stars);
284
-                $field = Model_Data_Translator::deduce_field_from_query_param(
285
-                    $query_param_key,
286
-                    $model
287
-                );
288
-                $timezone = 'UTC';
289
-            } else {
290
-                //so it's not a GMT field. Set the timezone on the model to the default
291
-                $timezone = \EEH_DTT_Helper::get_valid_timezone_string();
292
-            }
293
-            if ($field instanceof \EE_Model_Field_Base) {
294
-                //did they specify an operator?
295
-                if (is_array($query_param_value)) {
296
-                    $op = $query_param_value[0];
297
-                    $translated_value = array($op);
298
-                    if (isset($query_param_value[1])) {
299
-                        $value = $query_param_value[1];
300
-                        $translated_value[1] = Model_Data_Translator::prepare_field_values_from_json($field, $value,
301
-                            $requested_version, $timezone);
302
-                    }
303
-                } else {
304
-                    $translated_value = Model_Data_Translator::prepare_field_value_from_json($field, $query_param_value,
305
-                        $requested_version, $timezone);
306
-                }
307
-                $query_param_for_models[$query_param_key] = $translated_value;
308
-            } else {
309
-                //so it's not for a field, assume it's a logic query param key
310
-                $query_param_for_models[$query_param_key] = Model_Data_Translator::prepare_conditions_query_params_for_models($query_param_value,
311
-                    $model, $requested_version);
312
-            }
313
-        }
314
-        return $query_param_for_models;
315
-    }
316
-
317
-
318
-
319
-    /**
320
-     * Mostly checks if the last 4 characters are "_gmt", indicating its a
321
-     * gmt date field name
322
-     *
323
-     * @param string $field_name
324
-     * @return boolean
325
-     */
326
-    public static function is_gmt_date_field_name($field_name)
327
-    {
328
-        return substr(
329
-                   Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name),
330
-                   -4,
331
-                   4
332
-               ) === '_gmt';
333
-    }
334
-
335
-
336
-
337
-    /**
338
-     * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
339
-     *
340
-     * @param string $field_name
341
-     * @return string
342
-     */
343
-    public static function remove_gmt_from_field_name($field_name)
344
-    {
345
-        if (! Model_Data_Translator::is_gmt_date_field_name($field_name)) {
346
-            return $field_name;
347
-        }
348
-        $query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name);
349
-        $query_param_sans_gmt_and_sans_stars = substr(
350
-            $query_param_sans_stars,
351
-            0,
352
-            strrpos(
353
-                $field_name,
354
-                '_gmt'
355
-            )
356
-        );
357
-        return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
358
-    }
359
-
360
-
361
-
362
-    /**
363
-     * Takes a field name from the REST API and prepares it for the model querying
364
-     *
365
-     * @param string $field_name
366
-     * @return string
367
-     */
368
-    public static function prepare_field_name_from_json($field_name)
369
-    {
370
-        if (Model_Data_Translator::is_gmt_date_field_name($field_name)) {
371
-            return Model_Data_Translator::remove_gmt_from_field_name($field_name);
372
-        }
373
-        return $field_name;
374
-    }
375
-
376
-
377
-
378
-    /**
379
-     * Takes array of field names from REST API and prepares for models
380
-     *
381
-     * @param array $field_names
382
-     * @return array of field names (possibly include model prefixes)
383
-     */
384
-    public static function prepare_field_names_from_json(array $field_names)
385
-    {
386
-        $new_array = array();
387
-        foreach ($field_names as $key => $field_name) {
388
-            $new_array[$key] = Model_Data_Translator::prepare_field_name_from_json($field_name);
389
-        }
390
-        return $new_array;
391
-    }
392
-
393
-
394
-
395
-    /**
396
-     * Takes array where array keys are field names (possibly with model path prefixes)
397
-     * from the REST API and prepares them for model querying
398
-     *
399
-     * @param array $field_names_as_keys
400
-     * @return array
401
-     */
402
-    public static function prepare_field_names_in_array_keys_from_json(array $field_names_as_keys)
403
-    {
404
-        $new_array = array();
405
-        foreach ($field_names_as_keys as $field_name => $value) {
406
-            $new_array[Model_Data_Translator::prepare_field_name_from_json($field_name)] = $value;
407
-        }
408
-        return $new_array;
409
-    }
410
-
411
-
412
-
413
-    /**
414
-     * Prepares an array of model query params for use in the REST API
415
-     *
416
-     * @param array     $model_query_params
417
-     * @param \EEM_Base $model
418
-     * @param string    $requested_version eg "4.8.36". If null is provided, defaults to the latest release of the EE4
419
-     *                                     REST API
420
-     * @return array which can be passed into the EE4 REST API when querying a model resource
421
-     * @throws \EE_Error
422
-     */
423
-    public static function prepare_query_params_for_rest_api(
424
-        array $model_query_params,
425
-        \EEM_Base $model,
426
-        $requested_version = null
427
-    ) {
428
-        if ($requested_version === null) {
429
-            $requested_version = \EED_Core_Rest_Api::latest_rest_api_version();
430
-        }
431
-        $rest_query_params = $model_query_params;
432
-        if (isset($model_query_params[0])) {
433
-            $rest_query_params['where'] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api(
434
-                $model_query_params[0],
435
-                $model,
436
-                $requested_version
437
-            );
438
-            unset($rest_query_params[0]);
439
-        }
440
-        if (isset($model_query_params['having'])) {
441
-            $rest_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api(
442
-                $model_query_params['having'],
443
-                $model,
444
-                $requested_version
445
-            );
446
-        }
447
-        return apply_filters('FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
448
-            $rest_query_params, $model_query_params, $model, $requested_version);
449
-    }
450
-
451
-
452
-
453
-    /**
454
-     * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
455
-     *
456
-     * @param array     $inputted_query_params_of_this_type eg like the "where" or "having" conditions query params
457
-     *                                                      passed into EEM_Base::get_all()
458
-     * @param \EEM_Base $model
459
-     * @param string    $requested_version                  eg "4.8.36"
460
-     * @return array ready for use in the rest api query params
461
-     * @throws \EE_Error
462
-     */
463
-    public static function prepare_conditions_query_params_for_rest_api(
464
-        $inputted_query_params_of_this_type,
465
-        \EEM_Base $model,
466
-        $requested_version
467
-    ) {
468
-        $query_param_for_models = array();
469
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
470
-            $field = Model_Data_Translator::deduce_field_from_query_param(
471
-                Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($query_param_key),
472
-                $model
473
-            );
474
-            if ($field instanceof \EE_Model_Field_Base) {
475
-                //did they specify an operator?
476
-                if (is_array($query_param_value)) {
477
-                    $op = $query_param_value[0];
478
-                    $translated_value = array($op);
479
-                    if (isset($query_param_value[1])) {
480
-                        $value = $query_param_value[1];
481
-                        $translated_value[1] = Model_Data_Translator::prepare_field_values_for_json($field, $value,
482
-                            $requested_version);
483
-                    }
484
-                } else {
485
-                    $translated_value = Model_Data_Translator::prepare_field_value_for_json($field, $query_param_value,
486
-                        $requested_version);
487
-                }
488
-                $query_param_for_models[$query_param_key] = $translated_value;
489
-            } else {
490
-                //so it's not for a field, assume it's a logic query param key
491
-                $query_param_for_models[$query_param_key] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api($query_param_value,
492
-                    $model, $requested_version);
493
-            }
494
-        }
495
-        return $query_param_for_models;
496
-    }
497
-
498
-
499
-
500
-    /**
501
-     * @param $condition_query_param_key
502
-     * @return string
503
-     */
504
-    public static function remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
505
-    {
506
-        $pos_of_star = strpos($condition_query_param_key, '*');
507
-        if ($pos_of_star === false) {
508
-            return $condition_query_param_key;
509
-        } else {
510
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
511
-            return $condition_query_param_sans_star;
512
-        }
513
-    }
514
-
515
-
516
-
517
-    /**
518
-     * Takes the input parameter and finds the model field that it indicates.
519
-     *
520
-     * @param string    $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
521
-     * @param \EEM_Base $model
522
-     * @return \EE_Model_Field_Base
523
-     * @throws \EE_Error
524
-     */
525
-    public static function deduce_field_from_query_param($query_param_name, \EEM_Base $model)
526
-    {
527
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
528
-        //which will help us find the database table and column
529
-        $query_param_parts = explode('.', $query_param_name);
530
-        if (empty($query_param_parts)) {
531
-            throw new \EE_Error(sprintf(__('_extract_column_name is empty when trying to extract column and table name from %s',
532
-                'event_espresso'), $query_param_name));
533
-        }
534
-        $number_of_parts = count($query_param_parts);
535
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
536
-        if ($number_of_parts === 1) {
537
-            $field_name = $last_query_param_part;
538
-        } else {// $number_of_parts >= 2
539
-            //the last part is the column name, and there are only 2parts. therefore...
540
-            $field_name = $last_query_param_part;
541
-            $model = \EE_Registry::instance()->load_model($query_param_parts[$number_of_parts - 2]);
542
-        }
543
-        try {
544
-            return $model->field_settings_for($field_name);
545
-        } catch (\EE_Error $e) {
546
-            return null;
547
-        }
548
-    }
29
+	/**
30
+	 * We used to use -1 for infinity in the rest api, but that's ambiguous for
31
+	 * fields that COULD contain -1; so we use null
32
+	 */
33
+	const ee_inf_in_rest = null;
34
+
35
+
36
+
37
+	/**
38
+	 * Prepares a possible array of input values from JSON for use by the models
39
+	 *
40
+	 * @param \EE_Model_Field_Base $field_obj
41
+	 * @param mixed                $original_value_maybe_array
42
+	 * @param string               $requested_version
43
+	 * @param string               $timezone_string treat values as being in this timezone
44
+	 * @return mixed
45
+	 * @throws \DomainException
46
+	 */
47
+	public static function prepare_field_values_from_json(
48
+		$field_obj,
49
+		$original_value_maybe_array,
50
+		$requested_version,
51
+		$timezone_string = 'UTC'
52
+	) {
53
+		if (is_array($original_value_maybe_array)) {
54
+			$new_value_maybe_array = array();
55
+			foreach ($original_value_maybe_array as $array_key => $array_item) {
56
+				$new_value_maybe_array[$array_key] = Model_Data_Translator::prepare_field_value_from_json(
57
+					$field_obj,
58
+					$array_item,
59
+					$requested_version,
60
+					$timezone_string
61
+				);
62
+			}
63
+		} else {
64
+			$new_value_maybe_array = Model_Data_Translator::prepare_field_value_from_json(
65
+				$field_obj,
66
+				$original_value_maybe_array,
67
+				$requested_version,
68
+				$timezone_string
69
+			);
70
+		}
71
+		return $new_value_maybe_array;
72
+	}
73
+
74
+
75
+
76
+	/**
77
+	 * Prepares an array of field values FOR use in JSON/REST API
78
+	 *
79
+	 * @param \EE_Model_Field_Base $field_obj
80
+	 * @param mixed                $original_value_maybe_array
81
+	 * @param string               $request_version (eg 4.8.36)
82
+	 * @return array
83
+	 */
84
+	public static function prepare_field_values_for_json($field_obj, $original_value_maybe_array, $request_version)
85
+	{
86
+		if (is_array($original_value_maybe_array)) {
87
+			$new_value_maybe_array = array();
88
+			foreach ($original_value_maybe_array as $array_key => $array_item) {
89
+				$new_value_maybe_array[$array_key] = Model_Data_Translator::prepare_field_value_for_json(
90
+					$field_obj,
91
+					$array_item,
92
+					$request_version
93
+				);
94
+			}
95
+		} else {
96
+			$new_value_maybe_array = Model_Data_Translator::prepare_field_value_for_json(
97
+				$field_obj,
98
+				$original_value_maybe_array,
99
+				$request_version
100
+			);
101
+		}
102
+		return $new_value_maybe_array;
103
+	}
104
+
105
+
106
+
107
+	/**
108
+	 * Prepares incoming data from the json or $_REQUEST parameters for the models'
109
+	 * "$query_params".
110
+	 *
111
+	 * @param \EE_Model_Field_Base $field_obj
112
+	 * @param mixed                $original_value
113
+	 * @param string               $requested_version
114
+	 * @param string               $timezone_string treat values as being in this timezone
115
+	 * @return mixed
116
+	 * @throws \DomainException
117
+	 */
118
+	public static function prepare_field_value_from_json(
119
+		$field_obj,
120
+		$original_value,
121
+		$requested_version,
122
+		$timezone_string = 'UTC' // UTC
123
+	)
124
+	{
125
+		$timezone_string = $timezone_string !== '' ? $timezone_string : get_option('timezone_string', '');
126
+		$new_value = null;
127
+		if ($field_obj instanceof \EE_Infinite_Integer_Field
128
+			&& in_array($original_value, array(null, ''), true)
129
+		) {
130
+			$new_value = EE_INF;
131
+		} elseif ($field_obj instanceof \EE_Datetime_Field) {
132
+			list($offset_sign, $offset_secs) = Model_Data_Translator::parse_timezone_offset(
133
+				$field_obj->get_timezone_offset(
134
+					new \DateTimeZone($timezone_string)
135
+				)
136
+			);
137
+			$offset_string =
138
+				str_pad(
139
+					floor($offset_secs / HOUR_IN_SECONDS),
140
+					2,
141
+					'0',
142
+					STR_PAD_LEFT
143
+				)
144
+				. ':'
145
+				. str_pad(
146
+					($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
147
+					2,
148
+					'0',
149
+					STR_PAD_LEFT
150
+				);
151
+			$new_value = rest_parse_date($original_value . $offset_sign . $offset_string);
152
+		} else {
153
+			$new_value = $original_value;
154
+		}
155
+		return $new_value;
156
+	}
157
+
158
+
159
+
160
+	/**
161
+	 * determines what's going on with them timezone strings
162
+	 *
163
+	 * @param int $timezone_offset
164
+	 * @return array
165
+	 */
166
+	private static function parse_timezone_offset($timezone_offset)
167
+	{
168
+		$first_char = substr((string)$timezone_offset, 0, 1);
169
+		if ($first_char === '+' || $first_char === '-') {
170
+			$offset_sign = $first_char;
171
+			$offset_secs = substr((string)$timezone_offset, 1);
172
+		} else {
173
+			$offset_sign = '+';
174
+			$offset_secs = $timezone_offset;
175
+		}
176
+		return array($offset_sign, $offset_secs);
177
+	}
178
+
179
+
180
+
181
+	/**
182
+	 * Prepares a field's value for display in the API.
183
+	 * The $original_value should be in the model object's domain of values, see the explanation at the top of EEM_Base.
184
+	 * However, for backward compatibility, we also attempt to handle $original_values from the
185
+	 * model client-code domain, and from the database domain.
186
+	 * E.g., when working with EE_Datetime_Fields, $original_value should be a DateTime or DbSafeDateTime
187
+	 * (model object domain). However, for backward compatibility, we also accept a unix timestamp
188
+	 * (old model object domain), MySQL datetime string (database domain) or string formatted according to the
189
+	 * WP Datetime format (model client-code domain)
190
+	 *
191
+	 * @param \EE_Model_Field_Base $field_obj
192
+	 * @param mixed                $original_value
193
+	 * @param string               $requested_version
194
+	 * @return mixed
195
+	 */
196
+	public static function prepare_field_value_for_json($field_obj, $original_value, $requested_version)
197
+	{
198
+		if ($original_value === EE_INF) {
199
+			$new_value = Model_Data_Translator::ee_inf_in_rest;
200
+		} elseif ($field_obj instanceof \EE_Datetime_Field) {
201
+			if (is_string($original_value)) {
202
+				//did they submit a string of a unix timestamp?
203
+				if (is_numeric($original_value)) {
204
+					$datetime_obj = new \DateTime();
205
+					$datetime_obj->setTimestamp((int)$original_value);
206
+				} else {
207
+					//first, check if its a MySQL timestamp in GMT
208
+					$datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
209
+				}
210
+				if (! $datetime_obj instanceof \DateTime) {
211
+					//so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
212
+					$datetime_obj = $field_obj->prepare_for_set($original_value);
213
+				}
214
+				$original_value = $datetime_obj;
215
+			}
216
+			if ($original_value instanceof \DateTime) {
217
+				$new_value = $original_value->format('Y-m-d H:i:s');
218
+			} elseif (is_int($original_value)) {
219
+				$new_value = date('Y-m-d H:i:s', $original_value);
220
+			} elseif($original_value === null || $original_value === '') {
221
+				$new_value = null;
222
+			} else {
223
+				//so it's not a datetime object, unix timestamp (as string or int),
224
+				//MySQL timestamp, or even a string in the field object's format. So no idea what it is
225
+				throw new \EE_Error(
226
+					sprintf(
227
+						esc_html__(
228
+							// @codingStandardsIgnoreStart
229
+							'The value "%1$s" for the field "%2$s" on model "%3$s" could not be understood. It should be a PHP DateTime, unix timestamp, MySQL date, or string in the format "%4$s".',
230
+							// @codingStandardsIgnoreEnd
231
+							'event_espressso'
232
+						),
233
+						$original_value,
234
+						$field_obj->get_name(),
235
+						$field_obj->get_model_name(),
236
+						$field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
237
+					)
238
+				);
239
+			}
240
+			$new_value = mysql_to_rfc3339($new_value);
241
+		} else {
242
+			$new_value = $original_value;
243
+		}
244
+		return apply_filters(
245
+			'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
246
+			$new_value,
247
+			$field_obj,
248
+			$original_value,
249
+			$requested_version
250
+		);
251
+	}
252
+
253
+
254
+
255
+	/**
256
+	 * Prepares condition-query-parameters (like what's in where and having) from
257
+	 * the format expected in the API to use in the models
258
+	 *
259
+	 * @param array     $inputted_query_params_of_this_type
260
+	 * @param \EEM_Base $model
261
+	 * @param string    $requested_version
262
+	 * @return array
263
+	 * @throws \DomainException
264
+	 * @throws \EE_Error
265
+	 */
266
+	public static function prepare_conditions_query_params_for_models(
267
+		$inputted_query_params_of_this_type,
268
+		\EEM_Base $model,
269
+		$requested_version
270
+	) {
271
+		$query_param_for_models = array();
272
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
273
+			$query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($query_param_key);
274
+			$field = Model_Data_Translator::deduce_field_from_query_param(
275
+				$query_param_sans_stars,
276
+				$model
277
+			);
278
+			//double-check is it a *_gmt field?
279
+			if (! $field instanceof \EE_Model_Field_Base
280
+				&& Model_Data_Translator::is_gmt_date_field_name($query_param_sans_stars)
281
+			) {
282
+				//yep, take off '_gmt', and find the field
283
+				$query_param_key = Model_Data_Translator::remove_gmt_from_field_name($query_param_sans_stars);
284
+				$field = Model_Data_Translator::deduce_field_from_query_param(
285
+					$query_param_key,
286
+					$model
287
+				);
288
+				$timezone = 'UTC';
289
+			} else {
290
+				//so it's not a GMT field. Set the timezone on the model to the default
291
+				$timezone = \EEH_DTT_Helper::get_valid_timezone_string();
292
+			}
293
+			if ($field instanceof \EE_Model_Field_Base) {
294
+				//did they specify an operator?
295
+				if (is_array($query_param_value)) {
296
+					$op = $query_param_value[0];
297
+					$translated_value = array($op);
298
+					if (isset($query_param_value[1])) {
299
+						$value = $query_param_value[1];
300
+						$translated_value[1] = Model_Data_Translator::prepare_field_values_from_json($field, $value,
301
+							$requested_version, $timezone);
302
+					}
303
+				} else {
304
+					$translated_value = Model_Data_Translator::prepare_field_value_from_json($field, $query_param_value,
305
+						$requested_version, $timezone);
306
+				}
307
+				$query_param_for_models[$query_param_key] = $translated_value;
308
+			} else {
309
+				//so it's not for a field, assume it's a logic query param key
310
+				$query_param_for_models[$query_param_key] = Model_Data_Translator::prepare_conditions_query_params_for_models($query_param_value,
311
+					$model, $requested_version);
312
+			}
313
+		}
314
+		return $query_param_for_models;
315
+	}
316
+
317
+
318
+
319
+	/**
320
+	 * Mostly checks if the last 4 characters are "_gmt", indicating its a
321
+	 * gmt date field name
322
+	 *
323
+	 * @param string $field_name
324
+	 * @return boolean
325
+	 */
326
+	public static function is_gmt_date_field_name($field_name)
327
+	{
328
+		return substr(
329
+				   Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name),
330
+				   -4,
331
+				   4
332
+			   ) === '_gmt';
333
+	}
334
+
335
+
336
+
337
+	/**
338
+	 * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
339
+	 *
340
+	 * @param string $field_name
341
+	 * @return string
342
+	 */
343
+	public static function remove_gmt_from_field_name($field_name)
344
+	{
345
+		if (! Model_Data_Translator::is_gmt_date_field_name($field_name)) {
346
+			return $field_name;
347
+		}
348
+		$query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name);
349
+		$query_param_sans_gmt_and_sans_stars = substr(
350
+			$query_param_sans_stars,
351
+			0,
352
+			strrpos(
353
+				$field_name,
354
+				'_gmt'
355
+			)
356
+		);
357
+		return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
358
+	}
359
+
360
+
361
+
362
+	/**
363
+	 * Takes a field name from the REST API and prepares it for the model querying
364
+	 *
365
+	 * @param string $field_name
366
+	 * @return string
367
+	 */
368
+	public static function prepare_field_name_from_json($field_name)
369
+	{
370
+		if (Model_Data_Translator::is_gmt_date_field_name($field_name)) {
371
+			return Model_Data_Translator::remove_gmt_from_field_name($field_name);
372
+		}
373
+		return $field_name;
374
+	}
375
+
376
+
377
+
378
+	/**
379
+	 * Takes array of field names from REST API and prepares for models
380
+	 *
381
+	 * @param array $field_names
382
+	 * @return array of field names (possibly include model prefixes)
383
+	 */
384
+	public static function prepare_field_names_from_json(array $field_names)
385
+	{
386
+		$new_array = array();
387
+		foreach ($field_names as $key => $field_name) {
388
+			$new_array[$key] = Model_Data_Translator::prepare_field_name_from_json($field_name);
389
+		}
390
+		return $new_array;
391
+	}
392
+
393
+
394
+
395
+	/**
396
+	 * Takes array where array keys are field names (possibly with model path prefixes)
397
+	 * from the REST API and prepares them for model querying
398
+	 *
399
+	 * @param array $field_names_as_keys
400
+	 * @return array
401
+	 */
402
+	public static function prepare_field_names_in_array_keys_from_json(array $field_names_as_keys)
403
+	{
404
+		$new_array = array();
405
+		foreach ($field_names_as_keys as $field_name => $value) {
406
+			$new_array[Model_Data_Translator::prepare_field_name_from_json($field_name)] = $value;
407
+		}
408
+		return $new_array;
409
+	}
410
+
411
+
412
+
413
+	/**
414
+	 * Prepares an array of model query params for use in the REST API
415
+	 *
416
+	 * @param array     $model_query_params
417
+	 * @param \EEM_Base $model
418
+	 * @param string    $requested_version eg "4.8.36". If null is provided, defaults to the latest release of the EE4
419
+	 *                                     REST API
420
+	 * @return array which can be passed into the EE4 REST API when querying a model resource
421
+	 * @throws \EE_Error
422
+	 */
423
+	public static function prepare_query_params_for_rest_api(
424
+		array $model_query_params,
425
+		\EEM_Base $model,
426
+		$requested_version = null
427
+	) {
428
+		if ($requested_version === null) {
429
+			$requested_version = \EED_Core_Rest_Api::latest_rest_api_version();
430
+		}
431
+		$rest_query_params = $model_query_params;
432
+		if (isset($model_query_params[0])) {
433
+			$rest_query_params['where'] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api(
434
+				$model_query_params[0],
435
+				$model,
436
+				$requested_version
437
+			);
438
+			unset($rest_query_params[0]);
439
+		}
440
+		if (isset($model_query_params['having'])) {
441
+			$rest_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api(
442
+				$model_query_params['having'],
443
+				$model,
444
+				$requested_version
445
+			);
446
+		}
447
+		return apply_filters('FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
448
+			$rest_query_params, $model_query_params, $model, $requested_version);
449
+	}
450
+
451
+
452
+
453
+	/**
454
+	 * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
455
+	 *
456
+	 * @param array     $inputted_query_params_of_this_type eg like the "where" or "having" conditions query params
457
+	 *                                                      passed into EEM_Base::get_all()
458
+	 * @param \EEM_Base $model
459
+	 * @param string    $requested_version                  eg "4.8.36"
460
+	 * @return array ready for use in the rest api query params
461
+	 * @throws \EE_Error
462
+	 */
463
+	public static function prepare_conditions_query_params_for_rest_api(
464
+		$inputted_query_params_of_this_type,
465
+		\EEM_Base $model,
466
+		$requested_version
467
+	) {
468
+		$query_param_for_models = array();
469
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
470
+			$field = Model_Data_Translator::deduce_field_from_query_param(
471
+				Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($query_param_key),
472
+				$model
473
+			);
474
+			if ($field instanceof \EE_Model_Field_Base) {
475
+				//did they specify an operator?
476
+				if (is_array($query_param_value)) {
477
+					$op = $query_param_value[0];
478
+					$translated_value = array($op);
479
+					if (isset($query_param_value[1])) {
480
+						$value = $query_param_value[1];
481
+						$translated_value[1] = Model_Data_Translator::prepare_field_values_for_json($field, $value,
482
+							$requested_version);
483
+					}
484
+				} else {
485
+					$translated_value = Model_Data_Translator::prepare_field_value_for_json($field, $query_param_value,
486
+						$requested_version);
487
+				}
488
+				$query_param_for_models[$query_param_key] = $translated_value;
489
+			} else {
490
+				//so it's not for a field, assume it's a logic query param key
491
+				$query_param_for_models[$query_param_key] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api($query_param_value,
492
+					$model, $requested_version);
493
+			}
494
+		}
495
+		return $query_param_for_models;
496
+	}
497
+
498
+
499
+
500
+	/**
501
+	 * @param $condition_query_param_key
502
+	 * @return string
503
+	 */
504
+	public static function remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
505
+	{
506
+		$pos_of_star = strpos($condition_query_param_key, '*');
507
+		if ($pos_of_star === false) {
508
+			return $condition_query_param_key;
509
+		} else {
510
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
511
+			return $condition_query_param_sans_star;
512
+		}
513
+	}
514
+
515
+
516
+
517
+	/**
518
+	 * Takes the input parameter and finds the model field that it indicates.
519
+	 *
520
+	 * @param string    $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
521
+	 * @param \EEM_Base $model
522
+	 * @return \EE_Model_Field_Base
523
+	 * @throws \EE_Error
524
+	 */
525
+	public static function deduce_field_from_query_param($query_param_name, \EEM_Base $model)
526
+	{
527
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
528
+		//which will help us find the database table and column
529
+		$query_param_parts = explode('.', $query_param_name);
530
+		if (empty($query_param_parts)) {
531
+			throw new \EE_Error(sprintf(__('_extract_column_name is empty when trying to extract column and table name from %s',
532
+				'event_espresso'), $query_param_name));
533
+		}
534
+		$number_of_parts = count($query_param_parts);
535
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
536
+		if ($number_of_parts === 1) {
537
+			$field_name = $last_query_param_part;
538
+		} else {// $number_of_parts >= 2
539
+			//the last part is the column name, and there are only 2parts. therefore...
540
+			$field_name = $last_query_param_part;
541
+			$model = \EE_Registry::instance()->load_model($query_param_parts[$number_of_parts - 2]);
542
+		}
543
+		try {
544
+			return $model->field_settings_for($field_name);
545
+		} catch (\EE_Error $e) {
546
+			return null;
547
+		}
548
+	}
549 549
 
550 550
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 namespace EventEspresso\core\libraries\rest_api;
3 3
 
4
-if (! defined('EVENT_ESPRESSO_VERSION')) {
4
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5 5
     exit('No direct script access allowed');
6 6
 }
7 7
 
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
                     '0',
149 149
                     STR_PAD_LEFT
150 150
                 );
151
-            $new_value = rest_parse_date($original_value . $offset_sign . $offset_string);
151
+            $new_value = rest_parse_date($original_value.$offset_sign.$offset_string);
152 152
         } else {
153 153
             $new_value = $original_value;
154 154
         }
@@ -165,10 +165,10 @@  discard block
 block discarded – undo
165 165
      */
166 166
     private static function parse_timezone_offset($timezone_offset)
167 167
     {
168
-        $first_char = substr((string)$timezone_offset, 0, 1);
168
+        $first_char = substr((string) $timezone_offset, 0, 1);
169 169
         if ($first_char === '+' || $first_char === '-') {
170 170
             $offset_sign = $first_char;
171
-            $offset_secs = substr((string)$timezone_offset, 1);
171
+            $offset_secs = substr((string) $timezone_offset, 1);
172 172
         } else {
173 173
             $offset_sign = '+';
174 174
             $offset_secs = $timezone_offset;
@@ -202,12 +202,12 @@  discard block
 block discarded – undo
202 202
                 //did they submit a string of a unix timestamp?
203 203
                 if (is_numeric($original_value)) {
204 204
                     $datetime_obj = new \DateTime();
205
-                    $datetime_obj->setTimestamp((int)$original_value);
205
+                    $datetime_obj->setTimestamp((int) $original_value);
206 206
                 } else {
207 207
                     //first, check if its a MySQL timestamp in GMT
208 208
                     $datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
209 209
                 }
210
-                if (! $datetime_obj instanceof \DateTime) {
210
+                if ( ! $datetime_obj instanceof \DateTime) {
211 211
                     //so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
212 212
                     $datetime_obj = $field_obj->prepare_for_set($original_value);
213 213
                 }
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
                 $new_value = $original_value->format('Y-m-d H:i:s');
218 218
             } elseif (is_int($original_value)) {
219 219
                 $new_value = date('Y-m-d H:i:s', $original_value);
220
-            } elseif($original_value === null || $original_value === '') {
220
+            } elseif ($original_value === null || $original_value === '') {
221 221
                 $new_value = null;
222 222
             } else {
223 223
                 //so it's not a datetime object, unix timestamp (as string or int),
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
                         $original_value,
234 234
                         $field_obj->get_name(),
235 235
                         $field_obj->get_model_name(),
236
-                        $field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
236
+                        $field_obj->get_time_format().' '.$field_obj->get_time_format()
237 237
                     )
238 238
                 );
239 239
             }
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
                 $model
277 277
             );
278 278
             //double-check is it a *_gmt field?
279
-            if (! $field instanceof \EE_Model_Field_Base
279
+            if ( ! $field instanceof \EE_Model_Field_Base
280 280
                 && Model_Data_Translator::is_gmt_date_field_name($query_param_sans_stars)
281 281
             ) {
282 282
                 //yep, take off '_gmt', and find the field
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
      */
343 343
     public static function remove_gmt_from_field_name($field_name)
344 344
     {
345
-        if (! Model_Data_Translator::is_gmt_date_field_name($field_name)) {
345
+        if ( ! Model_Data_Translator::is_gmt_date_field_name($field_name)) {
346 346
             return $field_name;
347 347
         }
348 348
         $query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name);
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +18 added lines, -16 removed lines patch added patch discarded remove patch
@@ -960,7 +960,7 @@  discard block
 block discarded – undo
960 960
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961 961
      * foreign key to the WP_User table)
962 962
      *
963
-     * @return string|boolean string on success, boolean false when there is no
963
+     * @return string|false string on success, boolean false when there is no
964 964
      * foreign key to the WP_User table
965 965
      */
966 966
     public function wp_user_field_name()
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
      *
1067 1067
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1068 1068
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1069
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070 1070
      *                                  fields on the model, and the models we joined to in the query. However, you can
1071 1071
      *                                  override this and set the select to "*", or a specific column name, like
1072 1072
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1458,7 +1458,7 @@  discard block
 block discarded – undo
1458 1458
      * @param string $field_name The name of the field the formats are being retrieved for.
1459 1459
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460 1460
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1461
+     * @return string[] formats in an array with the date format first, and the time format last.
1462 1462
      */
1463 1463
     public function get_formats_for($field_name, $pretty = false)
1464 1464
     {
@@ -1491,7 +1491,7 @@  discard block
 block discarded – undo
1491 1491
      *                                 be returned.
1492 1492
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1493 1493
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1494
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1494
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1495 1495
      *                                 exception is triggered.
1496 1496
      */
1497 1497
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1531,7 +1531,7 @@  discard block
 block discarded – undo
1531 1531
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1532 1532
      *                                format is
1533 1533
      *                                'U', this is ignored.
1534
-     * @return DateTime
1534
+     * @return string
1535 1535
      * @throws \EE_Error
1536 1536
      */
1537 1537
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -1829,7 +1829,7 @@  discard block
 block discarded – undo
1829 1829
      * Wrapper for EEM_Base::delete_permanently()
1830 1830
      *
1831 1831
      * @param mixed $id
1832
-     * @return boolean whether the row got deleted or not
1832
+     * @return integer whether the row got deleted or not
1833 1833
      * @throws \EE_Error
1834 1834
      */
1835 1835
     public function delete_permanently_by_ID($id)
@@ -1849,7 +1849,7 @@  discard block
 block discarded – undo
1849 1849
      * Wrapper for EEM_Base::delete()
1850 1850
      *
1851 1851
      * @param mixed $id
1852
-     * @return boolean whether the row got deleted or not
1852
+     * @return integer whether the row got deleted or not
1853 1853
      * @throws \EE_Error
1854 1854
      */
1855 1855
     public function delete_by_ID($id)
@@ -2299,7 +2299,7 @@  discard block
 block discarded – undo
2299 2299
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2300 2300
      * EEM_Base::$_db_verification_level
2301 2301
      *
2302
-     * @param $wpdb_method
2302
+     * @param string $wpdb_method
2303 2303
      * @param $arguments_to_provide
2304 2304
      * @return string
2305 2305
      */
@@ -2423,6 +2423,7 @@  discard block
 block discarded – undo
2423 2423
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2424 2424
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2425 2425
      *                             because these will be inserted in any new rows created as well.
2426
+     * @param EE_Base_Class $id_or_obj
2426 2427
      */
2427 2428
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2428 2429
     {
@@ -2433,7 +2434,7 @@  discard block
 block discarded – undo
2433 2434
 
2434 2435
 
2435 2436
     /**
2436
-     * @param mixed           $id_or_obj
2437
+     * @param EE_Base_Class           $id_or_obj
2437 2438
      * @param string          $relationName
2438 2439
      * @param array           $where_query_params
2439 2440
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2474,7 +2475,7 @@  discard block
 block discarded – undo
2474 2475
      * However, if the model objects can't be deleted because of blocking related model objects, then
2475 2476
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2476 2477
      *
2477
-     * @param EE_Base_Class|int|string $id_or_obj
2478
+     * @param EE_Base_Class $id_or_obj
2478 2479
      * @param string                   $model_name
2479 2480
      * @param array                    $query_params
2480 2481
      * @return int how many deleted
@@ -2495,7 +2496,7 @@  discard block
 block discarded – undo
2495 2496
      * the model objects can't be hard deleted because of blocking related model objects,
2496 2497
      * just does a soft-delete on them instead.
2497 2498
      *
2498
-     * @param EE_Base_Class|int|string $id_or_obj
2499
+     * @param EE_Base_Class $id_or_obj
2499 2500
      * @param string                   $model_name
2500 2501
      * @param array                    $query_params
2501 2502
      * @return int how many deleted
@@ -2552,6 +2553,7 @@  discard block
 block discarded – undo
2552 2553
      * @param string $model_name   like 'Event', or 'Registration'
2553 2554
      * @param array  $query_params like EEM_Base::get_all's
2554 2555
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2556
+     * @param EE_Base_Class $id_or_obj
2555 2557
      * @return float
2556 2558
      * @throws \EE_Error
2557 2559
      */
@@ -3022,7 +3024,7 @@  discard block
 block discarded – undo
3022 3024
      * Finds all the fields that correspond to the given table
3023 3025
      *
3024 3026
      * @param string $table_alias , array key in EEM_Base::_tables
3025
-     * @return EE_Model_Field_Base[]
3027
+     * @return EE_Model_Field_Base
3026 3028
      */
3027 3029
     public function _get_fields_for_table($table_alias)
3028 3030
     {
@@ -3507,7 +3509,7 @@  discard block
 block discarded – undo
3507 3509
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3508 3510
      * We should use default where conditions on related models when they requested to use default where conditions
3509 3511
      * on all models, or specifically just on other related models
3510
-     * @param      $default_where_conditions_value
3512
+     * @param      string $default_where_conditions_value
3511 3513
      * @param bool $for_this_model false means this is for OTHER related models
3512 3514
      * @return bool
3513 3515
      */
@@ -3545,7 +3547,7 @@  discard block
 block discarded – undo
3545 3547
      * where conditions.
3546 3548
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3547 3549
      * on this model or others
3548
-     * @param      $default_where_conditions_value
3550
+     * @param      string $default_where_conditions_value
3549 3551
      * @param bool $for_this_model false means this is for OTHER related models
3550 3552
      * @return bool
3551 3553
      */
@@ -4598,7 +4600,7 @@  discard block
 block discarded – undo
4598 4600
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4599 4601
      * Eg, on EE_Answer that would be ANS_ID field object
4600 4602
      *
4601
-     * @param $field_obj
4603
+     * @param EE_Model_Field_Base $field_obj
4602 4604
      * @return boolean
4603 4605
      */
4604 4606
     public function is_primary_key_field($field_obj)
@@ -5320,7 +5322,7 @@  discard block
 block discarded – undo
5320 5322
     /**
5321 5323
      * Read comments for assume_values_already_prepared_by_model_object()
5322 5324
      *
5323
-     * @return int
5325
+     * @return boolean
5324 5326
      */
5325 5327
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5326 5328
     {
Please login to merge, or discard this patch.
Spacing   +155 added lines, -155 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 = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
539
+        $this->_tables = 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 = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
554
+        $this->_fields = 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 = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
585
+        $this->_model_relations = 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
 
@@ -679,7 +679,7 @@  discard block
 block discarded – undo
679 679
      */
680 680
     public static function set_model_query_blog_id($blog_id = 0)
681 681
     {
682
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
682
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
683 683
     }
684 684
 
685 685
 
@@ -709,7 +709,7 @@  discard block
 block discarded – undo
709 709
     public static function instance($timezone = null)
710 710
     {
711 711
         // check if instance of Espresso_model already exists
712
-        if (! static::$_instance instanceof static) {
712
+        if ( ! static::$_instance instanceof static) {
713 713
             // instantiate Espresso_model
714 714
             static::$_instance = new static($timezone);
715 715
         }
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
             foreach ($r->getDefaultProperties() as $property => $value) {
741 741
                 //don't set instance to null like it was originally,
742 742
                 //but it's static anyways, and we're ignoring static properties (for now at least)
743
-                if (! isset($static_properties[$property])) {
743
+                if ( ! isset($static_properties[$property])) {
744 744
                     static::$_instance->{$property} = $value;
745 745
                 }
746 746
             }
@@ -763,7 +763,7 @@  discard block
 block discarded – undo
763 763
      */
764 764
     public function status_array($translated = false)
765 765
     {
766
-        if (! array_key_exists('Status', $this->_model_relations)) {
766
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
767 767
             return array();
768 768
         }
769 769
         $model_name = $this->get_this_model_name();
@@ -966,17 +966,17 @@  discard block
 block discarded – undo
966 966
     public function wp_user_field_name()
967 967
     {
968 968
         try {
969
-            if (! empty($this->_model_chain_to_wp_user)) {
969
+            if ( ! empty($this->_model_chain_to_wp_user)) {
970 970
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971 971
                 $last_model_name = end($models_to_follow_to_wp_users);
972 972
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
973
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
974 974
             } else {
975 975
                 $model_with_fk_to_wp_users = $this;
976 976
                 $model_chain_to_wp_user = '';
977 977
             }
978 978
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
979
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
980 980
         } catch (EE_Error $e) {
981 981
             return false;
982 982
         }
@@ -1048,12 +1048,12 @@  discard block
 block discarded – undo
1048 1048
         // remember the custom selections, if any, and type cast as array
1049 1049
         // (unless $columns_to_select is an object, then just set as an empty array)
1050 1050
         // Note: (array) 'some string' === array( 'some string' )
1051
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1051
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1052 1052
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1053 1053
         $select_expressions = $columns_to_select !== null
1054 1054
             ? $this->_construct_select_from_input($columns_to_select)
1055 1055
             : $this->_construct_default_select_sql($model_query_info);
1056
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1056
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1057 1057
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058 1058
     }
1059 1059
 
@@ -1098,7 +1098,7 @@  discard block
 block discarded – undo
1098 1098
         if (is_array($columns_to_select)) {
1099 1099
             $select_sql_array = array();
1100 1100
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1101
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102 1102
                     throw new EE_Error(
1103 1103
                         sprintf(
1104 1104
                             __(
@@ -1110,7 +1110,7 @@  discard block
 block discarded – undo
1110 1110
                         )
1111 1111
                     );
1112 1112
                 }
1113
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1113
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114 1114
                     throw new EE_Error(
1115 1115
                         sprintf(
1116 1116
                             __(
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
      */
1183 1183
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184 1184
     {
1185
-        if (! isset($query_params[0])) {
1185
+        if ( ! isset($query_params[0])) {
1186 1186
             $query_params[0] = array();
1187 1187
         }
1188 1188
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1207,7 +1207,7 @@  discard block
 block discarded – undo
1207 1207
      */
1208 1208
     public function get_one($query_params = array())
1209 1209
     {
1210
-        if (! is_array($query_params)) {
1210
+        if ( ! is_array($query_params)) {
1211 1211
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1212 1212
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213 1213
                     gettype($query_params)), '4.6.0');
@@ -1375,7 +1375,7 @@  discard block
 block discarded – undo
1375 1375
                 return array();
1376 1376
             }
1377 1377
         }
1378
-        if (! is_array($query_params)) {
1378
+        if ( ! is_array($query_params)) {
1379 1379
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380 1380
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381 1381
                     gettype($query_params)), '4.6.0');
@@ -1385,7 +1385,7 @@  discard block
 block discarded – undo
1385 1385
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386 1386
         $query_params['limit'] = $limit;
1387 1387
         //set direction
1388
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1388
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1389 1389
         $query_params['order_by'] = $operand === '>'
1390 1390
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1391 1391
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1464,7 +1464,7 @@  discard block
 block discarded – undo
1464 1464
     {
1465 1465
         $field_settings = $this->field_settings_for($field_name);
1466 1466
         //if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1467
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1468 1468
             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.',
1469 1469
                 'event_espresso'), $field_name));
1470 1470
         }
@@ -1543,7 +1543,7 @@  discard block
 block discarded – undo
1543 1543
         //load EEH_DTT_Helper
1544 1544
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545 1545
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1546
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1547 1547
     }
1548 1548
 
1549 1549
 
@@ -1611,7 +1611,7 @@  discard block
 block discarded – undo
1611 1611
      */
1612 1612
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613 1613
     {
1614
-        if (! is_array($query_params)) {
1614
+        if ( ! is_array($query_params)) {
1615 1615
             EE_Error::doing_it_wrong('EEM_Base::update',
1616 1616
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617 1617
                     gettype($query_params)), '4.6.0');
@@ -1633,7 +1633,7 @@  discard block
 block discarded – undo
1633 1633
          * @param EEM_Base $model           the model being queried
1634 1634
          * @param array    $query_params    see EEM_Base::get_all()
1635 1635
          */
1636
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1636
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637 1637
             $query_params);
1638 1638
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1639 1639
         //to do that, for each table, verify that it's PK isn't null.
@@ -1647,7 +1647,7 @@  discard block
 block discarded – undo
1647 1647
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648 1648
         foreach ($wpdb_select_results as $wpdb_result) {
1649 1649
             // type cast stdClass as array
1650
-            $wpdb_result = (array)$wpdb_result;
1650
+            $wpdb_result = (array) $wpdb_result;
1651 1651
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652 1652
             if ($this->has_primary_key_field()) {
1653 1653
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1664,13 +1664,13 @@  discard block
 block discarded – undo
1664 1664
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665 1665
                     //if there is no private key for this table on the results, it means there's no entry
1666 1666
                     //in this table, right? so insert a row in the current table, using any fields available
1667
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1667
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1668 1668
                            && $wpdb_result[$this_table_pk_column])
1669 1669
                     ) {
1670 1670
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671 1671
                             $main_table_pk_value);
1672 1672
                         //if we died here, report the error
1673
-                        if (! $success) {
1673
+                        if ( ! $success) {
1674 1674
                             return false;
1675 1675
                         }
1676 1676
                     }
@@ -1701,7 +1701,7 @@  discard block
 block discarded – undo
1701 1701
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702 1702
                 }
1703 1703
             }
1704
-            if (! $model_objs_affected_ids) {
1704
+            if ( ! $model_objs_affected_ids) {
1705 1705
                 //wait wait wait- if nothing was affected let's stop here
1706 1706
                 return 0;
1707 1707
             }
@@ -1728,7 +1728,7 @@  discard block
 block discarded – undo
1728 1728
                . $model_query_info->get_full_join_sql()
1729 1729
                . " SET "
1730 1730
                . $this->_construct_update_sql($fields_n_values)
1731
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1731
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732 1732
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733 1733
         /**
1734 1734
          * Action called after a model update call has been made.
@@ -1739,7 +1739,7 @@  discard block
 block discarded – undo
1739 1739
          * @param int      $rows_affected
1740 1740
          */
1741 1741
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
-        return $rows_affected;//how many supposedly got updated
1742
+        return $rows_affected; //how many supposedly got updated
1743 1743
     }
1744 1744
 
1745 1745
 
@@ -1767,7 +1767,7 @@  discard block
 block discarded – undo
1767 1767
         }
1768 1768
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1769 1769
         $select_expressions = $field->get_qualified_column();
1770
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1770
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1771 1771
         return $this->_do_wpdb_query('get_col', array($SQL));
1772 1772
     }
1773 1773
 
@@ -1785,7 +1785,7 @@  discard block
 block discarded – undo
1785 1785
     {
1786 1786
         $query_params['limit'] = 1;
1787 1787
         $col = $this->get_col($query_params, $field_to_select);
1788
-        if (! empty($col)) {
1788
+        if ( ! empty($col)) {
1789 1789
             return reset($col);
1790 1790
         } else {
1791 1791
             return null;
@@ -1817,7 +1817,7 @@  discard block
 block discarded – undo
1817 1817
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818 1818
             $value_sql = $prepared_value === null ? 'NULL'
1819 1819
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1820
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1821 1821
         }
1822 1822
         return implode(",", $cols_n_values);
1823 1823
     }
@@ -1958,7 +1958,7 @@  discard block
 block discarded – undo
1958 1958
          * @param int      $rows_deleted
1959 1959
          */
1960 1960
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
1961
-        return $rows_deleted;//how many supposedly got deleted
1961
+        return $rows_deleted; //how many supposedly got deleted
1962 1962
     }
1963 1963
 
1964 1964
 
@@ -2078,7 +2078,7 @@  discard block
 block discarded – undo
2078 2078
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2079 2079
                 //make sure we have unique $ids
2080 2080
                 $ids = array_unique($ids);
2081
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2081
+                $query[] = $column.' IN('.implode(',', $ids).')';
2082 2082
             }
2083 2083
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2084 2084
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2086,9 +2086,9 @@  discard block
 block discarded – undo
2086 2086
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2087 2087
                 $values_for_each_combined_primary_key_for_a_row = array();
2088 2088
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2089
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2089
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2090 2090
                 }
2091
-                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2091
+                $ways_to_identify_a_row[] = '('.implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2092 2092
             }
2093 2093
             $query_part = implode(' OR ', $ways_to_identify_a_row);
2094 2094
         }
@@ -2134,9 +2134,9 @@  discard block
 block discarded – undo
2134 2134
                 $column_to_count = '*';
2135 2135
             }
2136 2136
         }
2137
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2138
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2139
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2137
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2138
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2139
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2140 2140
     }
2141 2141
 
2142 2142
 
@@ -2158,13 +2158,13 @@  discard block
 block discarded – undo
2158 2158
             $field_obj = $this->get_primary_key_field();
2159 2159
         }
2160 2160
         $column_to_count = $field_obj->get_qualified_column();
2161
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2161
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2162 2162
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2163 2163
         $data_type = $field_obj->get_wpdb_data_type();
2164 2164
         if ($data_type === '%d' || $data_type === '%s') {
2165
-            return (float)$return_value;
2165
+            return (float) $return_value;
2166 2166
         } else {//must be %f
2167
-            return (float)$return_value;
2167
+            return (float) $return_value;
2168 2168
         }
2169 2169
     }
2170 2170
 
@@ -2185,13 +2185,13 @@  discard block
 block discarded – undo
2185 2185
         //if we're in maintenance mode level 2, DON'T run any queries
2186 2186
         //because level 2 indicates the database needs updating and
2187 2187
         //is probably out of sync with the code
2188
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2188
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2189 2189
             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.",
2190 2190
                 "event_espresso")));
2191 2191
         }
2192 2192
         /** @type WPDB $wpdb */
2193 2193
         global $wpdb;
2194
-        if (! method_exists($wpdb, $wpdb_method)) {
2194
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2195 2195
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2196 2196
                 'event_espresso'), $wpdb_method));
2197 2197
         }
@@ -2203,7 +2203,7 @@  discard block
 block discarded – undo
2203 2203
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2204 2204
         if (WP_DEBUG) {
2205 2205
             $wpdb->show_errors($old_show_errors_value);
2206
-            if (! empty($wpdb->last_error)) {
2206
+            if ( ! empty($wpdb->last_error)) {
2207 2207
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2208 2208
             } elseif ($result === false) {
2209 2209
                 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"',
@@ -2263,7 +2263,7 @@  discard block
 block discarded – undo
2263 2263
                     return $result;
2264 2264
                     break;
2265 2265
             }
2266
-            if (! empty($error_message)) {
2266
+            if ( ! empty($error_message)) {
2267 2267
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2268 2268
                 trigger_error($error_message);
2269 2269
             }
@@ -2339,11 +2339,11 @@  discard block
 block discarded – undo
2339 2339
      */
2340 2340
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2341 2341
     {
2342
-        return " FROM " . $model_query_info->get_full_join_sql() .
2343
-               $model_query_info->get_where_sql() .
2344
-               $model_query_info->get_group_by_sql() .
2345
-               $model_query_info->get_having_sql() .
2346
-               $model_query_info->get_order_by_sql() .
2342
+        return " FROM ".$model_query_info->get_full_join_sql().
2343
+               $model_query_info->get_where_sql().
2344
+               $model_query_info->get_group_by_sql().
2345
+               $model_query_info->get_having_sql().
2346
+               $model_query_info->get_order_by_sql().
2347 2347
                $model_query_info->get_limit_sql();
2348 2348
     }
2349 2349
 
@@ -2539,12 +2539,12 @@  discard block
 block discarded – undo
2539 2539
         $related_model = $this->get_related_model_obj($model_name);
2540 2540
         //we're just going to use the query params on the related model's normal get_all query,
2541 2541
         //except add a condition to say to match the current mod
2542
-        if (! isset($query_params['default_where_conditions'])) {
2542
+        if ( ! isset($query_params['default_where_conditions'])) {
2543 2543
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2544 2544
         }
2545 2545
         $this_model_name = $this->get_this_model_name();
2546 2546
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2547
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2547
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2548 2548
         return $related_model->count($query_params, $field_to_count, $distinct);
2549 2549
     }
2550 2550
 
@@ -2564,7 +2564,7 @@  discard block
 block discarded – undo
2564 2564
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2565 2565
     {
2566 2566
         $related_model = $this->get_related_model_obj($model_name);
2567
-        if (! is_array($query_params)) {
2567
+        if ( ! is_array($query_params)) {
2568 2568
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2569 2569
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2570 2570
                     gettype($query_params)), '4.6.0');
@@ -2572,12 +2572,12 @@  discard block
 block discarded – undo
2572 2572
         }
2573 2573
         //we're just going to use the query params on the related model's normal get_all query,
2574 2574
         //except add a condition to say to match the current mod
2575
-        if (! isset($query_params['default_where_conditions'])) {
2575
+        if ( ! isset($query_params['default_where_conditions'])) {
2576 2576
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2577 2577
         }
2578 2578
         $this_model_name = $this->get_this_model_name();
2579 2579
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2580
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2580
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2581 2581
         return $related_model->sum($query_params, $field_to_sum);
2582 2582
     }
2583 2583
 
@@ -2631,7 +2631,7 @@  discard block
 block discarded – undo
2631 2631
                 $field_with_model_name = $field;
2632 2632
             }
2633 2633
         }
2634
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2634
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2635 2635
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2636 2636
                 $this->get_this_model_name()));
2637 2637
         }
@@ -2664,7 +2664,7 @@  discard block
 block discarded – undo
2664 2664
          * @param array    $fields_n_values keys are the fields and values are their new values
2665 2665
          * @param EEM_Base $model           the model used
2666 2666
          */
2667
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2667
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2668 2668
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2669 2669
             $main_table = $this->_get_main_table();
2670 2670
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2772,7 +2772,7 @@  discard block
 block discarded – undo
2772 2772
         }
2773 2773
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2774 2774
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2775
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2775
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2776 2776
         }
2777 2777
         //if there is nothing to base this search on, then we shouldn't find anything
2778 2778
         if (empty($query_params)) {
@@ -2859,7 +2859,7 @@  discard block
 block discarded – undo
2859 2859
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2860 2860
             //so add the fk to the main table as a column
2861 2861
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2862
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2862
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2863 2863
         }
2864 2864
         //insert the new entry
2865 2865
         $result = $this->_do_wpdb_query('insert',
@@ -3065,7 +3065,7 @@  discard block
 block discarded – undo
3065 3065
                     $query_info_carrier,
3066 3066
                     'group_by'
3067 3067
                 );
3068
-            } elseif (! empty ($query_params['group_by'])) {
3068
+            } elseif ( ! empty ($query_params['group_by'])) {
3069 3069
                 $this->_extract_related_model_info_from_query_param(
3070 3070
                     $query_params['group_by'],
3071 3071
                     $query_info_carrier,
@@ -3087,7 +3087,7 @@  discard block
 block discarded – undo
3087 3087
                     $query_info_carrier,
3088 3088
                     'order_by'
3089 3089
                 );
3090
-            } elseif (! empty($query_params['order_by'])) {
3090
+            } elseif ( ! empty($query_params['order_by'])) {
3091 3091
                 $this->_extract_related_model_info_from_query_param(
3092 3092
                     $query_params['order_by'],
3093 3093
                     $query_info_carrier,
@@ -3122,8 +3122,8 @@  discard block
 block discarded – undo
3122 3122
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3123 3123
         $query_param_type
3124 3124
     ) {
3125
-        if (! empty($sub_query_params)) {
3126
-            $sub_query_params = (array)$sub_query_params;
3125
+        if ( ! empty($sub_query_params)) {
3126
+            $sub_query_params = (array) $sub_query_params;
3127 3127
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3128 3128
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3129 3129
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3134,7 +3134,7 @@  discard block
 block discarded – undo
3134 3134
                 //of array('Registration.TXN_ID'=>23)
3135 3135
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3136 3136
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3137
-                    if (! is_array($possibly_array_of_params)) {
3137
+                    if ( ! is_array($possibly_array_of_params)) {
3138 3138
                         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'))",
3139 3139
                             "event_espresso"),
3140 3140
                             $param, $possibly_array_of_params));
@@ -3150,7 +3150,7 @@  discard block
 block discarded – undo
3150 3150
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3151 3151
                     //indicating that $possible_array_of_params[1] is actually a field name,
3152 3152
                     //from which we should extract query parameters!
3153
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3153
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3154 3154
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3155 3155
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3156 3156
                     }
@@ -3180,8 +3180,8 @@  discard block
 block discarded – undo
3180 3180
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3181 3181
         $query_param_type
3182 3182
     ) {
3183
-        if (! empty($sub_query_params)) {
3184
-            if (! is_array($sub_query_params)) {
3183
+        if ( ! empty($sub_query_params)) {
3184
+            if ( ! is_array($sub_query_params)) {
3185 3185
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3186 3186
                     $sub_query_params));
3187 3187
             }
@@ -3210,7 +3210,7 @@  discard block
 block discarded – undo
3210 3210
      */
3211 3211
     public function _create_model_query_info_carrier($query_params)
3212 3212
     {
3213
-        if (! is_array($query_params)) {
3213
+        if ( ! is_array($query_params)) {
3214 3214
             EE_Error::doing_it_wrong(
3215 3215
                 'EEM_Base::_create_model_query_info_carrier',
3216 3216
                 sprintf(
@@ -3286,7 +3286,7 @@  discard block
 block discarded – undo
3286 3286
         //set limit
3287 3287
         if (array_key_exists('limit', $query_params)) {
3288 3288
             if (is_array($query_params['limit'])) {
3289
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3289
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3290 3290
                     $e = sprintf(
3291 3291
                         __(
3292 3292
                             "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)",
@@ -3294,12 +3294,12 @@  discard block
 block discarded – undo
3294 3294
                         ),
3295 3295
                         http_build_query($query_params['limit'])
3296 3296
                     );
3297
-                    throw new EE_Error($e . "|" . $e);
3297
+                    throw new EE_Error($e."|".$e);
3298 3298
                 }
3299 3299
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3300
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3301
-            } elseif (! empty ($query_params['limit'])) {
3302
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3300
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3301
+            } elseif ( ! empty ($query_params['limit'])) {
3302
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3303 3303
             }
3304 3304
         }
3305 3305
         //set order by
@@ -3331,10 +3331,10 @@  discard block
 block discarded – undo
3331 3331
                 $order_array = array();
3332 3332
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3333 3333
                     $order = $this->_extract_order($order);
3334
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3334
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3335 3335
                 }
3336
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3337
-            } elseif (! empty ($query_params['order_by'])) {
3336
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3337
+            } elseif ( ! empty ($query_params['order_by'])) {
3338 3338
                 $this->_extract_related_model_info_from_query_param(
3339 3339
                     $query_params['order_by'],
3340 3340
                     $query_object,
@@ -3345,18 +3345,18 @@  discard block
 block discarded – undo
3345 3345
                     ? $this->_extract_order($query_params['order'])
3346 3346
                     : 'DESC';
3347 3347
                 $query_object->set_order_by_sql(
3348
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3348
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3349 3349
                 );
3350 3350
             }
3351 3351
         }
3352 3352
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3353
-        if (! array_key_exists('order_by', $query_params)
3353
+        if ( ! array_key_exists('order_by', $query_params)
3354 3354
             && array_key_exists('order', $query_params)
3355 3355
             && ! empty($query_params['order'])
3356 3356
         ) {
3357 3357
             $pk_field = $this->get_primary_key_field();
3358 3358
             $order = $this->_extract_order($query_params['order']);
3359
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3359
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3360 3360
         }
3361 3361
         //set group by
3362 3362
         if (array_key_exists('group_by', $query_params)) {
@@ -3366,10 +3366,10 @@  discard block
 block discarded – undo
3366 3366
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3367 3367
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3368 3368
                 }
3369
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3370
-            } elseif (! empty ($query_params['group_by'])) {
3369
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3370
+            } elseif ( ! empty ($query_params['group_by'])) {
3371 3371
                 $query_object->set_group_by_sql(
3372
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3372
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3373 3373
                 );
3374 3374
             }
3375 3375
         }
@@ -3379,7 +3379,7 @@  discard block
 block discarded – undo
3379 3379
         }
3380 3380
         //now, just verify they didn't pass anything wack
3381 3381
         foreach ($query_params as $query_key => $query_value) {
3382
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3382
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3383 3383
                 throw new EE_Error(
3384 3384
                     sprintf(
3385 3385
                         __(
@@ -3473,22 +3473,22 @@  discard block
 block discarded – undo
3473 3473
         $where_query_params = array()
3474 3474
     ) {
3475 3475
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3476
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3476
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3477 3477
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3478 3478
                 "event_espresso"), $use_default_where_conditions,
3479 3479
                 implode(", ", $allowed_used_default_where_conditions_values)));
3480 3480
         }
3481 3481
         $universal_query_params = array();
3482
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3482
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3483 3483
             $universal_query_params = $this->_get_default_where_conditions();
3484
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3484
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3485 3485
             $universal_query_params = $this->_get_minimum_where_conditions();
3486 3486
         }
3487 3487
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3488 3488
             $related_model = $this->get_related_model_obj($model_name);
3489
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3489
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3490 3490
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3491
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3491
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3492 3492
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3493 3493
             } else {
3494 3494
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3521,7 +3521,7 @@  discard block
 block discarded – undo
3521 3521
      * @param bool $for_this_model false means this is for OTHER related models
3522 3522
      * @return bool
3523 3523
      */
3524
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3524
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3525 3525
     {
3526 3526
         return (
3527 3527
                    $for_this_model
@@ -3600,7 +3600,7 @@  discard block
 block discarded – undo
3600 3600
     ) {
3601 3601
         $null_friendly_where_conditions = array();
3602 3602
         $none_overridden = true;
3603
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3603
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3604 3604
         foreach ($default_where_conditions as $key => $val) {
3605 3605
             if (isset($provided_where_conditions[$key])) {
3606 3606
                 $none_overridden = false;
@@ -3718,7 +3718,7 @@  discard block
 block discarded – undo
3718 3718
             foreach ($tables as $table_obj) {
3719 3719
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3720 3720
                                        . $table_obj->get_fully_qualified_pk_column();
3721
-                if (! in_array($qualified_pk_column, $selects)) {
3721
+                if ( ! in_array($qualified_pk_column, $selects)) {
3722 3722
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3723 3723
                 }
3724 3724
             }
@@ -3804,9 +3804,9 @@  discard block
 block discarded – undo
3804 3804
         //and
3805 3805
         //check if it's a field on a related model
3806 3806
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3807
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3807
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3808 3808
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3809
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3809
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3810 3810
                 if ($query_param === '') {
3811 3811
                     //nothing left to $query_param
3812 3812
                     //we should actually end in a field name, not a model like this!
@@ -3892,7 +3892,7 @@  discard block
 block discarded – undo
3892 3892
     {
3893 3893
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3894 3894
         if ($SQL) {
3895
-            return " WHERE " . $SQL;
3895
+            return " WHERE ".$SQL;
3896 3896
         } else {
3897 3897
             return '';
3898 3898
         }
@@ -3912,7 +3912,7 @@  discard block
 block discarded – undo
3912 3912
     {
3913 3913
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3914 3914
         if ($SQL) {
3915
-            return " HAVING " . $SQL;
3915
+            return " HAVING ".$SQL;
3916 3916
         } else {
3917 3917
             return '';
3918 3918
         }
@@ -3932,11 +3932,11 @@  discard block
 block discarded – undo
3932 3932
      */
3933 3933
     protected function _get_field_on_model($field_name, $model_name)
3934 3934
     {
3935
-        $model_class = 'EEM_' . $model_name;
3936
-        $model_filepath = $model_class . ".model.php";
3935
+        $model_class = 'EEM_'.$model_name;
3936
+        $model_filepath = $model_class.".model.php";
3937 3937
         if (is_readable($model_filepath)) {
3938 3938
             require_once($model_filepath);
3939
-            $model_instance = call_user_func($model_name . "::instance");
3939
+            $model_instance = call_user_func($model_name."::instance");
3940 3940
             /* @var $model_instance EEM_Base */
3941 3941
             return $model_instance->field_settings_for($field_name);
3942 3942
         } else {
@@ -3960,7 +3960,7 @@  discard block
 block discarded – undo
3960 3960
     {
3961 3961
         $where_clauses = array();
3962 3962
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3963
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3963
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
3964 3964
             if (in_array($query_param, $this->_logic_query_param_keys)) {
3965 3965
                 switch ($query_param) {
3966 3966
                     case 'not':
@@ -3988,7 +3988,7 @@  discard block
 block discarded – undo
3988 3988
             } else {
3989 3989
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
3990 3990
                 //if it's not a normal field, maybe it's a custom selection?
3991
-                if (! $field_obj) {
3991
+                if ( ! $field_obj) {
3992 3992
                     if (isset($this->_custom_selections[$query_param][1])) {
3993 3993
                         $field_obj = $this->_custom_selections[$query_param][1];
3994 3994
                     } else {
@@ -3997,7 +3997,7 @@  discard block
 block discarded – undo
3997 3997
                     }
3998 3998
                 }
3999 3999
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4000
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4000
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4001 4001
             }
4002 4002
         }
4003 4003
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4018,7 +4018,7 @@  discard block
 block discarded – undo
4018 4018
         if ($field) {
4019 4019
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4020 4020
                 $query_param);
4021
-            return $table_alias_prefix . $field->get_qualified_column();
4021
+            return $table_alias_prefix.$field->get_qualified_column();
4022 4022
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4023 4023
             //maybe it's custom selection item?
4024 4024
             //if so, just use it as the "column name"
@@ -4065,7 +4065,7 @@  discard block
 block discarded – undo
4065 4065
     {
4066 4066
         if (is_array($op_and_value)) {
4067 4067
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4068
-            if (! $operator) {
4068
+            if ( ! $operator) {
4069 4069
                 $php_array_like_string = array();
4070 4070
                 foreach ($op_and_value as $key => $value) {
4071 4071
                     $php_array_like_string[] = "$key=>$value";
@@ -4087,13 +4087,13 @@  discard block
 block discarded – undo
4087 4087
         }
4088 4088
         //check to see if the value is actually another field
4089 4089
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4090
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4090
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4091 4091
         } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4092 4092
             //in this case, the value should be an array, or at least a comma-separated list
4093 4093
             //it will need to handle a little differently
4094 4094
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4095 4095
             //note: $cleaned_value has already been run through $wpdb->prepare()
4096
-            return $operator . SP . $cleaned_value;
4096
+            return $operator.SP.$cleaned_value;
4097 4097
         } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4098 4098
             //the value should be an array with count of two.
4099 4099
             if (count($value) !== 2) {
@@ -4108,7 +4108,7 @@  discard block
 block discarded – undo
4108 4108
                 );
4109 4109
             }
4110 4110
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4111
-            return $operator . SP . $cleaned_value;
4111
+            return $operator.SP.$cleaned_value;
4112 4112
         } elseif (in_array($operator, $this->_null_style_operators)) {
4113 4113
             if ($value !== null) {
4114 4114
                 throw new EE_Error(
@@ -4126,9 +4126,9 @@  discard block
 block discarded – undo
4126 4126
         } elseif ($operator === 'LIKE' && ! is_array($value)) {
4127 4127
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4128 4128
             //remove other junk. So just treat it as a string.
4129
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4130
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4131
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4129
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4130
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4131
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4132 4132
         } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4133 4133
             throw new EE_Error(
4134 4134
                 sprintf(
@@ -4140,7 +4140,7 @@  discard block
 block discarded – undo
4140 4140
                     $operator
4141 4141
                 )
4142 4142
             );
4143
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4143
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4144 4144
             throw new EE_Error(
4145 4145
                 sprintf(
4146 4146
                     __(
@@ -4181,7 +4181,7 @@  discard block
 block discarded – undo
4181 4181
         foreach ($values as $value) {
4182 4182
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4183 4183
         }
4184
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4184
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4185 4185
     }
4186 4186
 
4187 4187
 
@@ -4222,7 +4222,7 @@  discard block
 block discarded – undo
4222 4222
                                 . $main_table->get_table_name()
4223 4223
                                 . " WHERE FALSE";
4224 4224
         }
4225
-        return "(" . implode(",", $cleaned_values) . ")";
4225
+        return "(".implode(",", $cleaned_values).")";
4226 4226
     }
4227 4227
 
4228 4228
 
@@ -4241,7 +4241,7 @@  discard block
 block discarded – undo
4241 4241
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4242 4242
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4243 4243
         } else {//$field_obj should really just be a data type
4244
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4244
+            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4245 4245
                 throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4246 4246
                     $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4247 4247
             }
@@ -4361,10 +4361,10 @@  discard block
 block discarded – undo
4361 4361
      */
4362 4362
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4363 4363
     {
4364
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4364
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4365 4365
         $qualified_columns = array();
4366 4366
         foreach ($this->field_settings() as $field_name => $field) {
4367
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4367
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4368 4368
         }
4369 4369
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4370 4370
     }
@@ -4388,11 +4388,11 @@  discard block
 block discarded – undo
4388 4388
             if ($table_obj instanceof EE_Primary_Table) {
4389 4389
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4390 4390
                     ? $table_obj->get_select_join_limit($limit)
4391
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4391
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4392 4392
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4393 4393
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4394 4394
                     ? $table_obj->get_select_join_limit_join($limit)
4395
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4395
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4396 4396
             }
4397 4397
         }
4398 4398
         return $SQL;
@@ -4480,12 +4480,12 @@  discard block
 block discarded – undo
4480 4480
      */
4481 4481
     public function get_related_model_obj($model_name)
4482 4482
     {
4483
-        $model_classname = "EEM_" . $model_name;
4484
-        if (! class_exists($model_classname)) {
4483
+        $model_classname = "EEM_".$model_name;
4484
+        if ( ! class_exists($model_classname)) {
4485 4485
             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",
4486 4486
                 'event_espresso'), $model_name, $model_classname));
4487 4487
         }
4488
-        return call_user_func($model_classname . "::instance");
4488
+        return call_user_func($model_classname."::instance");
4489 4489
     }
4490 4490
 
4491 4491
 
@@ -4532,7 +4532,7 @@  discard block
 block discarded – undo
4532 4532
     public function related_settings_for($relation_name)
4533 4533
     {
4534 4534
         $relatedModels = $this->relation_settings();
4535
-        if (! array_key_exists($relation_name, $relatedModels)) {
4535
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4536 4536
             throw new EE_Error(
4537 4537
                 sprintf(
4538 4538
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4559,7 +4559,7 @@  discard block
 block discarded – undo
4559 4559
     public function field_settings_for($fieldName)
4560 4560
     {
4561 4561
         $fieldSettings = $this->field_settings(true);
4562
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4562
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4563 4563
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4564 4564
                 get_class($this)));
4565 4565
         }
@@ -4634,7 +4634,7 @@  discard block
 block discarded – undo
4634 4634
                     break;
4635 4635
                 }
4636 4636
             }
4637
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4637
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4638 4638
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4639 4639
                     get_class($this)));
4640 4640
             }
@@ -4693,7 +4693,7 @@  discard block
 block discarded – undo
4693 4693
      */
4694 4694
     public function get_foreign_key_to($model_name)
4695 4695
     {
4696
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4696
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4697 4697
             foreach ($this->field_settings() as $field) {
4698 4698
                 if (
4699 4699
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4703,7 +4703,7 @@  discard block
 block discarded – undo
4703 4703
                     break;
4704 4704
                 }
4705 4705
             }
4706
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4706
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4707 4707
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4708 4708
                     'event_espresso'), $model_name, get_class($this)));
4709 4709
             }
@@ -4754,7 +4754,7 @@  discard block
 block discarded – undo
4754 4754
                 foreach ($this->_fields as $fields_corresponding_to_table) {
4755 4755
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4756 4756
                         /** @var $field_obj EE_Model_Field_Base */
4757
-                        if (! $field_obj->is_db_only_field()) {
4757
+                        if ( ! $field_obj->is_db_only_field()) {
4758 4758
                             $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4759 4759
                         }
4760 4760
                     }
@@ -4784,7 +4784,7 @@  discard block
 block discarded – undo
4784 4784
         $count_if_model_has_no_primary_key = 0;
4785 4785
         $has_primary_key = $this->has_primary_key_field();
4786 4786
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4787
-        foreach ((array)$rows as $row) {
4787
+        foreach ((array) $rows as $row) {
4788 4788
             if (empty($row)) {
4789 4789
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4790 4790
                 return array();
@@ -4802,7 +4802,7 @@  discard block
 block discarded – undo
4802 4802
                 }
4803 4803
             }
4804 4804
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4805
-            if (! $classInstance) {
4805
+            if ( ! $classInstance) {
4806 4806
                 throw new EE_Error(
4807 4807
                     sprintf(
4808 4808
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4871,7 +4871,7 @@  discard block
 block discarded – undo
4871 4871
      */
4872 4872
     public function instantiate_class_from_array_or_object($cols_n_values)
4873 4873
     {
4874
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4874
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4875 4875
             $cols_n_values = get_object_vars($cols_n_values);
4876 4876
         }
4877 4877
         $primary_key = null;
@@ -4896,7 +4896,7 @@  discard block
 block discarded – undo
4896 4896
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4897 4897
         if ($primary_key) {
4898 4898
             $classInstance = $this->get_from_entity_map($primary_key);
4899
-            if (! $classInstance) {
4899
+            if ( ! $classInstance) {
4900 4900
                 $classInstance = EE_Registry::instance()
4901 4901
                                             ->load_class($className,
4902 4902
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -4947,12 +4947,12 @@  discard block
 block discarded – undo
4947 4947
     public function add_to_entity_map(EE_Base_Class $object)
4948 4948
     {
4949 4949
         $className = $this->_get_class_name();
4950
-        if (! $object instanceof $className) {
4950
+        if ( ! $object instanceof $className) {
4951 4951
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4952 4952
                 is_object($object) ? get_class($object) : $object, $className));
4953 4953
         }
4954 4954
         /** @var $object EE_Base_Class */
4955
-        if (! $object->ID()) {
4955
+        if ( ! $object->ID()) {
4956 4956
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4957 4957
                 "event_espresso"), get_class($this)));
4958 4958
         }
@@ -5022,7 +5022,7 @@  discard block
 block discarded – undo
5022 5022
             //there is a primary key on this table and its not set. Use defaults for all its columns
5023 5023
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5024 5024
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5025
-                    if (! $field_obj->is_db_only_field()) {
5025
+                    if ( ! $field_obj->is_db_only_field()) {
5026 5026
                         //prepare field as if its coming from db
5027 5027
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5028 5028
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5031,7 +5031,7 @@  discard block
 block discarded – undo
5031 5031
             } else {
5032 5032
                 //the table's rows existed. Use their values
5033 5033
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5034
-                    if (! $field_obj->is_db_only_field()) {
5034
+                    if ( ! $field_obj->is_db_only_field()) {
5035 5035
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5036 5036
                             $cols_n_values, $field_obj->get_qualified_column(),
5037 5037
                             $field_obj->get_table_column()
@@ -5148,7 +5148,7 @@  discard block
 block discarded – undo
5148 5148
      */
5149 5149
     private function _get_class_name()
5150 5150
     {
5151
-        return "EE_" . $this->get_this_model_name();
5151
+        return "EE_".$this->get_this_model_name();
5152 5152
     }
5153 5153
 
5154 5154
 
@@ -5163,7 +5163,7 @@  discard block
 block discarded – undo
5163 5163
      */
5164 5164
     public function item_name($quantity = 1)
5165 5165
     {
5166
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5166
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5167 5167
     }
5168 5168
 
5169 5169
 
@@ -5196,7 +5196,7 @@  discard block
 block discarded – undo
5196 5196
     {
5197 5197
         $className = get_class($this);
5198 5198
         $tagName = "FHEE__{$className}__{$methodName}";
5199
-        if (! has_filter($tagName)) {
5199
+        if ( ! has_filter($tagName)) {
5200 5200
             throw new EE_Error(
5201 5201
                 sprintf(
5202 5202
                     __('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 );',
@@ -5422,7 +5422,7 @@  discard block
 block discarded – undo
5422 5422
         $key_vals_in_combined_pk = array();
5423 5423
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5424 5424
         foreach ($key_fields as $key_field_name => $field_obj) {
5425
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5425
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5426 5426
                 return null;
5427 5427
             }
5428 5428
         }
@@ -5443,7 +5443,7 @@  discard block
 block discarded – undo
5443 5443
     {
5444 5444
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5445 5445
         foreach ($keys_it_should_have as $key) {
5446
-            if (! isset($key_vals[$key])) {
5446
+            if ( ! isset($key_vals[$key])) {
5447 5447
                 return false;
5448 5448
             }
5449 5449
         }
@@ -5497,7 +5497,7 @@  discard block
 block discarded – undo
5497 5497
      */
5498 5498
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5499 5499
     {
5500
-        if (! is_array($query_params)) {
5500
+        if ( ! is_array($query_params)) {
5501 5501
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5502 5502
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5503 5503
                     gettype($query_params)), '4.6.0');
@@ -5589,7 +5589,7 @@  discard block
 block discarded – undo
5589 5589
      */
5590 5590
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5591 5591
     {
5592
-        if (! $this->has_primary_key_field()) {
5592
+        if ( ! $this->has_primary_key_field()) {
5593 5593
             if (WP_DEBUG) {
5594 5594
                 EE_Error::add_error(
5595 5595
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5602,7 +5602,7 @@  discard block
 block discarded – undo
5602 5602
         $IDs = array();
5603 5603
         foreach ($model_objects as $model_object) {
5604 5604
             $id = $model_object->ID();
5605
-            if (! $id) {
5605
+            if ( ! $id) {
5606 5606
                 if ($filter_out_empty_ids) {
5607 5607
                     continue;
5608 5608
                 }
@@ -5698,8 +5698,8 @@  discard block
 block discarded – undo
5698 5698
         $missing_caps = array();
5699 5699
         $cap_restrictions = $this->cap_restrictions($context);
5700 5700
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5701
-            if (! EE_Capabilities::instance()
5702
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5701
+            if ( ! EE_Capabilities::instance()
5702
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5703 5703
             ) {
5704 5704
                 $missing_caps[$cap] = $restriction_if_no_cap;
5705 5705
             }
@@ -5850,7 +5850,7 @@  discard block
 block discarded – undo
5850 5850
     {
5851 5851
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5852 5852
             if ($query_param_key === $logic_query_param_key
5853
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5853
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
5854 5854
             ) {
5855 5855
                 return true;
5856 5856
             }
Please login to merge, or discard this patch.
Indentation   +5883 added lines, -5883 removed lines patch added patch discarded remove patch
@@ -28,5895 +28,5895 @@
 block discarded – undo
28 28
 abstract class EEM_Base extends EE_Base implements EventEspresso\core\interfaces\ResettableInterface
29 29
 {
30 30
 
31
-    //admin posty
32
-    //basic -> grants access to mine -> if they don't have it, select none
33
-    //*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
-    //*_published -> grants access to published -> if they dont have it, select non-published
36
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
38
-    //frontend posty
39
-    //by default has access to published
40
-    //basic -> grants access to mine that aren't published, and all published
41
-    //*_others ->grants access to others that aren't private, all mine
42
-    //*_private -> grants full access
43
-    //frontend non-posty
44
-    //like admin posty
45
-    //category-y
46
-    //assign -> grants access to join-table
47
-    //(delete, edit)
48
-    //payment-method-y
49
-    //for each registered payment method,
50
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
-    /**
52
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
-     * They almost always WILL NOT, but it's not necessarily a requirement.
55
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
-     *
57
-     * @var boolean
58
-     */
59
-    private $_values_already_prepared_by_model_object = 0;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the data is just like form input that needs to have the model fields'
64
-     * prepare_for_set and prepare_for_use_in_db called on it
65
-     */
66
-    const not_prepared_by_model_object = 0;
67
-
68
-    /**
69
-     * when $_values_already_prepared_by_model_object equals this, we
70
-     * assume this value is coming from a model object and doesn't need to have
71
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
72
-     */
73
-    const prepared_by_model_object = 1;
74
-
75
-    /**
76
-     * when $_values_already_prepared_by_model_object equals this, we assume
77
-     * the values are already to be used in the database (ie no processing is done
78
-     * on them by the model's fields)
79
-     */
80
-    const prepared_for_use_in_db = 2;
81
-
82
-
83
-    protected $singular_item = 'Item';
84
-
85
-    protected $plural_item   = 'Items';
86
-
87
-    /**
88
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
-     */
90
-    protected $_tables;
91
-
92
-    /**
93
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
-     *
97
-     * @var \EE_Model_Field_Base[] $_fields
98
-     */
99
-    protected $_fields;
100
-
101
-    /**
102
-     * array of different kinds of relations
103
-     *
104
-     * @var \EE_Model_Relation_Base[] $_model_relations
105
-     */
106
-    protected $_model_relations;
107
-
108
-    /**
109
-     * @var \EE_Index[] $_indexes
110
-     */
111
-    protected $_indexes = array();
112
-
113
-    /**
114
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
115
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
-     * by setting the same columns as used in these queries in the query yourself.
117
-     *
118
-     * @var EE_Default_Where_Conditions
119
-     */
120
-    protected $_default_where_conditions_strategy;
121
-
122
-    /**
123
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
-     * This is particularly useful when you want something between 'none' and 'default'
125
-     *
126
-     * @var EE_Default_Where_Conditions
127
-     */
128
-    protected $_minimum_where_conditions_strategy;
129
-
130
-    /**
131
-     * String describing how to find the "owner" of this model's objects.
132
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
-     * But when there isn't, this indicates which related model, or transiently-related model,
134
-     * has the foreign key to the wp_users table.
135
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
-     * related to events, and events have a foreign key to wp_users.
137
-     * On EEM_Transaction, this would be 'Transaction.Event'
138
-     *
139
-     * @var string
140
-     */
141
-    protected $_model_chain_to_wp_user = '';
142
-
143
-    /**
144
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
-     * don't need it (particularly CPT models)
146
-     *
147
-     * @var bool
148
-     */
149
-    protected $_ignore_where_strategy = false;
150
-
151
-    /**
152
-     * String used in caps relating to this model. Eg, if the caps relating to this
153
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
-     *
155
-     * @var string. If null it hasn't been initialized yet. If false then we
156
-     * have indicated capabilities don't apply to this
157
-     */
158
-    protected $_caps_slug = null;
159
-
160
-    /**
161
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
-     * and next-level keys are capability names, and each's value is a
163
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
-     * they specify which context to use (ie, frontend, backend, edit or delete)
165
-     * and then each capability in the corresponding sub-array that they're missing
166
-     * adds the where conditions onto the query.
167
-     *
168
-     * @var array
169
-     */
170
-    protected $_cap_restrictions = array(
171
-        self::caps_read       => array(),
172
-        self::caps_read_admin => array(),
173
-        self::caps_edit       => array(),
174
-        self::caps_delete     => array(),
175
-    );
176
-
177
-    /**
178
-     * Array defining which cap restriction generators to use to create default
179
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
180
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
-     * automatically set this to false (not just null).
183
-     *
184
-     * @var EE_Restriction_Generator_Base[]
185
-     */
186
-    protected $_cap_restriction_generators = array();
187
-
188
-    /**
189
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
-     */
191
-    const caps_read       = 'read';
192
-
193
-    const caps_read_admin = 'read_admin';
194
-
195
-    const caps_edit       = 'edit';
196
-
197
-    const caps_delete     = 'delete';
198
-
199
-    /**
200
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
-     * maps to 'read' because when looking for relevant permissions we're going to use
203
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
204
-     *
205
-     * @var array
206
-     */
207
-    protected $_cap_contexts_to_cap_action_map = array(
208
-        self::caps_read       => 'read',
209
-        self::caps_read_admin => 'read',
210
-        self::caps_edit       => 'edit',
211
-        self::caps_delete     => 'delete',
212
-    );
213
-
214
-    /**
215
-     * Timezone
216
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
-     * EE_Datetime_Field data type will have access to it.
220
-     *
221
-     * @var string
222
-     */
223
-    protected $_timezone;
224
-
225
-
226
-    /**
227
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
-     * multisite.
229
-     *
230
-     * @var int
231
-     */
232
-    protected static $_model_query_blog_id;
233
-
234
-    /**
235
-     * A copy of _fields, except the array keys are the model names pointed to by
236
-     * the field
237
-     *
238
-     * @var EE_Model_Field_Base[]
239
-     */
240
-    private $_cache_foreign_key_to_fields = array();
241
-
242
-    /**
243
-     * Cached list of all the fields on the model, indexed by their name
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cached_fields = null;
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, except those that are
251
-     * marked as only pertinent to the database
252
-     *
253
-     * @var EE_Model_Field_Base[]
254
-     */
255
-    private $_cached_fields_non_db_only = null;
256
-
257
-    /**
258
-     * A cached reference to the primary key for quick lookup
259
-     *
260
-     * @var EE_Model_Field_Base
261
-     */
262
-    private $_primary_key_field = null;
263
-
264
-    /**
265
-     * Flag indicating whether this model has a primary key or not
266
-     *
267
-     * @var boolean
268
-     */
269
-    protected $_has_primary_key_field = null;
270
-
271
-    /**
272
-     * Whether or not this model is based off a table in WP core only (CPTs should set
273
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
-     *
275
-     * @var boolean
276
-     */
277
-    protected $_wp_core_model = false;
278
-
279
-    /**
280
-     *    List of valid operators that can be used for querying.
281
-     * The keys are all operators we'll accept, the values are the real SQL
282
-     * operators used
283
-     *
284
-     * @var array
285
-     */
286
-    protected $_valid_operators = array(
287
-        '='           => '=',
288
-        '<='          => '<=',
289
-        '<'           => '<',
290
-        '>='          => '>=',
291
-        '>'           => '>',
292
-        '!='          => '!=',
293
-        'LIKE'        => 'LIKE',
294
-        'like'        => 'LIKE',
295
-        'NOT_LIKE'    => 'NOT LIKE',
296
-        'not_like'    => 'NOT LIKE',
297
-        'NOT LIKE'    => 'NOT LIKE',
298
-        'not like'    => 'NOT LIKE',
299
-        'IN'          => 'IN',
300
-        'in'          => 'IN',
301
-        'NOT_IN'      => 'NOT IN',
302
-        'not_in'      => 'NOT IN',
303
-        'NOT IN'      => 'NOT IN',
304
-        'not in'      => 'NOT IN',
305
-        'between'     => 'BETWEEN',
306
-        'BETWEEN'     => 'BETWEEN',
307
-        'IS_NOT_NULL' => 'IS NOT NULL',
308
-        'is_not_null' => 'IS NOT NULL',
309
-        'IS NOT NULL' => 'IS NOT NULL',
310
-        'is not null' => 'IS NOT NULL',
311
-        'IS_NULL'     => 'IS NULL',
312
-        'is_null'     => 'IS NULL',
313
-        'IS NULL'     => 'IS NULL',
314
-        'is null'     => 'IS NULL',
315
-        'REGEXP'      => 'REGEXP',
316
-        'regexp'      => 'REGEXP',
317
-        'NOT_REGEXP'  => 'NOT REGEXP',
318
-        'not_regexp'  => 'NOT REGEXP',
319
-        'NOT REGEXP'  => 'NOT REGEXP',
320
-        'not regexp'  => 'NOT REGEXP',
321
-    );
322
-
323
-    /**
324
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
-     *
326
-     * @var array
327
-     */
328
-    protected $_in_style_operators = array('IN', 'NOT IN');
329
-
330
-    /**
331
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
-     * '12-31-2012'"
333
-     *
334
-     * @var array
335
-     */
336
-    protected $_between_style_operators = array('BETWEEN');
337
-
338
-    /**
339
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
-     * on a join table.
341
-     *
342
-     * @var array
343
-     */
344
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
-
346
-    /**
347
-     * Allowed values for $query_params['order'] for ordering in queries
348
-     *
349
-     * @var array
350
-     */
351
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
-
353
-    /**
354
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
356
-     *
357
-     * @var array
358
-     */
359
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
-
361
-    /**
362
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
364
-     *
365
-     * @var array
366
-     */
367
-    private $_allowed_query_params = array(
368
-        0,
369
-        'limit',
370
-        'order_by',
371
-        'group_by',
372
-        'having',
373
-        'force_join',
374
-        'order',
375
-        'on_join_limit',
376
-        'default_where_conditions',
377
-        'caps',
378
-    );
379
-
380
-    /**
381
-     * All the data types that can be used in $wpdb->prepare statements.
382
-     *
383
-     * @var array
384
-     */
385
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
-
387
-    /**
388
-     *    EE_Registry Object
389
-     *
390
-     * @var    object
391
-     * @access    protected
392
-     */
393
-    protected $EE = null;
394
-
395
-
396
-    /**
397
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
-     *
399
-     * @var int
400
-     */
401
-    protected $_show_next_x_db_queries = 0;
402
-
403
-    /**
404
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
-     *
407
-     * @var array
408
-     */
409
-    protected $_custom_selections = array();
410
-
411
-    /**
412
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
-     * caches every model object we've fetched from the DB on this request
414
-     *
415
-     * @var array
416
-     */
417
-    protected $_entity_map;
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 = 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 = 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 = 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
-     * Generates the cap restrictions for the given context, or if they were
654
-     * already generated just gets what's cached
655
-     *
656
-     * @param string $context one of EEM_Base::valid_cap_contexts()
657
-     * @return EE_Default_Where_Conditions[]
658
-     */
659
-    protected function _generate_cap_restrictions($context)
660
-    {
661
-        if (isset($this->_cap_restriction_generators[$context])
662
-            && $this->_cap_restriction_generators[$context]
663
-               instanceof
664
-               EE_Restriction_Generator_Base
665
-        ) {
666
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
-        } else {
668
-            return array();
669
-        }
670
-    }
671
-
672
-
673
-
674
-    /**
675
-     * Used to set the $_model_query_blog_id static property.
676
-     *
677
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
-     *                      value for get_current_blog_id() will be used.
679
-     */
680
-    public static function set_model_query_blog_id($blog_id = 0)
681
-    {
682
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
-    }
684
-
685
-
686
-
687
-    /**
688
-     * Returns whatever is set as the internal $model_query_blog_id.
689
-     *
690
-     * @return int
691
-     */
692
-    public static function get_model_query_blog_id()
693
-    {
694
-        return EEM_Base::$_model_query_blog_id;
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     *        This function is a singleton method used to instantiate the Espresso_model object
701
-     *
702
-     * @access public
703
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
-     *                         timezone in the 'timezone_string' wp option)
707
-     * @return static (as in the concrete child class)
708
-     */
709
-    public static function instance($timezone = null)
710
-    {
711
-        // check if instance of Espresso_model already exists
712
-        if (! static::$_instance instanceof static) {
713
-            // instantiate Espresso_model
714
-            static::$_instance = new static($timezone);
715
-        }
716
-        //we might have a timezone set, let set_timezone decide what to do with it
717
-        static::$_instance->set_timezone($timezone);
718
-        // Espresso_model object
719
-        return static::$_instance;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * resets the model and returns it
726
-     *
727
-     * @param null | string $timezone
728
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
-     * all its properties reset; if it wasn't instantiated, returns null)
730
-     */
731
-    public static function reset($timezone = null)
732
-    {
733
-        if (static::$_instance instanceof EEM_Base) {
734
-            //let's try to NOT swap out the current instance for a new one
735
-            //because if someone has a reference to it, we can't remove their reference
736
-            //so it's best to keep using the same reference, but change the original object
737
-            //reset all its properties to their original values as defined in the class
738
-            $r = new ReflectionClass(get_class(static::$_instance));
739
-            $static_properties = $r->getStaticProperties();
740
-            foreach ($r->getDefaultProperties() as $property => $value) {
741
-                //don't set instance to null like it was originally,
742
-                //but it's static anyways, and we're ignoring static properties (for now at least)
743
-                if (! isset($static_properties[$property])) {
744
-                    static::$_instance->{$property} = $value;
745
-                }
746
-            }
747
-            //and then directly call its constructor again, like we would if we
748
-            //were creating a new one
749
-            static::$_instance->__construct($timezone);
750
-            return self::instance();
751
-        }
752
-        return null;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
-     *
760
-     * @param  boolean $translated return localized strings or JUST the array.
761
-     * @return array
762
-     * @throws \EE_Error
763
-     */
764
-    public function status_array($translated = false)
765
-    {
766
-        if (! array_key_exists('Status', $this->_model_relations)) {
767
-            return array();
768
-        }
769
-        $model_name = $this->get_this_model_name();
770
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
-        $status_array = array();
773
-        foreach ($stati as $status) {
774
-            $status_array[$status->ID()] = $status->get('STS_code');
775
-        }
776
-        return $translated
777
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
-            : $status_array;
779
-    }
780
-
781
-
782
-
783
-    /**
784
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
-     *
786
-     * @param array $query_params             {
787
-     * @var array $0 (where) array {
788
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
-     *                                        conditions based on related models (and even
792
-     *                                        models-related-to-related-models) prepend the model's name onto the field
793
-     *                                        name. Eg,
794
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
-     *                                        to Venues (even when each of those models actually consisted of two
802
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
803
-     *                                        just having
804
-     *                                        "Venue.VNU_ID", you could have
805
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
-     *                                        events are related to Registrations, which are related to Attendees). You
807
-     *                                        can take it even further with
808
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
-     *                                        (from the default of '='), change the value to an numerically-indexed
810
-     *                                        array, where the first item in the list is the operator. eg: array(
811
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
819
-     *                                        the value is a field, simply provide a third array item (true) to the
820
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
-     *                                        Note: you can also use related model field names like you would any other
823
-     *                                        field name. eg:
824
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
-     *                                        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__>' =>
826
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
833
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
-     *                                        "stick" until you specify an AND. eg
835
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
-     *                                        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 >>
840
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
-     *                                        too, eg:
843
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
848
-     *                                        the OFFSET, the 2nd is the LIMIT
849
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
-     *                                        following format array('on_join_limit'
852
-     *                                        => array( 'table_alias', array(1,2) ) ).
853
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
-     *                                        values are either 'ASC' or 'DESC'.
855
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
-     *                                        DESC..." respectively. Like the
858
-     *                                        'where' conditions, these fields can be on related models. Eg
859
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
861
-     *                                        Attendee, Price, Datetime, etc.)
862
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
864
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
-     *                                        order by the primary key. Eg,
867
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
-     *                                        //(will join with the Datetime model's table(s) and order by its field
869
-     *                                        DTT_EVT_start) or
870
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
-     *                                        'group_by'=>'VNU_ID', or
874
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
-     *                                        if no
876
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
877
-     *                                        model's primary key (or combined primary keys). This avoids some
878
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
879
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
-     *                                        results)
883
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
-     *                                        array where values are models to be joined in the query.Eg
885
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
887
-     *                                        probably only want to do this in hopes of increasing efficiency, as
888
-     *                                        related models which belongs to the current model
889
-     *                                        (ie, the current model has a foreign key to them, like how Registration
890
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
891
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
894
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
-     *                                        default where conditions set it to 'other_models_only'. If you only want
896
-     *                                        this model's default where conditions added to the query, use
897
-     *                                        'this_model_only'. If you want to use all default where conditions
898
-     *                                        (default), set to 'all'.
899
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
-     *                                        everything? Or should we only show the current user items they should be
902
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
-     *                                        }
905
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
-     *                                        array( array(
911
-     *                                        'OR'=>array(
912
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
-     *                                        )
915
-     *                                        ),
916
-     *                                        'limit'=>10,
917
-     *                                        'group_by'=>'TXN_ID'
918
-     *                                        ));
919
-     *                                        get all the answers to the question titled "shirt size" for event with id
920
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
-     *                                        'Question.QST_display_text'=>'shirt size',
922
-     *                                        'Registration.Event.EVT_ID'=>12
923
-     *                                        ),
924
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
925
-     *                                        ));
926
-     * @throws \EE_Error
927
-     */
928
-    public function get_all($query_params = array())
929
-    {
930
-        if (isset($query_params['limit'])
931
-            && ! isset($query_params['group_by'])
932
-        ) {
933
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
-        }
935
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
-    }
937
-
938
-
939
-
940
-    /**
941
-     * Modifies the query parameters so we only get back model objects
942
-     * that "belong" to the current user
943
-     *
944
-     * @param array $query_params @see EEM_Base::get_all()
945
-     * @return array like EEM_Base::get_all
946
-     */
947
-    public function alter_query_params_to_only_include_mine($query_params = array())
948
-    {
949
-        $wp_user_field_name = $this->wp_user_field_name();
950
-        if ($wp_user_field_name) {
951
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
952
-        }
953
-        return $query_params;
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * Returns the name of the field's name that points to the WP_User table
960
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
-     * foreign key to the WP_User table)
962
-     *
963
-     * @return string|boolean string on success, boolean false when there is no
964
-     * foreign key to the WP_User table
965
-     */
966
-    public function wp_user_field_name()
967
-    {
968
-        try {
969
-            if (! empty($this->_model_chain_to_wp_user)) {
970
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
-                $last_model_name = end($models_to_follow_to_wp_users);
972
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
-            } else {
975
-                $model_with_fk_to_wp_users = $this;
976
-                $model_chain_to_wp_user = '';
977
-            }
978
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
980
-        } catch (EE_Error $e) {
981
-            return false;
982
-        }
983
-    }
984
-
985
-
986
-
987
-    /**
988
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
989
-     * (or transiently-related model) has a foreign key to the wp_users table;
990
-     * useful for finding if model objects of this type are 'owned' by the current user.
991
-     * This is an empty string when the foreign key is on this model and when it isn't,
992
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
993
-     * (or transiently-related model)
994
-     *
995
-     * @return string
996
-     */
997
-    public function model_chain_to_wp_user()
998
-    {
999
-        return $this->_model_chain_to_wp_user;
1000
-    }
1001
-
1002
-
1003
-
1004
-    /**
1005
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
-     * like how registrations don't have a foreign key to wp_users, but the
1007
-     * events they are for are), or is unrelated to wp users.
1008
-     * generally available
1009
-     *
1010
-     * @return boolean
1011
-     */
1012
-    public function is_owned()
1013
-    {
1014
-        if ($this->model_chain_to_wp_user()) {
1015
-            return true;
1016
-        } else {
1017
-            try {
1018
-                $this->get_foreign_key_to('WP_User');
1019
-                return true;
1020
-            } catch (EE_Error $e) {
1021
-                return false;
1022
-            }
1023
-        }
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
-     * the model)
1032
-     *
1033
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1037
-     *                                  override this and set the select to "*", or a specific column name, like
1038
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
-     *                                  the aliases used to refer to this selection, and values are to be
1041
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
-     * @throws \EE_Error
1045
-     */
1046
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
-    {
1048
-        // remember the custom selections, if any, and type cast as array
1049
-        // (unless $columns_to_select is an object, then just set as an empty array)
1050
-        // Note: (array) 'some string' === array( 'some string' )
1051
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
-        $select_expressions = $columns_to_select !== null
1054
-            ? $this->_construct_select_from_input($columns_to_select)
1055
-            : $this->_construct_default_select_sql($model_query_info);
1056
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
-    }
1059
-
1060
-
1061
-
1062
-    /**
1063
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1064
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
-     * take care of joins, field preparation etc.
1066
-     *
1067
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1071
-     *                                  override this and set the select to "*", or a specific column name, like
1072
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
-     *                                  the aliases used to refer to this selection, and values are to be
1075
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
-     * @throws \EE_Error
1079
-     */
1080
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
-    {
1082
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
-    }
1084
-
1085
-
1086
-
1087
-    /**
1088
-     * For creating a custom select statement
1089
-     *
1090
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
-     *                                 SQL, and 1=>is the datatype
1093
-     * @throws EE_Error
1094
-     * @return string
1095
-     */
1096
-    private function _construct_select_from_input($columns_to_select)
1097
-    {
1098
-        if (is_array($columns_to_select)) {
1099
-            $select_sql_array = array();
1100
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
-                    throw new EE_Error(
1103
-                        sprintf(
1104
-                            __(
1105
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
-                                "event_espresso"
1107
-                            ),
1108
-                            $selection_and_datatype,
1109
-                            $alias
1110
-                        )
1111
-                    );
1112
-                }
1113
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
-                    throw new EE_Error(
1115
-                        sprintf(
1116
-                            __(
1117
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
-                                "event_espresso"
1119
-                            ),
1120
-                            $selection_and_datatype[1],
1121
-                            $selection_and_datatype[0],
1122
-                            $alias,
1123
-                            implode(",", $this->_valid_wpdb_data_types)
1124
-                        )
1125
-                    );
1126
-                }
1127
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
-            }
1129
-            $columns_to_select_string = implode(", ", $select_sql_array);
1130
-        } else {
1131
-            $columns_to_select_string = $columns_to_select;
1132
-        }
1133
-        return $columns_to_select_string;
1134
-    }
1135
-
1136
-
1137
-
1138
-    /**
1139
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
-     *
1141
-     * @return string
1142
-     * @throws \EE_Error
1143
-     */
1144
-    public function primary_key_name()
1145
-    {
1146
-        return $this->get_primary_key_field()->get_name();
1147
-    }
1148
-
1149
-
1150
-
1151
-    /**
1152
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
-     * If there is no primary key on this model, $id is treated as primary key string
1154
-     *
1155
-     * @param mixed $id int or string, depending on the type of the model's primary key
1156
-     * @return EE_Base_Class
1157
-     */
1158
-    public function get_one_by_ID($id)
1159
-    {
1160
-        if ($this->get_from_entity_map($id)) {
1161
-            return $this->get_from_entity_map($id);
1162
-        }
1163
-        return $this->get_one(
1164
-            $this->alter_query_params_to_restrict_by_ID(
1165
-                $id,
1166
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
-            )
1168
-        );
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Alters query parameters to only get items with this ID are returned.
1175
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
-     * or could just be a simple primary key ID
1177
-     *
1178
-     * @param int   $id
1179
-     * @param array $query_params
1180
-     * @return array of normal query params, @see EEM_Base::get_all
1181
-     * @throws \EE_Error
1182
-     */
1183
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
-    {
1185
-        if (! isset($query_params[0])) {
1186
-            $query_params[0] = array();
1187
-        }
1188
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1189
-        if ($conditions_from_id === null) {
1190
-            $query_params[0][$this->primary_key_name()] = $id;
1191
-        } else {
1192
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1193
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
-        }
1195
-        return $query_params;
1196
-    }
1197
-
1198
-
1199
-
1200
-    /**
1201
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
-     * array. If no item is found, null is returned.
1203
-     *
1204
-     * @param array $query_params like EEM_Base's $query_params variable.
1205
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
-     * @throws \EE_Error
1207
-     */
1208
-    public function get_one($query_params = array())
1209
-    {
1210
-        if (! is_array($query_params)) {
1211
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
-                    gettype($query_params)), '4.6.0');
1214
-            $query_params = array();
1215
-        }
1216
-        $query_params['limit'] = 1;
1217
-        $items = $this->get_all($query_params);
1218
-        if (empty($items)) {
1219
-            return null;
1220
-        } else {
1221
-            return array_shift($items);
1222
-        }
1223
-    }
1224
-
1225
-
1226
-
1227
-    /**
1228
-     * Returns the next x number of items in sequence from the given value as
1229
-     * found in the database matching the given query conditions.
1230
-     *
1231
-     * @param mixed $current_field_value    Value used for the reference point.
1232
-     * @param null  $field_to_order_by      What field is used for the
1233
-     *                                      reference point.
1234
-     * @param int   $limit                  How many to return.
1235
-     * @param array $query_params           Extra conditions on the query.
1236
-     * @param null  $columns_to_select      If left null, then an array of
1237
-     *                                      EE_Base_Class objects is returned,
1238
-     *                                      otherwise you can indicate just the
1239
-     *                                      columns you want returned.
1240
-     * @return EE_Base_Class[]|array
1241
-     * @throws \EE_Error
1242
-     */
1243
-    public function next_x(
1244
-        $current_field_value,
1245
-        $field_to_order_by = null,
1246
-        $limit = 1,
1247
-        $query_params = array(),
1248
-        $columns_to_select = null
1249
-    ) {
1250
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
-            $columns_to_select);
1252
-    }
1253
-
1254
-
1255
-
1256
-    /**
1257
-     * Returns the previous x number of items in sequence from the given value
1258
-     * as found in the database matching the given query conditions.
1259
-     *
1260
-     * @param mixed $current_field_value    Value used for the reference point.
1261
-     * @param null  $field_to_order_by      What field is used for the
1262
-     *                                      reference point.
1263
-     * @param int   $limit                  How many to return.
1264
-     * @param array $query_params           Extra conditions on the query.
1265
-     * @param null  $columns_to_select      If left null, then an array of
1266
-     *                                      EE_Base_Class objects is returned,
1267
-     *                                      otherwise you can indicate just the
1268
-     *                                      columns you want returned.
1269
-     * @return EE_Base_Class[]|array
1270
-     * @throws \EE_Error
1271
-     */
1272
-    public function previous_x(
1273
-        $current_field_value,
1274
-        $field_to_order_by = null,
1275
-        $limit = 1,
1276
-        $query_params = array(),
1277
-        $columns_to_select = null
1278
-    ) {
1279
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
-            $columns_to_select);
1281
-    }
1282
-
1283
-
1284
-
1285
-    /**
1286
-     * Returns the next item in sequence from the given value as found in the
1287
-     * database matching the given query conditions.
1288
-     *
1289
-     * @param mixed $current_field_value    Value used for the reference point.
1290
-     * @param null  $field_to_order_by      What field is used for the
1291
-     *                                      reference point.
1292
-     * @param array $query_params           Extra conditions on the query.
1293
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
-     *                                      object is returned, otherwise you
1295
-     *                                      can indicate just the columns you
1296
-     *                                      want and a single array indexed by
1297
-     *                                      the columns will be returned.
1298
-     * @return EE_Base_Class|null|array()
1299
-     * @throws \EE_Error
1300
-     */
1301
-    public function next(
1302
-        $current_field_value,
1303
-        $field_to_order_by = null,
1304
-        $query_params = array(),
1305
-        $columns_to_select = null
1306
-    ) {
1307
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
-            $columns_to_select);
1309
-        return empty($results) ? null : reset($results);
1310
-    }
1311
-
1312
-
1313
-
1314
-    /**
1315
-     * Returns the previous item in sequence from the given value as found in
1316
-     * the database matching the given query conditions.
1317
-     *
1318
-     * @param mixed $current_field_value    Value used for the reference point.
1319
-     * @param null  $field_to_order_by      What field is used for the
1320
-     *                                      reference point.
1321
-     * @param array $query_params           Extra conditions on the query.
1322
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
-     *                                      object is returned, otherwise you
1324
-     *                                      can indicate just the columns you
1325
-     *                                      want and a single array indexed by
1326
-     *                                      the columns will be returned.
1327
-     * @return EE_Base_Class|null|array()
1328
-     * @throws EE_Error
1329
-     */
1330
-    public function previous(
1331
-        $current_field_value,
1332
-        $field_to_order_by = null,
1333
-        $query_params = array(),
1334
-        $columns_to_select = null
1335
-    ) {
1336
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
-            $columns_to_select);
1338
-        return empty($results) ? null : reset($results);
1339
-    }
1340
-
1341
-
1342
-
1343
-    /**
1344
-     * Returns the a consecutive number of items in sequence from the given
1345
-     * value as found in the database matching the given query conditions.
1346
-     *
1347
-     * @param mixed  $current_field_value   Value used for the reference point.
1348
-     * @param string $operand               What operand is used for the sequence.
1349
-     * @param string $field_to_order_by     What field is used for the reference point.
1350
-     * @param int    $limit                 How many to return.
1351
-     * @param array  $query_params          Extra conditions on the query.
1352
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
-     *                                      otherwise you can indicate just the columns you want returned.
1354
-     * @return EE_Base_Class[]|array
1355
-     * @throws EE_Error
1356
-     */
1357
-    protected function _get_consecutive(
1358
-        $current_field_value,
1359
-        $operand = '>',
1360
-        $field_to_order_by = null,
1361
-        $limit = 1,
1362
-        $query_params = array(),
1363
-        $columns_to_select = null
1364
-    ) {
1365
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
-        if (empty($field_to_order_by)) {
1367
-            if ($this->has_primary_key_field()) {
1368
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1369
-            } else {
1370
-                if (WP_DEBUG) {
1371
-                    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).',
1372
-                        'event_espresso'));
1373
-                }
1374
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
-                return array();
1376
-            }
1377
-        }
1378
-        if (! is_array($query_params)) {
1379
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
-                    gettype($query_params)), '4.6.0');
1382
-            $query_params = array();
1383
-        }
1384
-        //let's add the where query param for consecutive look up.
1385
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
-        $query_params['limit'] = $limit;
1387
-        //set direction
1388
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
-        $query_params['order_by'] = $operand === '>'
1390
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
-        if (empty($columns_to_select)) {
1394
-            return $this->get_all($query_params);
1395
-        } else {
1396
-            //getting just the fields
1397
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
-        }
1399
-    }
1400
-
1401
-
1402
-
1403
-    /**
1404
-     * This sets the _timezone property after model object has been instantiated.
1405
-     *
1406
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
-     */
1408
-    public function set_timezone($timezone)
1409
-    {
1410
-        if ($timezone !== null) {
1411
-            $this->_timezone = $timezone;
1412
-        }
1413
-        //note we need to loop through relations and set the timezone on those objects as well.
1414
-        foreach ($this->_model_relations as $relation) {
1415
-            $relation->set_timezone($timezone);
1416
-        }
1417
-        //and finally we do the same for any datetime fields
1418
-        foreach ($this->_fields as $field) {
1419
-            if ($field instanceof EE_Datetime_Field) {
1420
-                $field->set_timezone($timezone);
1421
-            }
1422
-        }
1423
-    }
1424
-
1425
-
1426
-
1427
-    /**
1428
-     * This just returns whatever is set for the current timezone.
1429
-     *
1430
-     * @access public
1431
-     * @return string
1432
-     */
1433
-    public function get_timezone()
1434
-    {
1435
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
-        if (empty($this->_timezone)) {
1437
-            foreach ($this->_fields as $field) {
1438
-                if ($field instanceof EE_Datetime_Field) {
1439
-                    $this->set_timezone($field->get_timezone());
1440
-                    break;
1441
-                }
1442
-            }
1443
-        }
1444
-        //if timezone STILL empty then return the default timezone for the site.
1445
-        if (empty($this->_timezone)) {
1446
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
-        }
1448
-        return $this->_timezone;
1449
-    }
1450
-
1451
-
1452
-
1453
-    /**
1454
-     * This returns the date formats set for the given field name and also ensures that
1455
-     * $this->_timezone property is set correctly.
1456
-     *
1457
-     * @since 4.6.x
1458
-     * @param string $field_name The name of the field the formats are being retrieved for.
1459
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1462
-     */
1463
-    public function get_formats_for($field_name, $pretty = false)
1464
-    {
1465
-        $field_settings = $this->field_settings_for($field_name);
1466
-        //if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1468
-            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.',
1469
-                'event_espresso'), $field_name));
1470
-        }
1471
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
-        //the field.
1473
-        $this->_timezone = $field_settings->get_timezone();
1474
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
-    }
1476
-
1477
-
1478
-
1479
-    /**
1480
-     * This returns the current time in a format setup for a query on this model.
1481
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
-     * it will return:
1483
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
-     *  NOW
1485
-     *  - or a unix timestamp (equivalent to time())
1486
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1487
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1488
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1489
-     * @since 4.6.x
1490
-     * @param string $field_name       The field the current time is needed for.
1491
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1492
-     *                                 formatted string matching the set format for the field in the set timezone will
1493
-     *                                 be returned.
1494
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1495
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1496
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497
-     *                                 exception is triggered.
1498
-     */
1499
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1500
-    {
1501
-        $formats = $this->get_formats_for($field_name);
1502
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1503
-        if ($timestamp) {
1504
-            return $DateTime->format('U');
1505
-        }
1506
-        //not returning timestamp, so return formatted string in timezone.
1507
-        switch ($what) {
1508
-            case 'time' :
1509
-                return $DateTime->format($formats[1]);
1510
-                break;
1511
-            case 'date' :
1512
-                return $DateTime->format($formats[0]);
1513
-                break;
1514
-            default :
1515
-                return $DateTime->format(implode(' ', $formats));
1516
-                break;
1517
-        }
1518
-    }
1519
-
1520
-
1521
-
1522
-    /**
1523
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1524
-     * for the model are.  Returns a DateTime object.
1525
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1526
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1527
-     * ignored.
1528
-     *
1529
-     * @param string $field_name      The field being setup.
1530
-     * @param string $timestring      The date time string being used.
1531
-     * @param string $incoming_format The format for the time string.
1532
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1533
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1534
-     *                                format is
1535
-     *                                'U', this is ignored.
1536
-     * @return DateTime
1537
-     * @throws \EE_Error
1538
-     */
1539
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1540
-    {
1541
-        //just using this to ensure the timezone is set correctly internally
1542
-        $this->get_formats_for($field_name);
1543
-        //load EEH_DTT_Helper
1544
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1547
-    }
1548
-
1549
-
1550
-
1551
-    /**
1552
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1553
-     *
1554
-     * @return EE_Table_Base[]
1555
-     */
1556
-    public function get_tables()
1557
-    {
1558
-        return $this->_tables;
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1565
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1566
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1567
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1568
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1569
-     * model object with EVT_ID = 1
1570
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1571
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1572
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1573
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1574
-     * are not specified)
1575
-     *
1576
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1577
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1578
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1579
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1580
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1581
-     *                                         ID=34, we'd use this method as follows:
1582
-     *                                         EEM_Transaction::instance()->update(
1583
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1584
-     *                                         array(array('TXN_ID'=>34)));
1585
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1586
-     *                                         in client code into what's expected to be stored on each field. Eg,
1587
-     *                                         consider updating Question's QST_admin_label field is of type
1588
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1589
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1590
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1591
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1592
-     *                                         TRUE, it is assumed that you've already called
1593
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1594
-     *                                         malicious javascript. However, if
1595
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1596
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1597
-     *                                         and every other field, before insertion. We provide this parameter
1598
-     *                                         because model objects perform their prepare_for_set function on all
1599
-     *                                         their values, and so don't need to be called again (and in many cases,
1600
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1601
-     *                                         prepare_for_set method...)
1602
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1603
-     *                                         in this model's entity map according to $fields_n_values that match
1604
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1605
-     *                                         by setting this to FALSE, but be aware that model objects being used
1606
-     *                                         could get out-of-sync with the database
1607
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1608
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1609
-     *                                         bad)
1610
-     * @throws \EE_Error
1611
-     */
1612
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613
-    {
1614
-        if (! is_array($query_params)) {
1615
-            EE_Error::doing_it_wrong('EEM_Base::update',
1616
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617
-                    gettype($query_params)), '4.6.0');
1618
-            $query_params = array();
1619
-        }
1620
-        /**
1621
-         * Action called before a model update call has been made.
1622
-         *
1623
-         * @param EEM_Base $model
1624
-         * @param array    $fields_n_values the updated fields and their new values
1625
-         * @param array    $query_params    @see EEM_Base::get_all()
1626
-         */
1627
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1628
-        /**
1629
-         * Filters the fields about to be updated given the query parameters. You can provide the
1630
-         * $query_params to $this->get_all() to find exactly which records will be updated
1631
-         *
1632
-         * @param array    $fields_n_values fields and their new values
1633
-         * @param EEM_Base $model           the model being queried
1634
-         * @param array    $query_params    see EEM_Base::get_all()
1635
-         */
1636
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637
-            $query_params);
1638
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1639
-        //to do that, for each table, verify that it's PK isn't null.
1640
-        $tables = $this->get_tables();
1641
-        //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
1642
-        //NOTE: we should make this code more efficient by NOT querying twice
1643
-        //before the real update, but that needs to first go through ALPHA testing
1644
-        //as it's dangerous. says Mike August 8 2014
1645
-        //we want to make sure the default_where strategy is ignored
1646
-        $this->_ignore_where_strategy = true;
1647
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648
-        foreach ($wpdb_select_results as $wpdb_result) {
1649
-            // type cast stdClass as array
1650
-            $wpdb_result = (array)$wpdb_result;
1651
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652
-            if ($this->has_primary_key_field()) {
1653
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1654
-            } else {
1655
-                //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)
1656
-                $main_table_pk_value = null;
1657
-            }
1658
-            //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
1659
-            //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
1660
-            if (count($tables) > 1) {
1661
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1662
-                //in that table, and so we'll want to insert one
1663
-                foreach ($tables as $table_obj) {
1664
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665
-                    //if there is no private key for this table on the results, it means there's no entry
1666
-                    //in this table, right? so insert a row in the current table, using any fields available
1667
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1668
-                           && $wpdb_result[$this_table_pk_column])
1669
-                    ) {
1670
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671
-                            $main_table_pk_value);
1672
-                        //if we died here, report the error
1673
-                        if (! $success) {
1674
-                            return false;
1675
-                        }
1676
-                    }
1677
-                }
1678
-            }
1679
-            //				//and now check that if we have cached any models by that ID on the model, that
1680
-            //				//they also get updated properly
1681
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1682
-            //				if( $model_object ){
1683
-            //					foreach( $fields_n_values as $field => $value ){
1684
-            //						$model_object->set($field, $value);
1685
-            //let's make sure default_where strategy is followed now
1686
-            $this->_ignore_where_strategy = false;
1687
-        }
1688
-        //if we want to keep model objects in sync, AND
1689
-        //if this wasn't called from a model object (to update itself)
1690
-        //then we want to make sure we keep all the existing
1691
-        //model objects in sync with the db
1692
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1693
-            if ($this->has_primary_key_field()) {
1694
-                $model_objs_affected_ids = $this->get_col($query_params);
1695
-            } else {
1696
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1697
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1698
-                $model_objs_affected_ids = array();
1699
-                foreach ($models_affected_key_columns as $row) {
1700
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1701
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702
-                }
1703
-            }
1704
-            if (! $model_objs_affected_ids) {
1705
-                //wait wait wait- if nothing was affected let's stop here
1706
-                return 0;
1707
-            }
1708
-            foreach ($model_objs_affected_ids as $id) {
1709
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1710
-                if ($model_obj_in_entity_map) {
1711
-                    foreach ($fields_n_values as $field => $new_value) {
1712
-                        $model_obj_in_entity_map->set($field, $new_value);
1713
-                    }
1714
-                }
1715
-            }
1716
-            //if there is a primary key on this model, we can now do a slight optimization
1717
-            if ($this->has_primary_key_field()) {
1718
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1719
-                $query_params = array(
1720
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1721
-                    'limit'                    => count($model_objs_affected_ids),
1722
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1723
-                );
1724
-            }
1725
-        }
1726
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1727
-        $SQL = "UPDATE "
1728
-               . $model_query_info->get_full_join_sql()
1729
-               . " SET "
1730
-               . $this->_construct_update_sql($fields_n_values)
1731
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733
-        /**
1734
-         * Action called after a model update call has been made.
1735
-         *
1736
-         * @param EEM_Base $model
1737
-         * @param array    $fields_n_values the updated fields and their new values
1738
-         * @param array    $query_params    @see EEM_Base::get_all()
1739
-         * @param int      $rows_affected
1740
-         */
1741
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
-        return $rows_affected;//how many supposedly got updated
1743
-    }
1744
-
1745
-
1746
-
1747
-    /**
1748
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1749
-     * are teh values of the field specified (or by default the primary key field)
1750
-     * that matched the query params. Note that you should pass the name of the
1751
-     * model FIELD, not the database table's column name.
1752
-     *
1753
-     * @param array  $query_params @see EEM_Base::get_all()
1754
-     * @param string $field_to_select
1755
-     * @return array just like $wpdb->get_col()
1756
-     * @throws \EE_Error
1757
-     */
1758
-    public function get_col($query_params = array(), $field_to_select = null)
1759
-    {
1760
-        if ($field_to_select) {
1761
-            $field = $this->field_settings_for($field_to_select);
1762
-        } elseif ($this->has_primary_key_field()) {
1763
-            $field = $this->get_primary_key_field();
1764
-        } else {
1765
-            //no primary key, just grab the first column
1766
-            $field = reset($this->field_settings());
1767
-        }
1768
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
-        $select_expressions = $field->get_qualified_column();
1770
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1771
-        return $this->_do_wpdb_query('get_col', array($SQL));
1772
-    }
1773
-
1774
-
1775
-
1776
-    /**
1777
-     * Returns a single column value for a single row from the database
1778
-     *
1779
-     * @param array  $query_params    @see EEM_Base::get_all()
1780
-     * @param string $field_to_select @see EEM_Base::get_col()
1781
-     * @return string
1782
-     * @throws \EE_Error
1783
-     */
1784
-    public function get_var($query_params = array(), $field_to_select = null)
1785
-    {
1786
-        $query_params['limit'] = 1;
1787
-        $col = $this->get_col($query_params, $field_to_select);
1788
-        if (! empty($col)) {
1789
-            return reset($col);
1790
-        } else {
1791
-            return null;
1792
-        }
1793
-    }
1794
-
1795
-
1796
-
1797
-    /**
1798
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1799
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1800
-     * injection, but currently no further filtering is done
1801
-     *
1802
-     * @global      $wpdb
1803
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1804
-     *                               be updated to in the DB
1805
-     * @return string of SQL
1806
-     * @throws \EE_Error
1807
-     */
1808
-    public function _construct_update_sql($fields_n_values)
1809
-    {
1810
-        /** @type WPDB $wpdb */
1811
-        global $wpdb;
1812
-        $cols_n_values = array();
1813
-        foreach ($fields_n_values as $field_name => $value) {
1814
-            $field_obj = $this->field_settings_for($field_name);
1815
-            //if the value is NULL, we want to assign the value to that.
1816
-            //wpdb->prepare doesn't really handle that properly
1817
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818
-            $value_sql = $prepared_value === null ? 'NULL'
1819
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1821
-        }
1822
-        return implode(",", $cols_n_values);
1823
-    }
1824
-
1825
-
1826
-
1827
-    /**
1828
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1829
-     * Performs a HARD delete, meaning the database row should always be removed,
1830
-     * not just have a flag field on it switched
1831
-     * Wrapper for EEM_Base::delete_permanently()
1832
-     *
1833
-     * @param mixed $id
1834
-     * @return boolean whether the row got deleted or not
1835
-     * @throws \EE_Error
1836
-     */
1837
-    public function delete_permanently_by_ID($id)
1838
-    {
1839
-        return $this->delete_permanently(
1840
-            array(
1841
-                array($this->get_primary_key_field()->get_name() => $id),
1842
-                'limit' => 1,
1843
-            )
1844
-        );
1845
-    }
1846
-
1847
-
1848
-
1849
-    /**
1850
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
-     * Wrapper for EEM_Base::delete()
1852
-     *
1853
-     * @param mixed $id
1854
-     * @return boolean whether the row got deleted or not
1855
-     * @throws \EE_Error
1856
-     */
1857
-    public function delete_by_ID($id)
1858
-    {
1859
-        return $this->delete(
1860
-            array(
1861
-                array($this->get_primary_key_field()->get_name() => $id),
1862
-                'limit' => 1,
1863
-            )
1864
-        );
1865
-    }
1866
-
1867
-
1868
-
1869
-    /**
1870
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1871
-     * meaning if the model has a field that indicates its been "trashed" or
1872
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1873
-     *
1874
-     * @see EEM_Base::delete_permanently
1875
-     * @param array   $query_params
1876
-     * @param boolean $allow_blocking
1877
-     * @return int how many rows got deleted
1878
-     * @throws \EE_Error
1879
-     */
1880
-    public function delete($query_params, $allow_blocking = true)
1881
-    {
1882
-        return $this->delete_permanently($query_params, $allow_blocking);
1883
-    }
1884
-
1885
-
1886
-
1887
-    /**
1888
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1889
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1890
-     * as archived, not actually deleted
1891
-     *
1892
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1893
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1894
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1895
-     *                                deletes regardless of other objects which may depend on it. Its generally
1896
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1897
-     *                                DB
1898
-     * @return int how many rows got deleted
1899
-     * @throws \EE_Error
1900
-     */
1901
-    public function delete_permanently($query_params, $allow_blocking = true)
1902
-    {
1903
-        /**
1904
-         * Action called just before performing a real deletion query. You can use the
1905
-         * model and its $query_params to find exactly which items will be deleted
1906
-         *
1907
-         * @param EEM_Base $model
1908
-         * @param array    $query_params   @see EEM_Base::get_all()
1909
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1910
-         *                                 to block (prevent) this deletion
1911
-         */
1912
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1913
-        //some MySQL databases may be running safe mode, which may restrict
1914
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1915
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1916
-        //to delete them
1917
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1918
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1919
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1920
-            $columns_and_ids_for_deleting
1921
-        );
1922
-        /**
1923
-         * Allows client code to act on the items being deleted before the query is actually executed.
1924
-         *
1925
-         * @param EEM_Base $this  The model instance being acted on.
1926
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1927
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1928
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1929
-         *                                                  derived from the incoming query parameters.
1930
-         *                                                  @see details on the structure of this array in the phpdocs
1931
-         *                                                  for the `_get_ids_for_delete_method`
1932
-         *
1933
-         */
1934
-        do_action('AHEE__EEM_Base__delete__before_query',
1935
-            $this,
1936
-            $query_params,
1937
-            $allow_blocking,
1938
-            $columns_and_ids_for_deleting
1939
-        );
1940
-        if ($deletion_where_query_part) {
1941
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1942
-            $table_aliases = array_keys($this->_tables);
1943
-            $SQL = "DELETE "
1944
-                   . implode(", ", $table_aliases)
1945
-                   . " FROM "
1946
-                   . $model_query_info->get_full_join_sql()
1947
-                   . " WHERE "
1948
-                   . $deletion_where_query_part;
1949
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1950
-        } else {
1951
-            $rows_deleted = 0;
1952
-        }
1953
-
1954
-        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1955
-        //there was no error with the delete query.
1956
-        if ($this->has_primary_key_field()
1957
-            && $rows_deleted !== false
1958
-            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1959
-        ) {
1960
-            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1961
-            foreach ($ids_for_removal as $id) {
1962
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1963
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1964
-                }
1965
-            }
1966
-
1967
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1968
-            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1969
-            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1970
-            // (although it is possible).
1971
-            //Note this can be skipped by using the provided filter and returning false.
1972
-            if (apply_filters(
1973
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1974
-                ! $this instanceof EEM_Extra_Meta,
1975
-                $this
1976
-            )) {
1977
-                EEM_Extra_Meta::instance()->delete_permanently(array(
1978
-                    0 => array(
1979
-                        'EXM_type' => $this->get_this_model_name(),
1980
-                        'OBJ_ID'   => array(
1981
-                            'IN',
1982
-                            $ids_for_removal
1983
-                        )
1984
-                    )
1985
-                ));
1986
-            }
1987
-        }
1988
-
1989
-        /**
1990
-         * Action called just after performing a real deletion query. Although at this point the
1991
-         * items should have been deleted
1992
-         *
1993
-         * @param EEM_Base $model
1994
-         * @param array    $query_params @see EEM_Base::get_all()
1995
-         * @param int      $rows_deleted
1996
-         */
1997
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
1998
-        return $rows_deleted;//how many supposedly got deleted
1999
-    }
2000
-
2001
-
2002
-
2003
-    /**
2004
-     * Checks all the relations that throw error messages when there are blocking related objects
2005
-     * for related model objects. If there are any related model objects on those relations,
2006
-     * adds an EE_Error, and return true
2007
-     *
2008
-     * @param EE_Base_Class|int $this_model_obj_or_id
2009
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2010
-     *                                                 should be ignored when determining whether there are related
2011
-     *                                                 model objects which block this model object's deletion. Useful
2012
-     *                                                 if you know A is related to B and are considering deleting A,
2013
-     *                                                 but want to see if A has any other objects blocking its deletion
2014
-     *                                                 before removing the relation between A and B
2015
-     * @return boolean
2016
-     * @throws \EE_Error
2017
-     */
2018
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2019
-    {
2020
-        //first, if $ignore_this_model_obj was supplied, get its model
2021
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2022
-            $ignored_model = $ignore_this_model_obj->get_model();
2023
-        } else {
2024
-            $ignored_model = null;
2025
-        }
2026
-        //now check all the relations of $this_model_obj_or_id and see if there
2027
-        //are any related model objects blocking it?
2028
-        $is_blocked = false;
2029
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2030
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2031
-                //if $ignore_this_model_obj was supplied, then for the query
2032
-                //on that model needs to be told to ignore $ignore_this_model_obj
2033
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2034
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2035
-                        array(
2036
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2037
-                                '!=',
2038
-                                $ignore_this_model_obj->ID(),
2039
-                            ),
2040
-                        ),
2041
-                    ));
2042
-                } else {
2043
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2044
-                }
2045
-                if ($related_model_objects) {
2046
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2047
-                    $is_blocked = true;
2048
-                }
2049
-            }
2050
-        }
2051
-        return $is_blocked;
2052
-    }
2053
-
2054
-
2055
-    /**
2056
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2057
-     * @param array $row_results_for_deleting
2058
-     * @param bool  $allow_blocking
2059
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2060
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2061
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2062
-     *                 deleted. Example:
2063
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2064
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2065
-     *                 where each element is a group of columns and values that get deleted. Example:
2066
-     *                      array(
2067
-     *                          0 => array(
2068
-     *                              'Term_Relationship.object_id' => 1
2069
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2070
-     *                          ),
2071
-     *                          1 => array(
2072
-     *                              'Term_Relationship.object_id' => 1
2073
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2074
-     *                          )
2075
-     *                      )
2076
-     * @throws EE_Error
2077
-     */
2078
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2079
-    {
2080
-        $ids_to_delete_indexed_by_column = array();
2081
-        if ($this->has_primary_key_field()) {
2082
-            $primary_table = $this->_get_main_table();
2083
-            $other_tables = $this->_get_other_tables();
2084
-            $ids_to_delete_indexed_by_column = $query = array();
2085
-            foreach ($row_results_for_deleting as $item_to_delete) {
2086
-                //before we mark this item for deletion,
2087
-                //make sure there's no related entities blocking its deletion (if we're checking)
2088
-                if (
2089
-                    $allow_blocking
2090
-                    && $this->delete_is_blocked_by_related_models(
2091
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2092
-                    )
2093
-                ) {
2094
-                    continue;
2095
-                }
2096
-                //primary table deletes
2097
-                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2098
-                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2099
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2100
-                }
2101
-            }
2102
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2103
-            $fields = $this->get_combined_primary_key_fields();
2104
-            foreach ($row_results_for_deleting as $item_to_delete) {
2105
-                $ids_to_delete_indexed_by_column_for_row = array();
2106
-                foreach ($fields as $cpk_field) {
2107
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2108
-                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2109
-                            $item_to_delete[$cpk_field->get_qualified_column()];
2110
-                    }
2111
-                }
2112
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2113
-            }
2114
-        } else {
2115
-            //so there's no primary key and no combined key...
2116
-            //sorry, can't help you
2117
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2118
-                "event_espresso"), get_class($this)));
2119
-        }
2120
-        return $ids_to_delete_indexed_by_column;
2121
-    }
2122
-
2123
-
2124
-    /**
2125
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2126
-     * the corresponding query_part for the query performing the delete.
2127
-     *
2128
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2129
-     * @return string
2130
-     * @throws EE_Error
2131
-     */
2132
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2133
-        $query_part = '';
2134
-        if (empty($ids_to_delete_indexed_by_column)) {
2135
-            return $query_part;
2136
-        } elseif ($this->has_primary_key_field()) {
2137
-            $query = array();
2138
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2139
-                //make sure we have unique $ids
2140
-                $ids = array_unique($ids);
2141
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2142
-            }
2143
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2144
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2145
-            $ways_to_identify_a_row = array();
2146
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2147
-                $values_for_each_combined_primary_key_for_a_row = array();
2148
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2149
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2150
-                }
2151
-                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2152
-            }
2153
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2154
-        }
2155
-        return $query_part;
2156
-    }
31
+	//admin posty
32
+	//basic -> grants access to mine -> if they don't have it, select none
33
+	//*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
+	//*_published -> grants access to published -> if they dont have it, select non-published
36
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
38
+	//frontend posty
39
+	//by default has access to published
40
+	//basic -> grants access to mine that aren't published, and all published
41
+	//*_others ->grants access to others that aren't private, all mine
42
+	//*_private -> grants full access
43
+	//frontend non-posty
44
+	//like admin posty
45
+	//category-y
46
+	//assign -> grants access to join-table
47
+	//(delete, edit)
48
+	//payment-method-y
49
+	//for each registered payment method,
50
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
+	/**
52
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
55
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
+	 *
57
+	 * @var boolean
58
+	 */
59
+	private $_values_already_prepared_by_model_object = 0;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the data is just like form input that needs to have the model fields'
64
+	 * prepare_for_set and prepare_for_use_in_db called on it
65
+	 */
66
+	const not_prepared_by_model_object = 0;
67
+
68
+	/**
69
+	 * when $_values_already_prepared_by_model_object equals this, we
70
+	 * assume this value is coming from a model object and doesn't need to have
71
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
72
+	 */
73
+	const prepared_by_model_object = 1;
74
+
75
+	/**
76
+	 * when $_values_already_prepared_by_model_object equals this, we assume
77
+	 * the values are already to be used in the database (ie no processing is done
78
+	 * on them by the model's fields)
79
+	 */
80
+	const prepared_for_use_in_db = 2;
81
+
82
+
83
+	protected $singular_item = 'Item';
84
+
85
+	protected $plural_item   = 'Items';
86
+
87
+	/**
88
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
+	 */
90
+	protected $_tables;
91
+
92
+	/**
93
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
+	 *
97
+	 * @var \EE_Model_Field_Base[] $_fields
98
+	 */
99
+	protected $_fields;
100
+
101
+	/**
102
+	 * array of different kinds of relations
103
+	 *
104
+	 * @var \EE_Model_Relation_Base[] $_model_relations
105
+	 */
106
+	protected $_model_relations;
107
+
108
+	/**
109
+	 * @var \EE_Index[] $_indexes
110
+	 */
111
+	protected $_indexes = array();
112
+
113
+	/**
114
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
115
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
+	 * by setting the same columns as used in these queries in the query yourself.
117
+	 *
118
+	 * @var EE_Default_Where_Conditions
119
+	 */
120
+	protected $_default_where_conditions_strategy;
121
+
122
+	/**
123
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
+	 * This is particularly useful when you want something between 'none' and 'default'
125
+	 *
126
+	 * @var EE_Default_Where_Conditions
127
+	 */
128
+	protected $_minimum_where_conditions_strategy;
129
+
130
+	/**
131
+	 * String describing how to find the "owner" of this model's objects.
132
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
+	 * But when there isn't, this indicates which related model, or transiently-related model,
134
+	 * has the foreign key to the wp_users table.
135
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
+	 * related to events, and events have a foreign key to wp_users.
137
+	 * On EEM_Transaction, this would be 'Transaction.Event'
138
+	 *
139
+	 * @var string
140
+	 */
141
+	protected $_model_chain_to_wp_user = '';
142
+
143
+	/**
144
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
+	 * don't need it (particularly CPT models)
146
+	 *
147
+	 * @var bool
148
+	 */
149
+	protected $_ignore_where_strategy = false;
150
+
151
+	/**
152
+	 * String used in caps relating to this model. Eg, if the caps relating to this
153
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
+	 *
155
+	 * @var string. If null it hasn't been initialized yet. If false then we
156
+	 * have indicated capabilities don't apply to this
157
+	 */
158
+	protected $_caps_slug = null;
159
+
160
+	/**
161
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
+	 * and next-level keys are capability names, and each's value is a
163
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
165
+	 * and then each capability in the corresponding sub-array that they're missing
166
+	 * adds the where conditions onto the query.
167
+	 *
168
+	 * @var array
169
+	 */
170
+	protected $_cap_restrictions = array(
171
+		self::caps_read       => array(),
172
+		self::caps_read_admin => array(),
173
+		self::caps_edit       => array(),
174
+		self::caps_delete     => array(),
175
+	);
176
+
177
+	/**
178
+	 * Array defining which cap restriction generators to use to create default
179
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
180
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
+	 * automatically set this to false (not just null).
183
+	 *
184
+	 * @var EE_Restriction_Generator_Base[]
185
+	 */
186
+	protected $_cap_restriction_generators = array();
187
+
188
+	/**
189
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
+	 */
191
+	const caps_read       = 'read';
192
+
193
+	const caps_read_admin = 'read_admin';
194
+
195
+	const caps_edit       = 'edit';
196
+
197
+	const caps_delete     = 'delete';
198
+
199
+	/**
200
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
+	 * maps to 'read' because when looking for relevant permissions we're going to use
203
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
204
+	 *
205
+	 * @var array
206
+	 */
207
+	protected $_cap_contexts_to_cap_action_map = array(
208
+		self::caps_read       => 'read',
209
+		self::caps_read_admin => 'read',
210
+		self::caps_edit       => 'edit',
211
+		self::caps_delete     => 'delete',
212
+	);
213
+
214
+	/**
215
+	 * Timezone
216
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
+	 * EE_Datetime_Field data type will have access to it.
220
+	 *
221
+	 * @var string
222
+	 */
223
+	protected $_timezone;
224
+
225
+
226
+	/**
227
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
+	 * multisite.
229
+	 *
230
+	 * @var int
231
+	 */
232
+	protected static $_model_query_blog_id;
233
+
234
+	/**
235
+	 * A copy of _fields, except the array keys are the model names pointed to by
236
+	 * the field
237
+	 *
238
+	 * @var EE_Model_Field_Base[]
239
+	 */
240
+	private $_cache_foreign_key_to_fields = array();
241
+
242
+	/**
243
+	 * Cached list of all the fields on the model, indexed by their name
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cached_fields = null;
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, except those that are
251
+	 * marked as only pertinent to the database
252
+	 *
253
+	 * @var EE_Model_Field_Base[]
254
+	 */
255
+	private $_cached_fields_non_db_only = null;
256
+
257
+	/**
258
+	 * A cached reference to the primary key for quick lookup
259
+	 *
260
+	 * @var EE_Model_Field_Base
261
+	 */
262
+	private $_primary_key_field = null;
263
+
264
+	/**
265
+	 * Flag indicating whether this model has a primary key or not
266
+	 *
267
+	 * @var boolean
268
+	 */
269
+	protected $_has_primary_key_field = null;
270
+
271
+	/**
272
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
273
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
+	 *
275
+	 * @var boolean
276
+	 */
277
+	protected $_wp_core_model = false;
278
+
279
+	/**
280
+	 *    List of valid operators that can be used for querying.
281
+	 * The keys are all operators we'll accept, the values are the real SQL
282
+	 * operators used
283
+	 *
284
+	 * @var array
285
+	 */
286
+	protected $_valid_operators = array(
287
+		'='           => '=',
288
+		'<='          => '<=',
289
+		'<'           => '<',
290
+		'>='          => '>=',
291
+		'>'           => '>',
292
+		'!='          => '!=',
293
+		'LIKE'        => 'LIKE',
294
+		'like'        => 'LIKE',
295
+		'NOT_LIKE'    => 'NOT LIKE',
296
+		'not_like'    => 'NOT LIKE',
297
+		'NOT LIKE'    => 'NOT LIKE',
298
+		'not like'    => 'NOT LIKE',
299
+		'IN'          => 'IN',
300
+		'in'          => 'IN',
301
+		'NOT_IN'      => 'NOT IN',
302
+		'not_in'      => 'NOT IN',
303
+		'NOT IN'      => 'NOT IN',
304
+		'not in'      => 'NOT IN',
305
+		'between'     => 'BETWEEN',
306
+		'BETWEEN'     => 'BETWEEN',
307
+		'IS_NOT_NULL' => 'IS NOT NULL',
308
+		'is_not_null' => 'IS NOT NULL',
309
+		'IS NOT NULL' => 'IS NOT NULL',
310
+		'is not null' => 'IS NOT NULL',
311
+		'IS_NULL'     => 'IS NULL',
312
+		'is_null'     => 'IS NULL',
313
+		'IS NULL'     => 'IS NULL',
314
+		'is null'     => 'IS NULL',
315
+		'REGEXP'      => 'REGEXP',
316
+		'regexp'      => 'REGEXP',
317
+		'NOT_REGEXP'  => 'NOT REGEXP',
318
+		'not_regexp'  => 'NOT REGEXP',
319
+		'NOT REGEXP'  => 'NOT REGEXP',
320
+		'not regexp'  => 'NOT REGEXP',
321
+	);
322
+
323
+	/**
324
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
+	 *
326
+	 * @var array
327
+	 */
328
+	protected $_in_style_operators = array('IN', 'NOT IN');
329
+
330
+	/**
331
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
+	 * '12-31-2012'"
333
+	 *
334
+	 * @var array
335
+	 */
336
+	protected $_between_style_operators = array('BETWEEN');
337
+
338
+	/**
339
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
+	 * on a join table.
341
+	 *
342
+	 * @var array
343
+	 */
344
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
+
346
+	/**
347
+	 * Allowed values for $query_params['order'] for ordering in queries
348
+	 *
349
+	 * @var array
350
+	 */
351
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
+
353
+	/**
354
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
356
+	 *
357
+	 * @var array
358
+	 */
359
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
+
361
+	/**
362
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
364
+	 *
365
+	 * @var array
366
+	 */
367
+	private $_allowed_query_params = array(
368
+		0,
369
+		'limit',
370
+		'order_by',
371
+		'group_by',
372
+		'having',
373
+		'force_join',
374
+		'order',
375
+		'on_join_limit',
376
+		'default_where_conditions',
377
+		'caps',
378
+	);
379
+
380
+	/**
381
+	 * All the data types that can be used in $wpdb->prepare statements.
382
+	 *
383
+	 * @var array
384
+	 */
385
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
+
387
+	/**
388
+	 *    EE_Registry Object
389
+	 *
390
+	 * @var    object
391
+	 * @access    protected
392
+	 */
393
+	protected $EE = null;
394
+
395
+
396
+	/**
397
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
+	 *
399
+	 * @var int
400
+	 */
401
+	protected $_show_next_x_db_queries = 0;
402
+
403
+	/**
404
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
+	 *
407
+	 * @var array
408
+	 */
409
+	protected $_custom_selections = array();
410
+
411
+	/**
412
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
+	 * caches every model object we've fetched from the DB on this request
414
+	 *
415
+	 * @var array
416
+	 */
417
+	protected $_entity_map;
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 = 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 = 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 = 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
+	 * Generates the cap restrictions for the given context, or if they were
654
+	 * already generated just gets what's cached
655
+	 *
656
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
657
+	 * @return EE_Default_Where_Conditions[]
658
+	 */
659
+	protected function _generate_cap_restrictions($context)
660
+	{
661
+		if (isset($this->_cap_restriction_generators[$context])
662
+			&& $this->_cap_restriction_generators[$context]
663
+			   instanceof
664
+			   EE_Restriction_Generator_Base
665
+		) {
666
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
+		} else {
668
+			return array();
669
+		}
670
+	}
671
+
672
+
673
+
674
+	/**
675
+	 * Used to set the $_model_query_blog_id static property.
676
+	 *
677
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
+	 *                      value for get_current_blog_id() will be used.
679
+	 */
680
+	public static function set_model_query_blog_id($blog_id = 0)
681
+	{
682
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
+	}
684
+
685
+
686
+
687
+	/**
688
+	 * Returns whatever is set as the internal $model_query_blog_id.
689
+	 *
690
+	 * @return int
691
+	 */
692
+	public static function get_model_query_blog_id()
693
+	{
694
+		return EEM_Base::$_model_query_blog_id;
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 *        This function is a singleton method used to instantiate the Espresso_model object
701
+	 *
702
+	 * @access public
703
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
+	 *                         timezone in the 'timezone_string' wp option)
707
+	 * @return static (as in the concrete child class)
708
+	 */
709
+	public static function instance($timezone = null)
710
+	{
711
+		// check if instance of Espresso_model already exists
712
+		if (! static::$_instance instanceof static) {
713
+			// instantiate Espresso_model
714
+			static::$_instance = new static($timezone);
715
+		}
716
+		//we might have a timezone set, let set_timezone decide what to do with it
717
+		static::$_instance->set_timezone($timezone);
718
+		// Espresso_model object
719
+		return static::$_instance;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * resets the model and returns it
726
+	 *
727
+	 * @param null | string $timezone
728
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
+	 * all its properties reset; if it wasn't instantiated, returns null)
730
+	 */
731
+	public static function reset($timezone = null)
732
+	{
733
+		if (static::$_instance instanceof EEM_Base) {
734
+			//let's try to NOT swap out the current instance for a new one
735
+			//because if someone has a reference to it, we can't remove their reference
736
+			//so it's best to keep using the same reference, but change the original object
737
+			//reset all its properties to their original values as defined in the class
738
+			$r = new ReflectionClass(get_class(static::$_instance));
739
+			$static_properties = $r->getStaticProperties();
740
+			foreach ($r->getDefaultProperties() as $property => $value) {
741
+				//don't set instance to null like it was originally,
742
+				//but it's static anyways, and we're ignoring static properties (for now at least)
743
+				if (! isset($static_properties[$property])) {
744
+					static::$_instance->{$property} = $value;
745
+				}
746
+			}
747
+			//and then directly call its constructor again, like we would if we
748
+			//were creating a new one
749
+			static::$_instance->__construct($timezone);
750
+			return self::instance();
751
+		}
752
+		return null;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
+	 *
760
+	 * @param  boolean $translated return localized strings or JUST the array.
761
+	 * @return array
762
+	 * @throws \EE_Error
763
+	 */
764
+	public function status_array($translated = false)
765
+	{
766
+		if (! array_key_exists('Status', $this->_model_relations)) {
767
+			return array();
768
+		}
769
+		$model_name = $this->get_this_model_name();
770
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
+		$status_array = array();
773
+		foreach ($stati as $status) {
774
+			$status_array[$status->ID()] = $status->get('STS_code');
775
+		}
776
+		return $translated
777
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
+			: $status_array;
779
+	}
780
+
781
+
782
+
783
+	/**
784
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
+	 *
786
+	 * @param array $query_params             {
787
+	 * @var array $0 (where) array {
788
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
+	 *                                        conditions based on related models (and even
792
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
793
+	 *                                        name. Eg,
794
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
+	 *                                        to Venues (even when each of those models actually consisted of two
802
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
803
+	 *                                        just having
804
+	 *                                        "Venue.VNU_ID", you could have
805
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
+	 *                                        events are related to Registrations, which are related to Attendees). You
807
+	 *                                        can take it even further with
808
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
+	 *                                        (from the default of '='), change the value to an numerically-indexed
810
+	 *                                        array, where the first item in the list is the operator. eg: array(
811
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
819
+	 *                                        the value is a field, simply provide a third array item (true) to the
820
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
+	 *                                        Note: you can also use related model field names like you would any other
823
+	 *                                        field name. eg:
824
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
+	 *                                        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__>' =>
826
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
833
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
+	 *                                        "stick" until you specify an AND. eg
835
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
+	 *                                        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 >>
840
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
+	 *                                        too, eg:
843
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
848
+	 *                                        the OFFSET, the 2nd is the LIMIT
849
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
+	 *                                        following format array('on_join_limit'
852
+	 *                                        => array( 'table_alias', array(1,2) ) ).
853
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
+	 *                                        values are either 'ASC' or 'DESC'.
855
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
+	 *                                        DESC..." respectively. Like the
858
+	 *                                        'where' conditions, these fields can be on related models. Eg
859
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
861
+	 *                                        Attendee, Price, Datetime, etc.)
862
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
864
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
+	 *                                        order by the primary key. Eg,
867
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
869
+	 *                                        DTT_EVT_start) or
870
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
+	 *                                        'group_by'=>'VNU_ID', or
874
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
+	 *                                        if no
876
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
877
+	 *                                        model's primary key (or combined primary keys). This avoids some
878
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
879
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
+	 *                                        results)
883
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
+	 *                                        array where values are models to be joined in the query.Eg
885
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
887
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
888
+	 *                                        related models which belongs to the current model
889
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
890
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
891
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
894
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
896
+	 *                                        this model's default where conditions added to the query, use
897
+	 *                                        'this_model_only'. If you want to use all default where conditions
898
+	 *                                        (default), set to 'all'.
899
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
+	 *                                        everything? Or should we only show the current user items they should be
902
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
+	 *                                        }
905
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
+	 *                                        array( array(
911
+	 *                                        'OR'=>array(
912
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
+	 *                                        )
915
+	 *                                        ),
916
+	 *                                        'limit'=>10,
917
+	 *                                        'group_by'=>'TXN_ID'
918
+	 *                                        ));
919
+	 *                                        get all the answers to the question titled "shirt size" for event with id
920
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
+	 *                                        'Question.QST_display_text'=>'shirt size',
922
+	 *                                        'Registration.Event.EVT_ID'=>12
923
+	 *                                        ),
924
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
925
+	 *                                        ));
926
+	 * @throws \EE_Error
927
+	 */
928
+	public function get_all($query_params = array())
929
+	{
930
+		if (isset($query_params['limit'])
931
+			&& ! isset($query_params['group_by'])
932
+		) {
933
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
+		}
935
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
+	}
937
+
938
+
939
+
940
+	/**
941
+	 * Modifies the query parameters so we only get back model objects
942
+	 * that "belong" to the current user
943
+	 *
944
+	 * @param array $query_params @see EEM_Base::get_all()
945
+	 * @return array like EEM_Base::get_all
946
+	 */
947
+	public function alter_query_params_to_only_include_mine($query_params = array())
948
+	{
949
+		$wp_user_field_name = $this->wp_user_field_name();
950
+		if ($wp_user_field_name) {
951
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
952
+		}
953
+		return $query_params;
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * Returns the name of the field's name that points to the WP_User table
960
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
+	 * foreign key to the WP_User table)
962
+	 *
963
+	 * @return string|boolean string on success, boolean false when there is no
964
+	 * foreign key to the WP_User table
965
+	 */
966
+	public function wp_user_field_name()
967
+	{
968
+		try {
969
+			if (! empty($this->_model_chain_to_wp_user)) {
970
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
+				$last_model_name = end($models_to_follow_to_wp_users);
972
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
+			} else {
975
+				$model_with_fk_to_wp_users = $this;
976
+				$model_chain_to_wp_user = '';
977
+			}
978
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
980
+		} catch (EE_Error $e) {
981
+			return false;
982
+		}
983
+	}
984
+
985
+
986
+
987
+	/**
988
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
989
+	 * (or transiently-related model) has a foreign key to the wp_users table;
990
+	 * useful for finding if model objects of this type are 'owned' by the current user.
991
+	 * This is an empty string when the foreign key is on this model and when it isn't,
992
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
993
+	 * (or transiently-related model)
994
+	 *
995
+	 * @return string
996
+	 */
997
+	public function model_chain_to_wp_user()
998
+	{
999
+		return $this->_model_chain_to_wp_user;
1000
+	}
1001
+
1002
+
1003
+
1004
+	/**
1005
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
+	 * like how registrations don't have a foreign key to wp_users, but the
1007
+	 * events they are for are), or is unrelated to wp users.
1008
+	 * generally available
1009
+	 *
1010
+	 * @return boolean
1011
+	 */
1012
+	public function is_owned()
1013
+	{
1014
+		if ($this->model_chain_to_wp_user()) {
1015
+			return true;
1016
+		} else {
1017
+			try {
1018
+				$this->get_foreign_key_to('WP_User');
1019
+				return true;
1020
+			} catch (EE_Error $e) {
1021
+				return false;
1022
+			}
1023
+		}
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
+	 * the model)
1032
+	 *
1033
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1037
+	 *                                  override this and set the select to "*", or a specific column name, like
1038
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
+	 *                                  the aliases used to refer to this selection, and values are to be
1041
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
+	 * @throws \EE_Error
1045
+	 */
1046
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
+	{
1048
+		// remember the custom selections, if any, and type cast as array
1049
+		// (unless $columns_to_select is an object, then just set as an empty array)
1050
+		// Note: (array) 'some string' === array( 'some string' )
1051
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
+		$select_expressions = $columns_to_select !== null
1054
+			? $this->_construct_select_from_input($columns_to_select)
1055
+			: $this->_construct_default_select_sql($model_query_info);
1056
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
+	}
1059
+
1060
+
1061
+
1062
+	/**
1063
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1064
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
+	 * take care of joins, field preparation etc.
1066
+	 *
1067
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1071
+	 *                                  override this and set the select to "*", or a specific column name, like
1072
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
+	 *                                  the aliases used to refer to this selection, and values are to be
1075
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
+	 * @throws \EE_Error
1079
+	 */
1080
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
+	{
1082
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
+	}
1084
+
1085
+
1086
+
1087
+	/**
1088
+	 * For creating a custom select statement
1089
+	 *
1090
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
+	 *                                 SQL, and 1=>is the datatype
1093
+	 * @throws EE_Error
1094
+	 * @return string
1095
+	 */
1096
+	private function _construct_select_from_input($columns_to_select)
1097
+	{
1098
+		if (is_array($columns_to_select)) {
1099
+			$select_sql_array = array();
1100
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
+					throw new EE_Error(
1103
+						sprintf(
1104
+							__(
1105
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
+								"event_espresso"
1107
+							),
1108
+							$selection_and_datatype,
1109
+							$alias
1110
+						)
1111
+					);
1112
+				}
1113
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
+					throw new EE_Error(
1115
+						sprintf(
1116
+							__(
1117
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
+								"event_espresso"
1119
+							),
1120
+							$selection_and_datatype[1],
1121
+							$selection_and_datatype[0],
1122
+							$alias,
1123
+							implode(",", $this->_valid_wpdb_data_types)
1124
+						)
1125
+					);
1126
+				}
1127
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
+			}
1129
+			$columns_to_select_string = implode(", ", $select_sql_array);
1130
+		} else {
1131
+			$columns_to_select_string = $columns_to_select;
1132
+		}
1133
+		return $columns_to_select_string;
1134
+	}
1135
+
1136
+
1137
+
1138
+	/**
1139
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
+	 *
1141
+	 * @return string
1142
+	 * @throws \EE_Error
1143
+	 */
1144
+	public function primary_key_name()
1145
+	{
1146
+		return $this->get_primary_key_field()->get_name();
1147
+	}
1148
+
1149
+
1150
+
1151
+	/**
1152
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
+	 * If there is no primary key on this model, $id is treated as primary key string
1154
+	 *
1155
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1156
+	 * @return EE_Base_Class
1157
+	 */
1158
+	public function get_one_by_ID($id)
1159
+	{
1160
+		if ($this->get_from_entity_map($id)) {
1161
+			return $this->get_from_entity_map($id);
1162
+		}
1163
+		return $this->get_one(
1164
+			$this->alter_query_params_to_restrict_by_ID(
1165
+				$id,
1166
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
+			)
1168
+		);
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Alters query parameters to only get items with this ID are returned.
1175
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
+	 * or could just be a simple primary key ID
1177
+	 *
1178
+	 * @param int   $id
1179
+	 * @param array $query_params
1180
+	 * @return array of normal query params, @see EEM_Base::get_all
1181
+	 * @throws \EE_Error
1182
+	 */
1183
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
+	{
1185
+		if (! isset($query_params[0])) {
1186
+			$query_params[0] = array();
1187
+		}
1188
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1189
+		if ($conditions_from_id === null) {
1190
+			$query_params[0][$this->primary_key_name()] = $id;
1191
+		} else {
1192
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1193
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
+		}
1195
+		return $query_params;
1196
+	}
1197
+
1198
+
1199
+
1200
+	/**
1201
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
+	 * array. If no item is found, null is returned.
1203
+	 *
1204
+	 * @param array $query_params like EEM_Base's $query_params variable.
1205
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
+	 * @throws \EE_Error
1207
+	 */
1208
+	public function get_one($query_params = array())
1209
+	{
1210
+		if (! is_array($query_params)) {
1211
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
+					gettype($query_params)), '4.6.0');
1214
+			$query_params = array();
1215
+		}
1216
+		$query_params['limit'] = 1;
1217
+		$items = $this->get_all($query_params);
1218
+		if (empty($items)) {
1219
+			return null;
1220
+		} else {
1221
+			return array_shift($items);
1222
+		}
1223
+	}
1224
+
1225
+
1226
+
1227
+	/**
1228
+	 * Returns the next x number of items in sequence from the given value as
1229
+	 * found in the database matching the given query conditions.
1230
+	 *
1231
+	 * @param mixed $current_field_value    Value used for the reference point.
1232
+	 * @param null  $field_to_order_by      What field is used for the
1233
+	 *                                      reference point.
1234
+	 * @param int   $limit                  How many to return.
1235
+	 * @param array $query_params           Extra conditions on the query.
1236
+	 * @param null  $columns_to_select      If left null, then an array of
1237
+	 *                                      EE_Base_Class objects is returned,
1238
+	 *                                      otherwise you can indicate just the
1239
+	 *                                      columns you want returned.
1240
+	 * @return EE_Base_Class[]|array
1241
+	 * @throws \EE_Error
1242
+	 */
1243
+	public function next_x(
1244
+		$current_field_value,
1245
+		$field_to_order_by = null,
1246
+		$limit = 1,
1247
+		$query_params = array(),
1248
+		$columns_to_select = null
1249
+	) {
1250
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
+			$columns_to_select);
1252
+	}
1253
+
1254
+
1255
+
1256
+	/**
1257
+	 * Returns the previous x number of items in sequence from the given value
1258
+	 * as found in the database matching the given query conditions.
1259
+	 *
1260
+	 * @param mixed $current_field_value    Value used for the reference point.
1261
+	 * @param null  $field_to_order_by      What field is used for the
1262
+	 *                                      reference point.
1263
+	 * @param int   $limit                  How many to return.
1264
+	 * @param array $query_params           Extra conditions on the query.
1265
+	 * @param null  $columns_to_select      If left null, then an array of
1266
+	 *                                      EE_Base_Class objects is returned,
1267
+	 *                                      otherwise you can indicate just the
1268
+	 *                                      columns you want returned.
1269
+	 * @return EE_Base_Class[]|array
1270
+	 * @throws \EE_Error
1271
+	 */
1272
+	public function previous_x(
1273
+		$current_field_value,
1274
+		$field_to_order_by = null,
1275
+		$limit = 1,
1276
+		$query_params = array(),
1277
+		$columns_to_select = null
1278
+	) {
1279
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
+			$columns_to_select);
1281
+	}
1282
+
1283
+
1284
+
1285
+	/**
1286
+	 * Returns the next item in sequence from the given value as found in the
1287
+	 * database matching the given query conditions.
1288
+	 *
1289
+	 * @param mixed $current_field_value    Value used for the reference point.
1290
+	 * @param null  $field_to_order_by      What field is used for the
1291
+	 *                                      reference point.
1292
+	 * @param array $query_params           Extra conditions on the query.
1293
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
+	 *                                      object is returned, otherwise you
1295
+	 *                                      can indicate just the columns you
1296
+	 *                                      want and a single array indexed by
1297
+	 *                                      the columns will be returned.
1298
+	 * @return EE_Base_Class|null|array()
1299
+	 * @throws \EE_Error
1300
+	 */
1301
+	public function next(
1302
+		$current_field_value,
1303
+		$field_to_order_by = null,
1304
+		$query_params = array(),
1305
+		$columns_to_select = null
1306
+	) {
1307
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
+			$columns_to_select);
1309
+		return empty($results) ? null : reset($results);
1310
+	}
1311
+
1312
+
1313
+
1314
+	/**
1315
+	 * Returns the previous item in sequence from the given value as found in
1316
+	 * the database matching the given query conditions.
1317
+	 *
1318
+	 * @param mixed $current_field_value    Value used for the reference point.
1319
+	 * @param null  $field_to_order_by      What field is used for the
1320
+	 *                                      reference point.
1321
+	 * @param array $query_params           Extra conditions on the query.
1322
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
+	 *                                      object is returned, otherwise you
1324
+	 *                                      can indicate just the columns you
1325
+	 *                                      want and a single array indexed by
1326
+	 *                                      the columns will be returned.
1327
+	 * @return EE_Base_Class|null|array()
1328
+	 * @throws EE_Error
1329
+	 */
1330
+	public function previous(
1331
+		$current_field_value,
1332
+		$field_to_order_by = null,
1333
+		$query_params = array(),
1334
+		$columns_to_select = null
1335
+	) {
1336
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
+			$columns_to_select);
1338
+		return empty($results) ? null : reset($results);
1339
+	}
1340
+
1341
+
1342
+
1343
+	/**
1344
+	 * Returns the a consecutive number of items in sequence from the given
1345
+	 * value as found in the database matching the given query conditions.
1346
+	 *
1347
+	 * @param mixed  $current_field_value   Value used for the reference point.
1348
+	 * @param string $operand               What operand is used for the sequence.
1349
+	 * @param string $field_to_order_by     What field is used for the reference point.
1350
+	 * @param int    $limit                 How many to return.
1351
+	 * @param array  $query_params          Extra conditions on the query.
1352
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
+	 *                                      otherwise you can indicate just the columns you want returned.
1354
+	 * @return EE_Base_Class[]|array
1355
+	 * @throws EE_Error
1356
+	 */
1357
+	protected function _get_consecutive(
1358
+		$current_field_value,
1359
+		$operand = '>',
1360
+		$field_to_order_by = null,
1361
+		$limit = 1,
1362
+		$query_params = array(),
1363
+		$columns_to_select = null
1364
+	) {
1365
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
+		if (empty($field_to_order_by)) {
1367
+			if ($this->has_primary_key_field()) {
1368
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1369
+			} else {
1370
+				if (WP_DEBUG) {
1371
+					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).',
1372
+						'event_espresso'));
1373
+				}
1374
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
+				return array();
1376
+			}
1377
+		}
1378
+		if (! is_array($query_params)) {
1379
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
+					gettype($query_params)), '4.6.0');
1382
+			$query_params = array();
1383
+		}
1384
+		//let's add the where query param for consecutive look up.
1385
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
+		$query_params['limit'] = $limit;
1387
+		//set direction
1388
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
+		$query_params['order_by'] = $operand === '>'
1390
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
+		if (empty($columns_to_select)) {
1394
+			return $this->get_all($query_params);
1395
+		} else {
1396
+			//getting just the fields
1397
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
+		}
1399
+	}
1400
+
1401
+
1402
+
1403
+	/**
1404
+	 * This sets the _timezone property after model object has been instantiated.
1405
+	 *
1406
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
+	 */
1408
+	public function set_timezone($timezone)
1409
+	{
1410
+		if ($timezone !== null) {
1411
+			$this->_timezone = $timezone;
1412
+		}
1413
+		//note we need to loop through relations and set the timezone on those objects as well.
1414
+		foreach ($this->_model_relations as $relation) {
1415
+			$relation->set_timezone($timezone);
1416
+		}
1417
+		//and finally we do the same for any datetime fields
1418
+		foreach ($this->_fields as $field) {
1419
+			if ($field instanceof EE_Datetime_Field) {
1420
+				$field->set_timezone($timezone);
1421
+			}
1422
+		}
1423
+	}
1424
+
1425
+
1426
+
1427
+	/**
1428
+	 * This just returns whatever is set for the current timezone.
1429
+	 *
1430
+	 * @access public
1431
+	 * @return string
1432
+	 */
1433
+	public function get_timezone()
1434
+	{
1435
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
+		if (empty($this->_timezone)) {
1437
+			foreach ($this->_fields as $field) {
1438
+				if ($field instanceof EE_Datetime_Field) {
1439
+					$this->set_timezone($field->get_timezone());
1440
+					break;
1441
+				}
1442
+			}
1443
+		}
1444
+		//if timezone STILL empty then return the default timezone for the site.
1445
+		if (empty($this->_timezone)) {
1446
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
+		}
1448
+		return $this->_timezone;
1449
+	}
1450
+
1451
+
1452
+
1453
+	/**
1454
+	 * This returns the date formats set for the given field name and also ensures that
1455
+	 * $this->_timezone property is set correctly.
1456
+	 *
1457
+	 * @since 4.6.x
1458
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1459
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
+	 * @return array formats in an array with the date format first, and the time format last.
1462
+	 */
1463
+	public function get_formats_for($field_name, $pretty = false)
1464
+	{
1465
+		$field_settings = $this->field_settings_for($field_name);
1466
+		//if not a valid EE_Datetime_Field then throw error
1467
+		if (! $field_settings instanceof EE_Datetime_Field) {
1468
+			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.',
1469
+				'event_espresso'), $field_name));
1470
+		}
1471
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
+		//the field.
1473
+		$this->_timezone = $field_settings->get_timezone();
1474
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
+	}
1476
+
1477
+
1478
+
1479
+	/**
1480
+	 * This returns the current time in a format setup for a query on this model.
1481
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
+	 * it will return:
1483
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
+	 *  NOW
1485
+	 *  - or a unix timestamp (equivalent to time())
1486
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1487
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1488
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1489
+	 * @since 4.6.x
1490
+	 * @param string $field_name       The field the current time is needed for.
1491
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1492
+	 *                                 formatted string matching the set format for the field in the set timezone will
1493
+	 *                                 be returned.
1494
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1495
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1496
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497
+	 *                                 exception is triggered.
1498
+	 */
1499
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1500
+	{
1501
+		$formats = $this->get_formats_for($field_name);
1502
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1503
+		if ($timestamp) {
1504
+			return $DateTime->format('U');
1505
+		}
1506
+		//not returning timestamp, so return formatted string in timezone.
1507
+		switch ($what) {
1508
+			case 'time' :
1509
+				return $DateTime->format($formats[1]);
1510
+				break;
1511
+			case 'date' :
1512
+				return $DateTime->format($formats[0]);
1513
+				break;
1514
+			default :
1515
+				return $DateTime->format(implode(' ', $formats));
1516
+				break;
1517
+		}
1518
+	}
1519
+
1520
+
1521
+
1522
+	/**
1523
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1524
+	 * for the model are.  Returns a DateTime object.
1525
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1526
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1527
+	 * ignored.
1528
+	 *
1529
+	 * @param string $field_name      The field being setup.
1530
+	 * @param string $timestring      The date time string being used.
1531
+	 * @param string $incoming_format The format for the time string.
1532
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1533
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1534
+	 *                                format is
1535
+	 *                                'U', this is ignored.
1536
+	 * @return DateTime
1537
+	 * @throws \EE_Error
1538
+	 */
1539
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1540
+	{
1541
+		//just using this to ensure the timezone is set correctly internally
1542
+		$this->get_formats_for($field_name);
1543
+		//load EEH_DTT_Helper
1544
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1547
+	}
1548
+
1549
+
1550
+
1551
+	/**
1552
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1553
+	 *
1554
+	 * @return EE_Table_Base[]
1555
+	 */
1556
+	public function get_tables()
1557
+	{
1558
+		return $this->_tables;
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1565
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1566
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1567
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1568
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1569
+	 * model object with EVT_ID = 1
1570
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1571
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1572
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1573
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1574
+	 * are not specified)
1575
+	 *
1576
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1577
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1578
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1579
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1580
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1581
+	 *                                         ID=34, we'd use this method as follows:
1582
+	 *                                         EEM_Transaction::instance()->update(
1583
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1584
+	 *                                         array(array('TXN_ID'=>34)));
1585
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1586
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1587
+	 *                                         consider updating Question's QST_admin_label field is of type
1588
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1589
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1590
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1591
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1592
+	 *                                         TRUE, it is assumed that you've already called
1593
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1594
+	 *                                         malicious javascript. However, if
1595
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1596
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1597
+	 *                                         and every other field, before insertion. We provide this parameter
1598
+	 *                                         because model objects perform their prepare_for_set function on all
1599
+	 *                                         their values, and so don't need to be called again (and in many cases,
1600
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1601
+	 *                                         prepare_for_set method...)
1602
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1603
+	 *                                         in this model's entity map according to $fields_n_values that match
1604
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1605
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1606
+	 *                                         could get out-of-sync with the database
1607
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1608
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1609
+	 *                                         bad)
1610
+	 * @throws \EE_Error
1611
+	 */
1612
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613
+	{
1614
+		if (! is_array($query_params)) {
1615
+			EE_Error::doing_it_wrong('EEM_Base::update',
1616
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617
+					gettype($query_params)), '4.6.0');
1618
+			$query_params = array();
1619
+		}
1620
+		/**
1621
+		 * Action called before a model update call has been made.
1622
+		 *
1623
+		 * @param EEM_Base $model
1624
+		 * @param array    $fields_n_values the updated fields and their new values
1625
+		 * @param array    $query_params    @see EEM_Base::get_all()
1626
+		 */
1627
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1628
+		/**
1629
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1630
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1631
+		 *
1632
+		 * @param array    $fields_n_values fields and their new values
1633
+		 * @param EEM_Base $model           the model being queried
1634
+		 * @param array    $query_params    see EEM_Base::get_all()
1635
+		 */
1636
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637
+			$query_params);
1638
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1639
+		//to do that, for each table, verify that it's PK isn't null.
1640
+		$tables = $this->get_tables();
1641
+		//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
1642
+		//NOTE: we should make this code more efficient by NOT querying twice
1643
+		//before the real update, but that needs to first go through ALPHA testing
1644
+		//as it's dangerous. says Mike August 8 2014
1645
+		//we want to make sure the default_where strategy is ignored
1646
+		$this->_ignore_where_strategy = true;
1647
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648
+		foreach ($wpdb_select_results as $wpdb_result) {
1649
+			// type cast stdClass as array
1650
+			$wpdb_result = (array)$wpdb_result;
1651
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652
+			if ($this->has_primary_key_field()) {
1653
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1654
+			} else {
1655
+				//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)
1656
+				$main_table_pk_value = null;
1657
+			}
1658
+			//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
1659
+			//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
1660
+			if (count($tables) > 1) {
1661
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1662
+				//in that table, and so we'll want to insert one
1663
+				foreach ($tables as $table_obj) {
1664
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665
+					//if there is no private key for this table on the results, it means there's no entry
1666
+					//in this table, right? so insert a row in the current table, using any fields available
1667
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1668
+						   && $wpdb_result[$this_table_pk_column])
1669
+					) {
1670
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671
+							$main_table_pk_value);
1672
+						//if we died here, report the error
1673
+						if (! $success) {
1674
+							return false;
1675
+						}
1676
+					}
1677
+				}
1678
+			}
1679
+			//				//and now check that if we have cached any models by that ID on the model, that
1680
+			//				//they also get updated properly
1681
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1682
+			//				if( $model_object ){
1683
+			//					foreach( $fields_n_values as $field => $value ){
1684
+			//						$model_object->set($field, $value);
1685
+			//let's make sure default_where strategy is followed now
1686
+			$this->_ignore_where_strategy = false;
1687
+		}
1688
+		//if we want to keep model objects in sync, AND
1689
+		//if this wasn't called from a model object (to update itself)
1690
+		//then we want to make sure we keep all the existing
1691
+		//model objects in sync with the db
1692
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1693
+			if ($this->has_primary_key_field()) {
1694
+				$model_objs_affected_ids = $this->get_col($query_params);
1695
+			} else {
1696
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1697
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1698
+				$model_objs_affected_ids = array();
1699
+				foreach ($models_affected_key_columns as $row) {
1700
+					$combined_index_key = $this->get_index_primary_key_string($row);
1701
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702
+				}
1703
+			}
1704
+			if (! $model_objs_affected_ids) {
1705
+				//wait wait wait- if nothing was affected let's stop here
1706
+				return 0;
1707
+			}
1708
+			foreach ($model_objs_affected_ids as $id) {
1709
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1710
+				if ($model_obj_in_entity_map) {
1711
+					foreach ($fields_n_values as $field => $new_value) {
1712
+						$model_obj_in_entity_map->set($field, $new_value);
1713
+					}
1714
+				}
1715
+			}
1716
+			//if there is a primary key on this model, we can now do a slight optimization
1717
+			if ($this->has_primary_key_field()) {
1718
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1719
+				$query_params = array(
1720
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1721
+					'limit'                    => count($model_objs_affected_ids),
1722
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1723
+				);
1724
+			}
1725
+		}
1726
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1727
+		$SQL = "UPDATE "
1728
+			   . $model_query_info->get_full_join_sql()
1729
+			   . " SET "
1730
+			   . $this->_construct_update_sql($fields_n_values)
1731
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733
+		/**
1734
+		 * Action called after a model update call has been made.
1735
+		 *
1736
+		 * @param EEM_Base $model
1737
+		 * @param array    $fields_n_values the updated fields and their new values
1738
+		 * @param array    $query_params    @see EEM_Base::get_all()
1739
+		 * @param int      $rows_affected
1740
+		 */
1741
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
+		return $rows_affected;//how many supposedly got updated
1743
+	}
1744
+
1745
+
1746
+
1747
+	/**
1748
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1749
+	 * are teh values of the field specified (or by default the primary key field)
1750
+	 * that matched the query params. Note that you should pass the name of the
1751
+	 * model FIELD, not the database table's column name.
1752
+	 *
1753
+	 * @param array  $query_params @see EEM_Base::get_all()
1754
+	 * @param string $field_to_select
1755
+	 * @return array just like $wpdb->get_col()
1756
+	 * @throws \EE_Error
1757
+	 */
1758
+	public function get_col($query_params = array(), $field_to_select = null)
1759
+	{
1760
+		if ($field_to_select) {
1761
+			$field = $this->field_settings_for($field_to_select);
1762
+		} elseif ($this->has_primary_key_field()) {
1763
+			$field = $this->get_primary_key_field();
1764
+		} else {
1765
+			//no primary key, just grab the first column
1766
+			$field = reset($this->field_settings());
1767
+		}
1768
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
+		$select_expressions = $field->get_qualified_column();
1770
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1771
+		return $this->_do_wpdb_query('get_col', array($SQL));
1772
+	}
1773
+
1774
+
1775
+
1776
+	/**
1777
+	 * Returns a single column value for a single row from the database
1778
+	 *
1779
+	 * @param array  $query_params    @see EEM_Base::get_all()
1780
+	 * @param string $field_to_select @see EEM_Base::get_col()
1781
+	 * @return string
1782
+	 * @throws \EE_Error
1783
+	 */
1784
+	public function get_var($query_params = array(), $field_to_select = null)
1785
+	{
1786
+		$query_params['limit'] = 1;
1787
+		$col = $this->get_col($query_params, $field_to_select);
1788
+		if (! empty($col)) {
1789
+			return reset($col);
1790
+		} else {
1791
+			return null;
1792
+		}
1793
+	}
1794
+
1795
+
1796
+
1797
+	/**
1798
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1799
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1800
+	 * injection, but currently no further filtering is done
1801
+	 *
1802
+	 * @global      $wpdb
1803
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1804
+	 *                               be updated to in the DB
1805
+	 * @return string of SQL
1806
+	 * @throws \EE_Error
1807
+	 */
1808
+	public function _construct_update_sql($fields_n_values)
1809
+	{
1810
+		/** @type WPDB $wpdb */
1811
+		global $wpdb;
1812
+		$cols_n_values = array();
1813
+		foreach ($fields_n_values as $field_name => $value) {
1814
+			$field_obj = $this->field_settings_for($field_name);
1815
+			//if the value is NULL, we want to assign the value to that.
1816
+			//wpdb->prepare doesn't really handle that properly
1817
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818
+			$value_sql = $prepared_value === null ? 'NULL'
1819
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1821
+		}
1822
+		return implode(",", $cols_n_values);
1823
+	}
1824
+
1825
+
1826
+
1827
+	/**
1828
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1829
+	 * Performs a HARD delete, meaning the database row should always be removed,
1830
+	 * not just have a flag field on it switched
1831
+	 * Wrapper for EEM_Base::delete_permanently()
1832
+	 *
1833
+	 * @param mixed $id
1834
+	 * @return boolean whether the row got deleted or not
1835
+	 * @throws \EE_Error
1836
+	 */
1837
+	public function delete_permanently_by_ID($id)
1838
+	{
1839
+		return $this->delete_permanently(
1840
+			array(
1841
+				array($this->get_primary_key_field()->get_name() => $id),
1842
+				'limit' => 1,
1843
+			)
1844
+		);
1845
+	}
1846
+
1847
+
1848
+
1849
+	/**
1850
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
+	 * Wrapper for EEM_Base::delete()
1852
+	 *
1853
+	 * @param mixed $id
1854
+	 * @return boolean whether the row got deleted or not
1855
+	 * @throws \EE_Error
1856
+	 */
1857
+	public function delete_by_ID($id)
1858
+	{
1859
+		return $this->delete(
1860
+			array(
1861
+				array($this->get_primary_key_field()->get_name() => $id),
1862
+				'limit' => 1,
1863
+			)
1864
+		);
1865
+	}
1866
+
1867
+
1868
+
1869
+	/**
1870
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1871
+	 * meaning if the model has a field that indicates its been "trashed" or
1872
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1873
+	 *
1874
+	 * @see EEM_Base::delete_permanently
1875
+	 * @param array   $query_params
1876
+	 * @param boolean $allow_blocking
1877
+	 * @return int how many rows got deleted
1878
+	 * @throws \EE_Error
1879
+	 */
1880
+	public function delete($query_params, $allow_blocking = true)
1881
+	{
1882
+		return $this->delete_permanently($query_params, $allow_blocking);
1883
+	}
1884
+
1885
+
1886
+
1887
+	/**
1888
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1889
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1890
+	 * as archived, not actually deleted
1891
+	 *
1892
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1893
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1894
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1895
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1896
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1897
+	 *                                DB
1898
+	 * @return int how many rows got deleted
1899
+	 * @throws \EE_Error
1900
+	 */
1901
+	public function delete_permanently($query_params, $allow_blocking = true)
1902
+	{
1903
+		/**
1904
+		 * Action called just before performing a real deletion query. You can use the
1905
+		 * model and its $query_params to find exactly which items will be deleted
1906
+		 *
1907
+		 * @param EEM_Base $model
1908
+		 * @param array    $query_params   @see EEM_Base::get_all()
1909
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1910
+		 *                                 to block (prevent) this deletion
1911
+		 */
1912
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1913
+		//some MySQL databases may be running safe mode, which may restrict
1914
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1915
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1916
+		//to delete them
1917
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1918
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1919
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1920
+			$columns_and_ids_for_deleting
1921
+		);
1922
+		/**
1923
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1924
+		 *
1925
+		 * @param EEM_Base $this  The model instance being acted on.
1926
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1927
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1928
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1929
+		 *                                                  derived from the incoming query parameters.
1930
+		 *                                                  @see details on the structure of this array in the phpdocs
1931
+		 *                                                  for the `_get_ids_for_delete_method`
1932
+		 *
1933
+		 */
1934
+		do_action('AHEE__EEM_Base__delete__before_query',
1935
+			$this,
1936
+			$query_params,
1937
+			$allow_blocking,
1938
+			$columns_and_ids_for_deleting
1939
+		);
1940
+		if ($deletion_where_query_part) {
1941
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1942
+			$table_aliases = array_keys($this->_tables);
1943
+			$SQL = "DELETE "
1944
+				   . implode(", ", $table_aliases)
1945
+				   . " FROM "
1946
+				   . $model_query_info->get_full_join_sql()
1947
+				   . " WHERE "
1948
+				   . $deletion_where_query_part;
1949
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1950
+		} else {
1951
+			$rows_deleted = 0;
1952
+		}
1953
+
1954
+		//Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1955
+		//there was no error with the delete query.
1956
+		if ($this->has_primary_key_field()
1957
+			&& $rows_deleted !== false
1958
+			&& isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1959
+		) {
1960
+			$ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1961
+			foreach ($ids_for_removal as $id) {
1962
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1963
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1964
+				}
1965
+			}
1966
+
1967
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1968
+			//`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1969
+			//unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1970
+			// (although it is possible).
1971
+			//Note this can be skipped by using the provided filter and returning false.
1972
+			if (apply_filters(
1973
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1974
+				! $this instanceof EEM_Extra_Meta,
1975
+				$this
1976
+			)) {
1977
+				EEM_Extra_Meta::instance()->delete_permanently(array(
1978
+					0 => array(
1979
+						'EXM_type' => $this->get_this_model_name(),
1980
+						'OBJ_ID'   => array(
1981
+							'IN',
1982
+							$ids_for_removal
1983
+						)
1984
+					)
1985
+				));
1986
+			}
1987
+		}
1988
+
1989
+		/**
1990
+		 * Action called just after performing a real deletion query. Although at this point the
1991
+		 * items should have been deleted
1992
+		 *
1993
+		 * @param EEM_Base $model
1994
+		 * @param array    $query_params @see EEM_Base::get_all()
1995
+		 * @param int      $rows_deleted
1996
+		 */
1997
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
1998
+		return $rows_deleted;//how many supposedly got deleted
1999
+	}
2000
+
2001
+
2002
+
2003
+	/**
2004
+	 * Checks all the relations that throw error messages when there are blocking related objects
2005
+	 * for related model objects. If there are any related model objects on those relations,
2006
+	 * adds an EE_Error, and return true
2007
+	 *
2008
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2009
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2010
+	 *                                                 should be ignored when determining whether there are related
2011
+	 *                                                 model objects which block this model object's deletion. Useful
2012
+	 *                                                 if you know A is related to B and are considering deleting A,
2013
+	 *                                                 but want to see if A has any other objects blocking its deletion
2014
+	 *                                                 before removing the relation between A and B
2015
+	 * @return boolean
2016
+	 * @throws \EE_Error
2017
+	 */
2018
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2019
+	{
2020
+		//first, if $ignore_this_model_obj was supplied, get its model
2021
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2022
+			$ignored_model = $ignore_this_model_obj->get_model();
2023
+		} else {
2024
+			$ignored_model = null;
2025
+		}
2026
+		//now check all the relations of $this_model_obj_or_id and see if there
2027
+		//are any related model objects blocking it?
2028
+		$is_blocked = false;
2029
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2030
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2031
+				//if $ignore_this_model_obj was supplied, then for the query
2032
+				//on that model needs to be told to ignore $ignore_this_model_obj
2033
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2034
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2035
+						array(
2036
+							$ignored_model->get_primary_key_field()->get_name() => array(
2037
+								'!=',
2038
+								$ignore_this_model_obj->ID(),
2039
+							),
2040
+						),
2041
+					));
2042
+				} else {
2043
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2044
+				}
2045
+				if ($related_model_objects) {
2046
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2047
+					$is_blocked = true;
2048
+				}
2049
+			}
2050
+		}
2051
+		return $is_blocked;
2052
+	}
2053
+
2054
+
2055
+	/**
2056
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2057
+	 * @param array $row_results_for_deleting
2058
+	 * @param bool  $allow_blocking
2059
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2060
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2061
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2062
+	 *                 deleted. Example:
2063
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2064
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2065
+	 *                 where each element is a group of columns and values that get deleted. Example:
2066
+	 *                      array(
2067
+	 *                          0 => array(
2068
+	 *                              'Term_Relationship.object_id' => 1
2069
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2070
+	 *                          ),
2071
+	 *                          1 => array(
2072
+	 *                              'Term_Relationship.object_id' => 1
2073
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2074
+	 *                          )
2075
+	 *                      )
2076
+	 * @throws EE_Error
2077
+	 */
2078
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2079
+	{
2080
+		$ids_to_delete_indexed_by_column = array();
2081
+		if ($this->has_primary_key_field()) {
2082
+			$primary_table = $this->_get_main_table();
2083
+			$other_tables = $this->_get_other_tables();
2084
+			$ids_to_delete_indexed_by_column = $query = array();
2085
+			foreach ($row_results_for_deleting as $item_to_delete) {
2086
+				//before we mark this item for deletion,
2087
+				//make sure there's no related entities blocking its deletion (if we're checking)
2088
+				if (
2089
+					$allow_blocking
2090
+					&& $this->delete_is_blocked_by_related_models(
2091
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2092
+					)
2093
+				) {
2094
+					continue;
2095
+				}
2096
+				//primary table deletes
2097
+				if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2098
+					$ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2099
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2100
+				}
2101
+			}
2102
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2103
+			$fields = $this->get_combined_primary_key_fields();
2104
+			foreach ($row_results_for_deleting as $item_to_delete) {
2105
+				$ids_to_delete_indexed_by_column_for_row = array();
2106
+				foreach ($fields as $cpk_field) {
2107
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2108
+						$ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2109
+							$item_to_delete[$cpk_field->get_qualified_column()];
2110
+					}
2111
+				}
2112
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2113
+			}
2114
+		} else {
2115
+			//so there's no primary key and no combined key...
2116
+			//sorry, can't help you
2117
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2118
+				"event_espresso"), get_class($this)));
2119
+		}
2120
+		return $ids_to_delete_indexed_by_column;
2121
+	}
2122
+
2123
+
2124
+	/**
2125
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2126
+	 * the corresponding query_part for the query performing the delete.
2127
+	 *
2128
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2129
+	 * @return string
2130
+	 * @throws EE_Error
2131
+	 */
2132
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2133
+		$query_part = '';
2134
+		if (empty($ids_to_delete_indexed_by_column)) {
2135
+			return $query_part;
2136
+		} elseif ($this->has_primary_key_field()) {
2137
+			$query = array();
2138
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2139
+				//make sure we have unique $ids
2140
+				$ids = array_unique($ids);
2141
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2142
+			}
2143
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2144
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2145
+			$ways_to_identify_a_row = array();
2146
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2147
+				$values_for_each_combined_primary_key_for_a_row = array();
2148
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2149
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2150
+				}
2151
+				$ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2152
+			}
2153
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2154
+		}
2155
+		return $query_part;
2156
+	}
2157 2157
     
2158 2158
 
2159 2159
 
2160 2160
 
2161
-    /**
2162
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2163
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2164
-     * column
2165
-     *
2166
-     * @param array  $query_params   like EEM_Base::get_all's
2167
-     * @param string $field_to_count field on model to count by (not column name)
2168
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2169
-     *                               that by the setting $distinct to TRUE;
2170
-     * @return int
2171
-     * @throws \EE_Error
2172
-     */
2173
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2174
-    {
2175
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2176
-        if ($field_to_count) {
2177
-            $field_obj = $this->field_settings_for($field_to_count);
2178
-            $column_to_count = $field_obj->get_qualified_column();
2179
-        } elseif ($this->has_primary_key_field()) {
2180
-            $pk_field_obj = $this->get_primary_key_field();
2181
-            $column_to_count = $pk_field_obj->get_qualified_column();
2182
-        } else {
2183
-            //there's no primary key
2184
-            //if we're counting distinct items, and there's no primary key,
2185
-            //we need to list out the columns for distinction;
2186
-            //otherwise we can just use star
2187
-            if ($distinct) {
2188
-                $columns_to_use = array();
2189
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2190
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2191
-                }
2192
-                $column_to_count = implode(',', $columns_to_use);
2193
-            } else {
2194
-                $column_to_count = '*';
2195
-            }
2196
-        }
2197
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2198
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2199
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2200
-    }
2201
-
2202
-
2203
-
2204
-    /**
2205
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2206
-     *
2207
-     * @param array  $query_params like EEM_Base::get_all
2208
-     * @param string $field_to_sum name of field (array key in $_fields array)
2209
-     * @return float
2210
-     * @throws \EE_Error
2211
-     */
2212
-    public function sum($query_params, $field_to_sum = null)
2213
-    {
2214
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2215
-        if ($field_to_sum) {
2216
-            $field_obj = $this->field_settings_for($field_to_sum);
2217
-        } else {
2218
-            $field_obj = $this->get_primary_key_field();
2219
-        }
2220
-        $column_to_count = $field_obj->get_qualified_column();
2221
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2222
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2223
-        $data_type = $field_obj->get_wpdb_data_type();
2224
-        if ($data_type === '%d' || $data_type === '%s') {
2225
-            return (float)$return_value;
2226
-        } else {//must be %f
2227
-            return (float)$return_value;
2228
-        }
2229
-    }
2230
-
2231
-
2232
-
2233
-    /**
2234
-     * Just calls the specified method on $wpdb with the given arguments
2235
-     * Consolidates a little extra error handling code
2236
-     *
2237
-     * @param string $wpdb_method
2238
-     * @param array  $arguments_to_provide
2239
-     * @throws EE_Error
2240
-     * @global wpdb  $wpdb
2241
-     * @return mixed
2242
-     */
2243
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2244
-    {
2245
-        //if we're in maintenance mode level 2, DON'T run any queries
2246
-        //because level 2 indicates the database needs updating and
2247
-        //is probably out of sync with the code
2248
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2249
-            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.",
2250
-                "event_espresso")));
2251
-        }
2252
-        /** @type WPDB $wpdb */
2253
-        global $wpdb;
2254
-        if (! method_exists($wpdb, $wpdb_method)) {
2255
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2256
-                'event_espresso'), $wpdb_method));
2257
-        }
2258
-        if (WP_DEBUG) {
2259
-            $old_show_errors_value = $wpdb->show_errors;
2260
-            $wpdb->show_errors(false);
2261
-        }
2262
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2263
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2264
-        if (WP_DEBUG) {
2265
-            $wpdb->show_errors($old_show_errors_value);
2266
-            if (! empty($wpdb->last_error)) {
2267
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2268
-            } elseif ($result === false) {
2269
-                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"',
2270
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2271
-            }
2272
-        } elseif ($result === false) {
2273
-            EE_Error::add_error(
2274
-                sprintf(
2275
-                    __('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"',
2276
-                        'event_espresso'),
2277
-                    $wpdb_method,
2278
-                    var_export($arguments_to_provide, true),
2279
-                    $wpdb->last_error
2280
-                ),
2281
-                __FILE__,
2282
-                __FUNCTION__,
2283
-                __LINE__
2284
-            );
2285
-        }
2286
-        return $result;
2287
-    }
2288
-
2289
-
2290
-
2291
-    /**
2292
-     * Attempts to run the indicated WPDB method with the provided arguments,
2293
-     * and if there's an error tries to verify the DB is correct. Uses
2294
-     * the static property EEM_Base::$_db_verification_level to determine whether
2295
-     * we should try to fix the EE core db, the addons, or just give up
2296
-     *
2297
-     * @param string $wpdb_method
2298
-     * @param array  $arguments_to_provide
2299
-     * @return mixed
2300
-     */
2301
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2302
-    {
2303
-        /** @type WPDB $wpdb */
2304
-        global $wpdb;
2305
-        $wpdb->last_error = null;
2306
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2307
-        // was there an error running the query? but we don't care on new activations
2308
-        // (we're going to setup the DB anyway on new activations)
2309
-        if (($result === false || ! empty($wpdb->last_error))
2310
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2311
-        ) {
2312
-            switch (EEM_Base::$_db_verification_level) {
2313
-                case EEM_Base::db_verified_none :
2314
-                    // let's double-check core's DB
2315
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2316
-                    break;
2317
-                case EEM_Base::db_verified_core :
2318
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2319
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2320
-                    break;
2321
-                case EEM_Base::db_verified_addons :
2322
-                    // ummmm... you in trouble
2323
-                    return $result;
2324
-                    break;
2325
-            }
2326
-            if (! empty($error_message)) {
2327
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2328
-                trigger_error($error_message);
2329
-            }
2330
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2331
-        }
2332
-        return $result;
2333
-    }
2334
-
2335
-
2336
-
2337
-    /**
2338
-     * Verifies the EE core database is up-to-date and records that we've done it on
2339
-     * EEM_Base::$_db_verification_level
2340
-     *
2341
-     * @param string $wpdb_method
2342
-     * @param array  $arguments_to_provide
2343
-     * @return string
2344
-     */
2345
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2346
-    {
2347
-        /** @type WPDB $wpdb */
2348
-        global $wpdb;
2349
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2350
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2351
-        $error_message = sprintf(
2352
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2353
-                'event_espresso'),
2354
-            $wpdb->last_error,
2355
-            $wpdb_method,
2356
-            wp_json_encode($arguments_to_provide)
2357
-        );
2358
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2359
-        return $error_message;
2360
-    }
2361
-
2362
-
2363
-
2364
-    /**
2365
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2366
-     * EEM_Base::$_db_verification_level
2367
-     *
2368
-     * @param $wpdb_method
2369
-     * @param $arguments_to_provide
2370
-     * @return string
2371
-     */
2372
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2373
-    {
2374
-        /** @type WPDB $wpdb */
2375
-        global $wpdb;
2376
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2377
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2378
-        $error_message = sprintf(
2379
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2380
-                'event_espresso'),
2381
-            $wpdb->last_error,
2382
-            $wpdb_method,
2383
-            wp_json_encode($arguments_to_provide)
2384
-        );
2385
-        EE_System::instance()->initialize_addons();
2386
-        return $error_message;
2387
-    }
2388
-
2389
-
2390
-
2391
-    /**
2392
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2393
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2394
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2395
-     * ..."
2396
-     *
2397
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2398
-     * @return string
2399
-     */
2400
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2401
-    {
2402
-        return " FROM " . $model_query_info->get_full_join_sql() .
2403
-               $model_query_info->get_where_sql() .
2404
-               $model_query_info->get_group_by_sql() .
2405
-               $model_query_info->get_having_sql() .
2406
-               $model_query_info->get_order_by_sql() .
2407
-               $model_query_info->get_limit_sql();
2408
-    }
2409
-
2410
-
2411
-
2412
-    /**
2413
-     * Set to easily debug the next X queries ran from this model.
2414
-     *
2415
-     * @param int $count
2416
-     */
2417
-    public function show_next_x_db_queries($count = 1)
2418
-    {
2419
-        $this->_show_next_x_db_queries = $count;
2420
-    }
2421
-
2422
-
2423
-
2424
-    /**
2425
-     * @param $sql_query
2426
-     */
2427
-    public function show_db_query_if_previously_requested($sql_query)
2428
-    {
2429
-        if ($this->_show_next_x_db_queries > 0) {
2430
-            echo $sql_query;
2431
-            $this->_show_next_x_db_queries--;
2432
-        }
2433
-    }
2434
-
2435
-
2436
-
2437
-    /**
2438
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2439
-     * There are the 3 cases:
2440
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2441
-     * $otherModelObject has no ID, it is first saved.
2442
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2443
-     * has no ID, it is first saved.
2444
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2445
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2446
-     * join table
2447
-     *
2448
-     * @param        EE_Base_Class                     /int $thisModelObject
2449
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2450
-     * @param string $relationName                     , key in EEM_Base::_relations
2451
-     *                                                 an attendee to a group, you also want to specify which role they
2452
-     *                                                 will have in that group. So you would use this parameter to
2453
-     *                                                 specify array('role-column-name'=>'role-id')
2454
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2455
-     *                                                 to for relation to methods that allow you to further specify
2456
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2457
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2458
-     *                                                 because these will be inserted in any new rows created as well.
2459
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2460
-     * @throws \EE_Error
2461
-     */
2462
-    public function add_relationship_to(
2463
-        $id_or_obj,
2464
-        $other_model_id_or_obj,
2465
-        $relationName,
2466
-        $extra_join_model_fields_n_values = array()
2467
-    ) {
2468
-        $relation_obj = $this->related_settings_for($relationName);
2469
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2470
-    }
2471
-
2472
-
2473
-
2474
-    /**
2475
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2476
-     * There are the 3 cases:
2477
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2478
-     * error
2479
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2480
-     * an error
2481
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2482
-     *
2483
-     * @param        EE_Base_Class /int $id_or_obj
2484
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2485
-     * @param string $relationName key in EEM_Base::_relations
2486
-     * @return boolean of success
2487
-     * @throws \EE_Error
2488
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2489
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2490
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2491
-     *                             because these will be inserted in any new rows created as well.
2492
-     */
2493
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2494
-    {
2495
-        $relation_obj = $this->related_settings_for($relationName);
2496
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2497
-    }
2498
-
2499
-
2500
-
2501
-    /**
2502
-     * @param mixed           $id_or_obj
2503
-     * @param string          $relationName
2504
-     * @param array           $where_query_params
2505
-     * @param EE_Base_Class[] objects to which relations were removed
2506
-     * @return \EE_Base_Class[]
2507
-     * @throws \EE_Error
2508
-     */
2509
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2510
-    {
2511
-        $relation_obj = $this->related_settings_for($relationName);
2512
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2513
-    }
2514
-
2515
-
2516
-
2517
-    /**
2518
-     * Gets all the related items of the specified $model_name, using $query_params.
2519
-     * Note: by default, we remove the "default query params"
2520
-     * because we want to get even deleted items etc.
2521
-     *
2522
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2523
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2524
-     * @param array  $query_params like EEM_Base::get_all
2525
-     * @return EE_Base_Class[]
2526
-     * @throws \EE_Error
2527
-     */
2528
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2529
-    {
2530
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2531
-        $relation_settings = $this->related_settings_for($model_name);
2532
-        return $relation_settings->get_all_related($model_obj, $query_params);
2533
-    }
2534
-
2535
-
2536
-
2537
-    /**
2538
-     * Deletes all the model objects across the relation indicated by $model_name
2539
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2540
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2541
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2542
-     *
2543
-     * @param EE_Base_Class|int|string $id_or_obj
2544
-     * @param string                   $model_name
2545
-     * @param array                    $query_params
2546
-     * @return int how many deleted
2547
-     * @throws \EE_Error
2548
-     */
2549
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2550
-    {
2551
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2552
-        $relation_settings = $this->related_settings_for($model_name);
2553
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2554
-    }
2555
-
2556
-
2557
-
2558
-    /**
2559
-     * Hard deletes all the model objects across the relation indicated by $model_name
2560
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2561
-     * the model objects can't be hard deleted because of blocking related model objects,
2562
-     * just does a soft-delete on them instead.
2563
-     *
2564
-     * @param EE_Base_Class|int|string $id_or_obj
2565
-     * @param string                   $model_name
2566
-     * @param array                    $query_params
2567
-     * @return int how many deleted
2568
-     * @throws \EE_Error
2569
-     */
2570
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2571
-    {
2572
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2573
-        $relation_settings = $this->related_settings_for($model_name);
2574
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2575
-    }
2576
-
2577
-
2578
-
2579
-    /**
2580
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2581
-     * unless otherwise specified in the $query_params
2582
-     *
2583
-     * @param        int             /EE_Base_Class $id_or_obj
2584
-     * @param string $model_name     like 'Event', or 'Registration'
2585
-     * @param array  $query_params   like EEM_Base::get_all's
2586
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2587
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2588
-     *                               that by the setting $distinct to TRUE;
2589
-     * @return int
2590
-     * @throws \EE_Error
2591
-     */
2592
-    public function count_related(
2593
-        $id_or_obj,
2594
-        $model_name,
2595
-        $query_params = array(),
2596
-        $field_to_count = null,
2597
-        $distinct = false
2598
-    ) {
2599
-        $related_model = $this->get_related_model_obj($model_name);
2600
-        //we're just going to use the query params on the related model's normal get_all query,
2601
-        //except add a condition to say to match the current mod
2602
-        if (! isset($query_params['default_where_conditions'])) {
2603
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2604
-        }
2605
-        $this_model_name = $this->get_this_model_name();
2606
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2607
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2608
-        return $related_model->count($query_params, $field_to_count, $distinct);
2609
-    }
2610
-
2611
-
2612
-
2613
-    /**
2614
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2615
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2616
-     *
2617
-     * @param        int           /EE_Base_Class $id_or_obj
2618
-     * @param string $model_name   like 'Event', or 'Registration'
2619
-     * @param array  $query_params like EEM_Base::get_all's
2620
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2621
-     * @return float
2622
-     * @throws \EE_Error
2623
-     */
2624
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2625
-    {
2626
-        $related_model = $this->get_related_model_obj($model_name);
2627
-        if (! is_array($query_params)) {
2628
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2629
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2630
-                    gettype($query_params)), '4.6.0');
2631
-            $query_params = array();
2632
-        }
2633
-        //we're just going to use the query params on the related model's normal get_all query,
2634
-        //except add a condition to say to match the current mod
2635
-        if (! isset($query_params['default_where_conditions'])) {
2636
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2637
-        }
2638
-        $this_model_name = $this->get_this_model_name();
2639
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2640
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2641
-        return $related_model->sum($query_params, $field_to_sum);
2642
-    }
2643
-
2644
-
2645
-
2646
-    /**
2647
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2648
-     * $modelObject
2649
-     *
2650
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2651
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2652
-     * @param array               $query_params     like EEM_Base::get_all's
2653
-     * @return EE_Base_Class
2654
-     * @throws \EE_Error
2655
-     */
2656
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2657
-    {
2658
-        $query_params['limit'] = 1;
2659
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2660
-        if ($results) {
2661
-            return array_shift($results);
2662
-        } else {
2663
-            return null;
2664
-        }
2665
-    }
2666
-
2667
-
2668
-
2669
-    /**
2670
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2671
-     *
2672
-     * @return string
2673
-     */
2674
-    public function get_this_model_name()
2675
-    {
2676
-        return str_replace("EEM_", "", get_class($this));
2677
-    }
2678
-
2679
-
2680
-
2681
-    /**
2682
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2683
-     *
2684
-     * @return EE_Any_Foreign_Model_Name_Field
2685
-     * @throws EE_Error
2686
-     */
2687
-    public function get_field_containing_related_model_name()
2688
-    {
2689
-        foreach ($this->field_settings(true) as $field) {
2690
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2691
-                $field_with_model_name = $field;
2692
-            }
2693
-        }
2694
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2695
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2696
-                $this->get_this_model_name()));
2697
-        }
2698
-        return $field_with_model_name;
2699
-    }
2700
-
2701
-
2702
-
2703
-    /**
2704
-     * Inserts a new entry into the database, for each table.
2705
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2706
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2707
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2708
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2709
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2710
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2711
-     *
2712
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2713
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2714
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2715
-     *                              of EEM_Base)
2716
-     * @return int new primary key on main table that got inserted
2717
-     * @throws EE_Error
2718
-     */
2719
-    public function insert($field_n_values)
2720
-    {
2721
-        /**
2722
-         * Filters the fields and their values before inserting an item using the models
2723
-         *
2724
-         * @param array    $fields_n_values keys are the fields and values are their new values
2725
-         * @param EEM_Base $model           the model used
2726
-         */
2727
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2728
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2729
-            $main_table = $this->_get_main_table();
2730
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2731
-            if ($new_id !== false) {
2732
-                foreach ($this->_get_other_tables() as $other_table) {
2733
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2734
-                }
2735
-            }
2736
-            /**
2737
-             * Done just after attempting to insert a new model object
2738
-             *
2739
-             * @param EEM_Base   $model           used
2740
-             * @param array      $fields_n_values fields and their values
2741
-             * @param int|string the              ID of the newly-inserted model object
2742
-             */
2743
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2744
-            return $new_id;
2745
-        } else {
2746
-            return false;
2747
-        }
2748
-    }
2749
-
2750
-
2751
-
2752
-    /**
2753
-     * Checks that the result would satisfy the unique indexes on this model
2754
-     *
2755
-     * @param array  $field_n_values
2756
-     * @param string $action
2757
-     * @return boolean
2758
-     * @throws \EE_Error
2759
-     */
2760
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2761
-    {
2762
-        foreach ($this->unique_indexes() as $index_name => $index) {
2763
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2764
-            if ($this->exists(array($uniqueness_where_params))) {
2765
-                EE_Error::add_error(
2766
-                    sprintf(
2767
-                        __(
2768
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2769
-                            "event_espresso"
2770
-                        ),
2771
-                        $action,
2772
-                        $this->_get_class_name(),
2773
-                        $index_name,
2774
-                        implode(",", $index->field_names()),
2775
-                        http_build_query($uniqueness_where_params)
2776
-                    ),
2777
-                    __FILE__,
2778
-                    __FUNCTION__,
2779
-                    __LINE__
2780
-                );
2781
-                return false;
2782
-            }
2783
-        }
2784
-        return true;
2785
-    }
2786
-
2787
-
2788
-
2789
-    /**
2790
-     * Checks the database for an item that conflicts (ie, if this item were
2791
-     * saved to the DB would break some uniqueness requirement, like a primary key
2792
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2793
-     * can be either an EE_Base_Class or an array of fields n values
2794
-     *
2795
-     * @param EE_Base_Class|array $obj_or_fields_array
2796
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2797
-     *                                                 when looking for conflicts
2798
-     *                                                 (ie, if false, we ignore the model object's primary key
2799
-     *                                                 when finding "conflicts". If true, it's also considered).
2800
-     *                                                 Only works for INT primary key,
2801
-     *                                                 STRING primary keys cannot be ignored
2802
-     * @throws EE_Error
2803
-     * @return EE_Base_Class|array
2804
-     */
2805
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2806
-    {
2807
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2808
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2809
-        } elseif (is_array($obj_or_fields_array)) {
2810
-            $fields_n_values = $obj_or_fields_array;
2811
-        } else {
2812
-            throw new EE_Error(
2813
-                sprintf(
2814
-                    __(
2815
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2816
-                        "event_espresso"
2817
-                    ),
2818
-                    get_class($this),
2819
-                    $obj_or_fields_array
2820
-                )
2821
-            );
2822
-        }
2823
-        $query_params = array();
2824
-        if ($this->has_primary_key_field()
2825
-            && ($include_primary_key
2826
-                || $this->get_primary_key_field()
2827
-                   instanceof
2828
-                   EE_Primary_Key_String_Field)
2829
-            && isset($fields_n_values[$this->primary_key_name()])
2830
-        ) {
2831
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2832
-        }
2833
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2834
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2835
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2836
-        }
2837
-        //if there is nothing to base this search on, then we shouldn't find anything
2838
-        if (empty($query_params)) {
2839
-            return array();
2840
-        } else {
2841
-            return $this->get_one($query_params);
2842
-        }
2843
-    }
2844
-
2845
-
2846
-
2847
-    /**
2848
-     * Like count, but is optimized and returns a boolean instead of an int
2849
-     *
2850
-     * @param array $query_params
2851
-     * @return boolean
2852
-     * @throws \EE_Error
2853
-     */
2854
-    public function exists($query_params)
2855
-    {
2856
-        $query_params['limit'] = 1;
2857
-        return $this->count($query_params) > 0;
2858
-    }
2859
-
2860
-
2861
-
2862
-    /**
2863
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2864
-     *
2865
-     * @param int|string $id
2866
-     * @return boolean
2867
-     * @throws \EE_Error
2868
-     */
2869
-    public function exists_by_ID($id)
2870
-    {
2871
-        return $this->exists(
2872
-            array(
2873
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2874
-                array(
2875
-                    $this->primary_key_name() => $id,
2876
-                ),
2877
-            )
2878
-        );
2879
-    }
2880
-
2881
-
2882
-
2883
-    /**
2884
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2885
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2886
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2887
-     * on the main table)
2888
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2889
-     * cases where we want to call it directly rather than via insert().
2890
-     *
2891
-     * @access   protected
2892
-     * @param EE_Table_Base $table
2893
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2894
-     *                                       float
2895
-     * @param int           $new_id          for now we assume only int keys
2896
-     * @throws EE_Error
2897
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2898
-     * @return int ID of new row inserted, or FALSE on failure
2899
-     */
2900
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2901
-    {
2902
-        global $wpdb;
2903
-        $insertion_col_n_values = array();
2904
-        $format_for_insertion = array();
2905
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2906
-        foreach ($fields_on_table as $field_name => $field_obj) {
2907
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2908
-            if ($field_obj->is_auto_increment()) {
2909
-                continue;
2910
-            }
2911
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2912
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2913
-            if ($prepared_value !== null) {
2914
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2915
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2916
-            }
2917
-        }
2918
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2919
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2920
-            //so add the fk to the main table as a column
2921
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2922
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2923
-        }
2924
-        //insert the new entry
2925
-        $result = $this->_do_wpdb_query('insert',
2926
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2927
-        if ($result === false) {
2928
-            return false;
2929
-        }
2930
-        //ok, now what do we return for the ID of the newly-inserted thing?
2931
-        if ($this->has_primary_key_field()) {
2932
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2933
-                return $wpdb->insert_id;
2934
-            } else {
2935
-                //it's not an auto-increment primary key, so
2936
-                //it must have been supplied
2937
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2938
-            }
2939
-        } else {
2940
-            //we can't return a  primary key because there is none. instead return
2941
-            //a unique string indicating this model
2942
-            return $this->get_index_primary_key_string($fields_n_values);
2943
-        }
2944
-    }
2945
-
2946
-
2947
-
2948
-    /**
2949
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2950
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2951
-     * and there is no default, we pass it along. WPDB will take care of it)
2952
-     *
2953
-     * @param EE_Model_Field_Base $field_obj
2954
-     * @param array               $fields_n_values
2955
-     * @return mixed string|int|float depending on what the table column will be expecting
2956
-     * @throws \EE_Error
2957
-     */
2958
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2959
-    {
2960
-        //if this field doesn't allow nullable, don't allow it
2961
-        if (
2962
-            ! $field_obj->is_nullable()
2963
-            && (
2964
-                ! isset($fields_n_values[$field_obj->get_name()])
2965
-                || $fields_n_values[$field_obj->get_name()] === null
2966
-            )
2967
-        ) {
2968
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2969
-        }
2970
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2971
-            ? $fields_n_values[$field_obj->get_name()]
2972
-            : null;
2973
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2974
-    }
2975
-
2976
-
2977
-
2978
-    /**
2979
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2980
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2981
-     * the field's prepare_for_set() method.
2982
-     *
2983
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2984
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2985
-     *                                   top of file)
2986
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2987
-     *                                   $value is a custom selection
2988
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2989
-     */
2990
-    private function _prepare_value_for_use_in_db($value, $field)
2991
-    {
2992
-        if ($field && $field instanceof EE_Model_Field_Base) {
2993
-            switch ($this->_values_already_prepared_by_model_object) {
2994
-                /** @noinspection PhpMissingBreakStatementInspection */
2995
-                case self::not_prepared_by_model_object:
2996
-                    $value = $field->prepare_for_set($value);
2997
-                //purposefully left out "return"
2998
-                case self::prepared_by_model_object:
2999
-                    $value = $field->prepare_for_use_in_db($value);
3000
-                case self::prepared_for_use_in_db:
3001
-                    //leave the value alone
3002
-            }
3003
-            return $value;
3004
-        } else {
3005
-            return $value;
3006
-        }
3007
-    }
3008
-
3009
-
3010
-
3011
-    /**
3012
-     * Returns the main table on this model
3013
-     *
3014
-     * @return EE_Primary_Table
3015
-     * @throws EE_Error
3016
-     */
3017
-    protected function _get_main_table()
3018
-    {
3019
-        foreach ($this->_tables as $table) {
3020
-            if ($table instanceof EE_Primary_Table) {
3021
-                return $table;
3022
-            }
3023
-        }
3024
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3025
-            'event_espresso'), get_class($this)));
3026
-    }
3027
-
3028
-
3029
-
3030
-    /**
3031
-     * table
3032
-     * returns EE_Primary_Table table name
3033
-     *
3034
-     * @return string
3035
-     * @throws \EE_Error
3036
-     */
3037
-    public function table()
3038
-    {
3039
-        return $this->_get_main_table()->get_table_name();
3040
-    }
3041
-
3042
-
3043
-
3044
-    /**
3045
-     * table
3046
-     * returns first EE_Secondary_Table table name
3047
-     *
3048
-     * @return string
3049
-     */
3050
-    public function second_table()
3051
-    {
3052
-        // grab second table from tables array
3053
-        $second_table = end($this->_tables);
3054
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3055
-    }
3056
-
3057
-
3058
-
3059
-    /**
3060
-     * get_table_obj_by_alias
3061
-     * returns table name given it's alias
3062
-     *
3063
-     * @param string $table_alias
3064
-     * @return EE_Primary_Table | EE_Secondary_Table
3065
-     */
3066
-    public function get_table_obj_by_alias($table_alias = '')
3067
-    {
3068
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3069
-    }
3070
-
3071
-
3072
-
3073
-    /**
3074
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3075
-     *
3076
-     * @return EE_Secondary_Table[]
3077
-     */
3078
-    protected function _get_other_tables()
3079
-    {
3080
-        $other_tables = array();
3081
-        foreach ($this->_tables as $table_alias => $table) {
3082
-            if ($table instanceof EE_Secondary_Table) {
3083
-                $other_tables[$table_alias] = $table;
3084
-            }
3085
-        }
3086
-        return $other_tables;
3087
-    }
3088
-
3089
-
3090
-
3091
-    /**
3092
-     * Finds all the fields that correspond to the given table
3093
-     *
3094
-     * @param string $table_alias , array key in EEM_Base::_tables
3095
-     * @return EE_Model_Field_Base[]
3096
-     */
3097
-    public function _get_fields_for_table($table_alias)
3098
-    {
3099
-        return $this->_fields[$table_alias];
3100
-    }
3101
-
3102
-
3103
-
3104
-    /**
3105
-     * Recurses through all the where parameters, and finds all the related models we'll need
3106
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3107
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3108
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3109
-     * related Registration, Transaction, and Payment models.
3110
-     *
3111
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3112
-     * @return EE_Model_Query_Info_Carrier
3113
-     * @throws \EE_Error
3114
-     */
3115
-    public function _extract_related_models_from_query($query_params)
3116
-    {
3117
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3118
-        if (array_key_exists(0, $query_params)) {
3119
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3120
-        }
3121
-        if (array_key_exists('group_by', $query_params)) {
3122
-            if (is_array($query_params['group_by'])) {
3123
-                $this->_extract_related_models_from_sub_params_array_values(
3124
-                    $query_params['group_by'],
3125
-                    $query_info_carrier,
3126
-                    'group_by'
3127
-                );
3128
-            } elseif (! empty ($query_params['group_by'])) {
3129
-                $this->_extract_related_model_info_from_query_param(
3130
-                    $query_params['group_by'],
3131
-                    $query_info_carrier,
3132
-                    'group_by'
3133
-                );
3134
-            }
3135
-        }
3136
-        if (array_key_exists('having', $query_params)) {
3137
-            $this->_extract_related_models_from_sub_params_array_keys(
3138
-                $query_params[0],
3139
-                $query_info_carrier,
3140
-                'having'
3141
-            );
3142
-        }
3143
-        if (array_key_exists('order_by', $query_params)) {
3144
-            if (is_array($query_params['order_by'])) {
3145
-                $this->_extract_related_models_from_sub_params_array_keys(
3146
-                    $query_params['order_by'],
3147
-                    $query_info_carrier,
3148
-                    'order_by'
3149
-                );
3150
-            } elseif (! empty($query_params['order_by'])) {
3151
-                $this->_extract_related_model_info_from_query_param(
3152
-                    $query_params['order_by'],
3153
-                    $query_info_carrier,
3154
-                    'order_by'
3155
-                );
3156
-            }
3157
-        }
3158
-        if (array_key_exists('force_join', $query_params)) {
3159
-            $this->_extract_related_models_from_sub_params_array_values(
3160
-                $query_params['force_join'],
3161
-                $query_info_carrier,
3162
-                'force_join'
3163
-            );
3164
-        }
3165
-        return $query_info_carrier;
3166
-    }
3167
-
3168
-
3169
-
3170
-    /**
3171
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3172
-     *
3173
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3174
-     *                                                      $query_params['having']
3175
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3176
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3177
-     * @throws EE_Error
3178
-     * @return \EE_Model_Query_Info_Carrier
3179
-     */
3180
-    private function _extract_related_models_from_sub_params_array_keys(
3181
-        $sub_query_params,
3182
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3183
-        $query_param_type
3184
-    ) {
3185
-        if (! empty($sub_query_params)) {
3186
-            $sub_query_params = (array)$sub_query_params;
3187
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3188
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3189
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3190
-                    $query_param_type);
3191
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3192
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3193
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3194
-                //of array('Registration.TXN_ID'=>23)
3195
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3196
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3197
-                    if (! is_array($possibly_array_of_params)) {
3198
-                        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'))",
3199
-                            "event_espresso"),
3200
-                            $param, $possibly_array_of_params));
3201
-                    } else {
3202
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3203
-                            $model_query_info_carrier, $query_param_type);
3204
-                    }
3205
-                } elseif ($query_param_type === 0 //ie WHERE
3206
-                          && is_array($possibly_array_of_params)
3207
-                          && isset($possibly_array_of_params[2])
3208
-                          && $possibly_array_of_params[2] == true
3209
-                ) {
3210
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3211
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3212
-                    //from which we should extract query parameters!
3213
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3214
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3215
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3216
-                    }
3217
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3218
-                        $model_query_info_carrier, $query_param_type);
3219
-                }
3220
-            }
3221
-        }
3222
-        return $model_query_info_carrier;
3223
-    }
3224
-
3225
-
3226
-
3227
-    /**
3228
-     * For extracting related models from forced_joins, where the array values contain the info about what
3229
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3230
-     *
3231
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3232
-     *                                                      $query_params['having']
3233
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3234
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3235
-     * @throws EE_Error
3236
-     * @return \EE_Model_Query_Info_Carrier
3237
-     */
3238
-    private function _extract_related_models_from_sub_params_array_values(
3239
-        $sub_query_params,
3240
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3241
-        $query_param_type
3242
-    ) {
3243
-        if (! empty($sub_query_params)) {
3244
-            if (! is_array($sub_query_params)) {
3245
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3246
-                    $sub_query_params));
3247
-            }
3248
-            foreach ($sub_query_params as $param) {
3249
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3250
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3251
-                    $query_param_type);
3252
-            }
3253
-        }
3254
-        return $model_query_info_carrier;
3255
-    }
3256
-
3257
-
3258
-
3259
-    /**
3260
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3261
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3262
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3263
-     * but use them in a different order. Eg, we need to know what models we are querying
3264
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3265
-     * other models before we can finalize the where clause SQL.
3266
-     *
3267
-     * @param array $query_params
3268
-     * @throws EE_Error
3269
-     * @return EE_Model_Query_Info_Carrier
3270
-     */
3271
-    public function _create_model_query_info_carrier($query_params)
3272
-    {
3273
-        if (! is_array($query_params)) {
3274
-            EE_Error::doing_it_wrong(
3275
-                'EEM_Base::_create_model_query_info_carrier',
3276
-                sprintf(
3277
-                    __(
3278
-                        '$query_params should be an array, you passed a variable of type %s',
3279
-                        'event_espresso'
3280
-                    ),
3281
-                    gettype($query_params)
3282
-                ),
3283
-                '4.6.0'
3284
-            );
3285
-            $query_params = array();
3286
-        }
3287
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3288
-        //first check if we should alter the query to account for caps or not
3289
-        //because the caps might require us to do extra joins
3290
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3291
-            $query_params[0] = $where_query_params = array_replace_recursive(
3292
-                $where_query_params,
3293
-                $this->caps_where_conditions(
3294
-                    $query_params['caps']
3295
-                )
3296
-            );
3297
-        }
3298
-        $query_object = $this->_extract_related_models_from_query($query_params);
3299
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3300
-        foreach ($where_query_params as $key => $value) {
3301
-            if (is_int($key)) {
3302
-                throw new EE_Error(
3303
-                    sprintf(
3304
-                        __(
3305
-                            "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.",
3306
-                            "event_espresso"
3307
-                        ),
3308
-                        $key,
3309
-                        var_export($value, true),
3310
-                        var_export($query_params, true),
3311
-                        get_class($this)
3312
-                    )
3313
-                );
3314
-            }
3315
-        }
3316
-        if (
3317
-            array_key_exists('default_where_conditions', $query_params)
3318
-            && ! empty($query_params['default_where_conditions'])
3319
-        ) {
3320
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3321
-        } else {
3322
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3323
-        }
3324
-        $where_query_params = array_merge(
3325
-            $this->_get_default_where_conditions_for_models_in_query(
3326
-                $query_object,
3327
-                $use_default_where_conditions,
3328
-                $where_query_params
3329
-            ),
3330
-            $where_query_params
3331
-        );
3332
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3333
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3334
-        // So we need to setup a subquery and use that for the main join.
3335
-        // Note for now this only works on the primary table for the model.
3336
-        // So for instance, you could set the limit array like this:
3337
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3338
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3339
-            $query_object->set_main_model_join_sql(
3340
-                $this->_construct_limit_join_select(
3341
-                    $query_params['on_join_limit'][0],
3342
-                    $query_params['on_join_limit'][1]
3343
-                )
3344
-            );
3345
-        }
3346
-        //set limit
3347
-        if (array_key_exists('limit', $query_params)) {
3348
-            if (is_array($query_params['limit'])) {
3349
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3350
-                    $e = sprintf(
3351
-                        __(
3352
-                            "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)",
3353
-                            "event_espresso"
3354
-                        ),
3355
-                        http_build_query($query_params['limit'])
3356
-                    );
3357
-                    throw new EE_Error($e . "|" . $e);
3358
-                }
3359
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3360
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3361
-            } elseif (! empty ($query_params['limit'])) {
3362
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3363
-            }
3364
-        }
3365
-        //set order by
3366
-        if (array_key_exists('order_by', $query_params)) {
3367
-            if (is_array($query_params['order_by'])) {
3368
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3369
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3370
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3371
-                if (array_key_exists('order', $query_params)) {
3372
-                    throw new EE_Error(
3373
-                        sprintf(
3374
-                            __(
3375
-                                "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 ",
3376
-                                "event_espresso"
3377
-                            ),
3378
-                            get_class($this),
3379
-                            implode(", ", array_keys($query_params['order_by'])),
3380
-                            implode(", ", $query_params['order_by']),
3381
-                            $query_params['order']
3382
-                        )
3383
-                    );
3384
-                }
3385
-                $this->_extract_related_models_from_sub_params_array_keys(
3386
-                    $query_params['order_by'],
3387
-                    $query_object,
3388
-                    'order_by'
3389
-                );
3390
-                //assume it's an array of fields to order by
3391
-                $order_array = array();
3392
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3393
-                    $order = $this->_extract_order($order);
3394
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3395
-                }
3396
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3397
-            } elseif (! empty ($query_params['order_by'])) {
3398
-                $this->_extract_related_model_info_from_query_param(
3399
-                    $query_params['order_by'],
3400
-                    $query_object,
3401
-                    'order',
3402
-                    $query_params['order_by']
3403
-                );
3404
-                $order = isset($query_params['order'])
3405
-                    ? $this->_extract_order($query_params['order'])
3406
-                    : 'DESC';
3407
-                $query_object->set_order_by_sql(
3408
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3409
-                );
3410
-            }
3411
-        }
3412
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3413
-        if (! array_key_exists('order_by', $query_params)
3414
-            && array_key_exists('order', $query_params)
3415
-            && ! empty($query_params['order'])
3416
-        ) {
3417
-            $pk_field = $this->get_primary_key_field();
3418
-            $order = $this->_extract_order($query_params['order']);
3419
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3420
-        }
3421
-        //set group by
3422
-        if (array_key_exists('group_by', $query_params)) {
3423
-            if (is_array($query_params['group_by'])) {
3424
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3425
-                $group_by_array = array();
3426
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3427
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3428
-                }
3429
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3430
-            } elseif (! empty ($query_params['group_by'])) {
3431
-                $query_object->set_group_by_sql(
3432
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3433
-                );
3434
-            }
3435
-        }
3436
-        //set having
3437
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3438
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3439
-        }
3440
-        //now, just verify they didn't pass anything wack
3441
-        foreach ($query_params as $query_key => $query_value) {
3442
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3443
-                throw new EE_Error(
3444
-                    sprintf(
3445
-                        __(
3446
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3447
-                            'event_espresso'
3448
-                        ),
3449
-                        $query_key,
3450
-                        get_class($this),
3451
-                        //						print_r( $this->_allowed_query_params, TRUE )
3452
-                        implode(',', $this->_allowed_query_params)
3453
-                    )
3454
-                );
3455
-            }
3456
-        }
3457
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3458
-        if (empty($main_model_join_sql)) {
3459
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3460
-        }
3461
-        return $query_object;
3462
-    }
3463
-
3464
-
3465
-
3466
-    /**
3467
-     * Gets the where conditions that should be imposed on the query based on the
3468
-     * context (eg reading frontend, backend, edit or delete).
3469
-     *
3470
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3471
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3472
-     * @throws \EE_Error
3473
-     */
3474
-    public function caps_where_conditions($context = self::caps_read)
3475
-    {
3476
-        EEM_Base::verify_is_valid_cap_context($context);
3477
-        $cap_where_conditions = array();
3478
-        $cap_restrictions = $this->caps_missing($context);
3479
-        /**
3480
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3481
-         */
3482
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3483
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3484
-                $restriction_if_no_cap->get_default_where_conditions());
3485
-        }
3486
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3487
-            $cap_restrictions);
3488
-    }
3489
-
3490
-
3491
-
3492
-    /**
3493
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3494
-     * otherwise throws an exception
3495
-     *
3496
-     * @param string $should_be_order_string
3497
-     * @return string either ASC, asc, DESC or desc
3498
-     * @throws EE_Error
3499
-     */
3500
-    private function _extract_order($should_be_order_string)
3501
-    {
3502
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3503
-            return $should_be_order_string;
3504
-        } else {
3505
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3506
-                "event_espresso"), get_class($this), $should_be_order_string));
3507
-        }
3508
-    }
3509
-
3510
-
3511
-
3512
-    /**
3513
-     * Looks at all the models which are included in this query, and asks each
3514
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3515
-     * so they can be merged
3516
-     *
3517
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3518
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3519
-     *                                                                  'none' means NO default where conditions will
3520
-     *                                                                  be used AT ALL during this query.
3521
-     *                                                                  'other_models_only' means default where
3522
-     *                                                                  conditions from other models will be used, but
3523
-     *                                                                  not for this primary model. 'all', the default,
3524
-     *                                                                  means default where conditions will apply as
3525
-     *                                                                  normal
3526
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3527
-     * @throws EE_Error
3528
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3529
-     */
3530
-    private function _get_default_where_conditions_for_models_in_query(
3531
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3532
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3533
-        $where_query_params = array()
3534
-    ) {
3535
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3536
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3537
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3538
-                "event_espresso"), $use_default_where_conditions,
3539
-                implode(", ", $allowed_used_default_where_conditions_values)));
3540
-        }
3541
-        $universal_query_params = array();
3542
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3543
-            $universal_query_params = $this->_get_default_where_conditions();
3544
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3545
-            $universal_query_params = $this->_get_minimum_where_conditions();
3546
-        }
3547
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3548
-            $related_model = $this->get_related_model_obj($model_name);
3549
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3550
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3551
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3552
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3553
-            } else {
3554
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3555
-                continue;
3556
-            }
3557
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3558
-                $related_model_universal_where_params,
3559
-                $where_query_params,
3560
-                $related_model,
3561
-                $model_relation_path
3562
-            );
3563
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3564
-                $universal_query_params,
3565
-                $overrides
3566
-            );
3567
-        }
3568
-        return $universal_query_params;
3569
-    }
3570
-
3571
-
3572
-
3573
-    /**
3574
-     * Determines whether or not we should use default where conditions for the model in question
3575
-     * (this model, or other related models).
3576
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3577
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3578
-     * We should use default where conditions on related models when they requested to use default where conditions
3579
-     * on all models, or specifically just on other related models
3580
-     * @param      $default_where_conditions_value
3581
-     * @param bool $for_this_model false means this is for OTHER related models
3582
-     * @return bool
3583
-     */
3584
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3585
-    {
3586
-        return (
3587
-                   $for_this_model
3588
-                   && in_array(
3589
-                       $default_where_conditions_value,
3590
-                       array(
3591
-                           EEM_Base::default_where_conditions_all,
3592
-                           EEM_Base::default_where_conditions_this_only,
3593
-                           EEM_Base::default_where_conditions_minimum_others,
3594
-                       ),
3595
-                       true
3596
-                   )
3597
-               )
3598
-               || (
3599
-                   ! $for_this_model
3600
-                   && in_array(
3601
-                       $default_where_conditions_value,
3602
-                       array(
3603
-                           EEM_Base::default_where_conditions_all,
3604
-                           EEM_Base::default_where_conditions_others_only,
3605
-                       ),
3606
-                       true
3607
-                   )
3608
-               );
3609
-    }
3610
-
3611
-    /**
3612
-     * Determines whether or not we should use default minimum conditions for the model in question
3613
-     * (this model, or other related models).
3614
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3615
-     * where conditions.
3616
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3617
-     * on this model or others
3618
-     * @param      $default_where_conditions_value
3619
-     * @param bool $for_this_model false means this is for OTHER related models
3620
-     * @return bool
3621
-     */
3622
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3623
-    {
3624
-        return (
3625
-                   $for_this_model
3626
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3627
-               )
3628
-               || (
3629
-                   ! $for_this_model
3630
-                   && in_array(
3631
-                       $default_where_conditions_value,
3632
-                       array(
3633
-                           EEM_Base::default_where_conditions_minimum_others,
3634
-                           EEM_Base::default_where_conditions_minimum_all,
3635
-                       ),
3636
-                       true
3637
-                   )
3638
-               );
3639
-    }
3640
-
3641
-
3642
-    /**
3643
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3644
-     * then we also add a special where condition which allows for that model's primary key
3645
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3646
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3647
-     *
3648
-     * @param array    $default_where_conditions
3649
-     * @param array    $provided_where_conditions
3650
-     * @param EEM_Base $model
3651
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3652
-     * @return array like EEM_Base::get_all's $query_params[0]
3653
-     * @throws \EE_Error
3654
-     */
3655
-    private function _override_defaults_or_make_null_friendly(
3656
-        $default_where_conditions,
3657
-        $provided_where_conditions,
3658
-        $model,
3659
-        $model_relation_path
3660
-    ) {
3661
-        $null_friendly_where_conditions = array();
3662
-        $none_overridden = true;
3663
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3664
-        foreach ($default_where_conditions as $key => $val) {
3665
-            if (isset($provided_where_conditions[$key])) {
3666
-                $none_overridden = false;
3667
-            } else {
3668
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3669
-            }
3670
-        }
3671
-        if ($none_overridden && $default_where_conditions) {
3672
-            if ($model->has_primary_key_field()) {
3673
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3674
-                                                                                . "."
3675
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3676
-            }/*else{
2161
+	/**
2162
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2163
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2164
+	 * column
2165
+	 *
2166
+	 * @param array  $query_params   like EEM_Base::get_all's
2167
+	 * @param string $field_to_count field on model to count by (not column name)
2168
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2169
+	 *                               that by the setting $distinct to TRUE;
2170
+	 * @return int
2171
+	 * @throws \EE_Error
2172
+	 */
2173
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2174
+	{
2175
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2176
+		if ($field_to_count) {
2177
+			$field_obj = $this->field_settings_for($field_to_count);
2178
+			$column_to_count = $field_obj->get_qualified_column();
2179
+		} elseif ($this->has_primary_key_field()) {
2180
+			$pk_field_obj = $this->get_primary_key_field();
2181
+			$column_to_count = $pk_field_obj->get_qualified_column();
2182
+		} else {
2183
+			//there's no primary key
2184
+			//if we're counting distinct items, and there's no primary key,
2185
+			//we need to list out the columns for distinction;
2186
+			//otherwise we can just use star
2187
+			if ($distinct) {
2188
+				$columns_to_use = array();
2189
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2190
+					$columns_to_use[] = $field_obj->get_qualified_column();
2191
+				}
2192
+				$column_to_count = implode(',', $columns_to_use);
2193
+			} else {
2194
+				$column_to_count = '*';
2195
+			}
2196
+		}
2197
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2198
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2199
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2200
+	}
2201
+
2202
+
2203
+
2204
+	/**
2205
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2206
+	 *
2207
+	 * @param array  $query_params like EEM_Base::get_all
2208
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2209
+	 * @return float
2210
+	 * @throws \EE_Error
2211
+	 */
2212
+	public function sum($query_params, $field_to_sum = null)
2213
+	{
2214
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2215
+		if ($field_to_sum) {
2216
+			$field_obj = $this->field_settings_for($field_to_sum);
2217
+		} else {
2218
+			$field_obj = $this->get_primary_key_field();
2219
+		}
2220
+		$column_to_count = $field_obj->get_qualified_column();
2221
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2222
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2223
+		$data_type = $field_obj->get_wpdb_data_type();
2224
+		if ($data_type === '%d' || $data_type === '%s') {
2225
+			return (float)$return_value;
2226
+		} else {//must be %f
2227
+			return (float)$return_value;
2228
+		}
2229
+	}
2230
+
2231
+
2232
+
2233
+	/**
2234
+	 * Just calls the specified method on $wpdb with the given arguments
2235
+	 * Consolidates a little extra error handling code
2236
+	 *
2237
+	 * @param string $wpdb_method
2238
+	 * @param array  $arguments_to_provide
2239
+	 * @throws EE_Error
2240
+	 * @global wpdb  $wpdb
2241
+	 * @return mixed
2242
+	 */
2243
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2244
+	{
2245
+		//if we're in maintenance mode level 2, DON'T run any queries
2246
+		//because level 2 indicates the database needs updating and
2247
+		//is probably out of sync with the code
2248
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2249
+			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.",
2250
+				"event_espresso")));
2251
+		}
2252
+		/** @type WPDB $wpdb */
2253
+		global $wpdb;
2254
+		if (! method_exists($wpdb, $wpdb_method)) {
2255
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2256
+				'event_espresso'), $wpdb_method));
2257
+		}
2258
+		if (WP_DEBUG) {
2259
+			$old_show_errors_value = $wpdb->show_errors;
2260
+			$wpdb->show_errors(false);
2261
+		}
2262
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2263
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2264
+		if (WP_DEBUG) {
2265
+			$wpdb->show_errors($old_show_errors_value);
2266
+			if (! empty($wpdb->last_error)) {
2267
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2268
+			} elseif ($result === false) {
2269
+				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"',
2270
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2271
+			}
2272
+		} elseif ($result === false) {
2273
+			EE_Error::add_error(
2274
+				sprintf(
2275
+					__('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"',
2276
+						'event_espresso'),
2277
+					$wpdb_method,
2278
+					var_export($arguments_to_provide, true),
2279
+					$wpdb->last_error
2280
+				),
2281
+				__FILE__,
2282
+				__FUNCTION__,
2283
+				__LINE__
2284
+			);
2285
+		}
2286
+		return $result;
2287
+	}
2288
+
2289
+
2290
+
2291
+	/**
2292
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2293
+	 * and if there's an error tries to verify the DB is correct. Uses
2294
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2295
+	 * we should try to fix the EE core db, the addons, or just give up
2296
+	 *
2297
+	 * @param string $wpdb_method
2298
+	 * @param array  $arguments_to_provide
2299
+	 * @return mixed
2300
+	 */
2301
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2302
+	{
2303
+		/** @type WPDB $wpdb */
2304
+		global $wpdb;
2305
+		$wpdb->last_error = null;
2306
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2307
+		// was there an error running the query? but we don't care on new activations
2308
+		// (we're going to setup the DB anyway on new activations)
2309
+		if (($result === false || ! empty($wpdb->last_error))
2310
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2311
+		) {
2312
+			switch (EEM_Base::$_db_verification_level) {
2313
+				case EEM_Base::db_verified_none :
2314
+					// let's double-check core's DB
2315
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2316
+					break;
2317
+				case EEM_Base::db_verified_core :
2318
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2319
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2320
+					break;
2321
+				case EEM_Base::db_verified_addons :
2322
+					// ummmm... you in trouble
2323
+					return $result;
2324
+					break;
2325
+			}
2326
+			if (! empty($error_message)) {
2327
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2328
+				trigger_error($error_message);
2329
+			}
2330
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2331
+		}
2332
+		return $result;
2333
+	}
2334
+
2335
+
2336
+
2337
+	/**
2338
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2339
+	 * EEM_Base::$_db_verification_level
2340
+	 *
2341
+	 * @param string $wpdb_method
2342
+	 * @param array  $arguments_to_provide
2343
+	 * @return string
2344
+	 */
2345
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2346
+	{
2347
+		/** @type WPDB $wpdb */
2348
+		global $wpdb;
2349
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2350
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2351
+		$error_message = sprintf(
2352
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2353
+				'event_espresso'),
2354
+			$wpdb->last_error,
2355
+			$wpdb_method,
2356
+			wp_json_encode($arguments_to_provide)
2357
+		);
2358
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2359
+		return $error_message;
2360
+	}
2361
+
2362
+
2363
+
2364
+	/**
2365
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2366
+	 * EEM_Base::$_db_verification_level
2367
+	 *
2368
+	 * @param $wpdb_method
2369
+	 * @param $arguments_to_provide
2370
+	 * @return string
2371
+	 */
2372
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2373
+	{
2374
+		/** @type WPDB $wpdb */
2375
+		global $wpdb;
2376
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2377
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2378
+		$error_message = sprintf(
2379
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2380
+				'event_espresso'),
2381
+			$wpdb->last_error,
2382
+			$wpdb_method,
2383
+			wp_json_encode($arguments_to_provide)
2384
+		);
2385
+		EE_System::instance()->initialize_addons();
2386
+		return $error_message;
2387
+	}
2388
+
2389
+
2390
+
2391
+	/**
2392
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2393
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2394
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2395
+	 * ..."
2396
+	 *
2397
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2398
+	 * @return string
2399
+	 */
2400
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2401
+	{
2402
+		return " FROM " . $model_query_info->get_full_join_sql() .
2403
+			   $model_query_info->get_where_sql() .
2404
+			   $model_query_info->get_group_by_sql() .
2405
+			   $model_query_info->get_having_sql() .
2406
+			   $model_query_info->get_order_by_sql() .
2407
+			   $model_query_info->get_limit_sql();
2408
+	}
2409
+
2410
+
2411
+
2412
+	/**
2413
+	 * Set to easily debug the next X queries ran from this model.
2414
+	 *
2415
+	 * @param int $count
2416
+	 */
2417
+	public function show_next_x_db_queries($count = 1)
2418
+	{
2419
+		$this->_show_next_x_db_queries = $count;
2420
+	}
2421
+
2422
+
2423
+
2424
+	/**
2425
+	 * @param $sql_query
2426
+	 */
2427
+	public function show_db_query_if_previously_requested($sql_query)
2428
+	{
2429
+		if ($this->_show_next_x_db_queries > 0) {
2430
+			echo $sql_query;
2431
+			$this->_show_next_x_db_queries--;
2432
+		}
2433
+	}
2434
+
2435
+
2436
+
2437
+	/**
2438
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2439
+	 * There are the 3 cases:
2440
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2441
+	 * $otherModelObject has no ID, it is first saved.
2442
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2443
+	 * has no ID, it is first saved.
2444
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2445
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2446
+	 * join table
2447
+	 *
2448
+	 * @param        EE_Base_Class                     /int $thisModelObject
2449
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2450
+	 * @param string $relationName                     , key in EEM_Base::_relations
2451
+	 *                                                 an attendee to a group, you also want to specify which role they
2452
+	 *                                                 will have in that group. So you would use this parameter to
2453
+	 *                                                 specify array('role-column-name'=>'role-id')
2454
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2455
+	 *                                                 to for relation to methods that allow you to further specify
2456
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2457
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2458
+	 *                                                 because these will be inserted in any new rows created as well.
2459
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2460
+	 * @throws \EE_Error
2461
+	 */
2462
+	public function add_relationship_to(
2463
+		$id_or_obj,
2464
+		$other_model_id_or_obj,
2465
+		$relationName,
2466
+		$extra_join_model_fields_n_values = array()
2467
+	) {
2468
+		$relation_obj = $this->related_settings_for($relationName);
2469
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2470
+	}
2471
+
2472
+
2473
+
2474
+	/**
2475
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2476
+	 * There are the 3 cases:
2477
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2478
+	 * error
2479
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2480
+	 * an error
2481
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2482
+	 *
2483
+	 * @param        EE_Base_Class /int $id_or_obj
2484
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2485
+	 * @param string $relationName key in EEM_Base::_relations
2486
+	 * @return boolean of success
2487
+	 * @throws \EE_Error
2488
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2489
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2490
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2491
+	 *                             because these will be inserted in any new rows created as well.
2492
+	 */
2493
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2494
+	{
2495
+		$relation_obj = $this->related_settings_for($relationName);
2496
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2497
+	}
2498
+
2499
+
2500
+
2501
+	/**
2502
+	 * @param mixed           $id_or_obj
2503
+	 * @param string          $relationName
2504
+	 * @param array           $where_query_params
2505
+	 * @param EE_Base_Class[] objects to which relations were removed
2506
+	 * @return \EE_Base_Class[]
2507
+	 * @throws \EE_Error
2508
+	 */
2509
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2510
+	{
2511
+		$relation_obj = $this->related_settings_for($relationName);
2512
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2513
+	}
2514
+
2515
+
2516
+
2517
+	/**
2518
+	 * Gets all the related items of the specified $model_name, using $query_params.
2519
+	 * Note: by default, we remove the "default query params"
2520
+	 * because we want to get even deleted items etc.
2521
+	 *
2522
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2523
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2524
+	 * @param array  $query_params like EEM_Base::get_all
2525
+	 * @return EE_Base_Class[]
2526
+	 * @throws \EE_Error
2527
+	 */
2528
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2529
+	{
2530
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2531
+		$relation_settings = $this->related_settings_for($model_name);
2532
+		return $relation_settings->get_all_related($model_obj, $query_params);
2533
+	}
2534
+
2535
+
2536
+
2537
+	/**
2538
+	 * Deletes all the model objects across the relation indicated by $model_name
2539
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2540
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2541
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2542
+	 *
2543
+	 * @param EE_Base_Class|int|string $id_or_obj
2544
+	 * @param string                   $model_name
2545
+	 * @param array                    $query_params
2546
+	 * @return int how many deleted
2547
+	 * @throws \EE_Error
2548
+	 */
2549
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2550
+	{
2551
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2552
+		$relation_settings = $this->related_settings_for($model_name);
2553
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2554
+	}
2555
+
2556
+
2557
+
2558
+	/**
2559
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2560
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2561
+	 * the model objects can't be hard deleted because of blocking related model objects,
2562
+	 * just does a soft-delete on them instead.
2563
+	 *
2564
+	 * @param EE_Base_Class|int|string $id_or_obj
2565
+	 * @param string                   $model_name
2566
+	 * @param array                    $query_params
2567
+	 * @return int how many deleted
2568
+	 * @throws \EE_Error
2569
+	 */
2570
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2571
+	{
2572
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2573
+		$relation_settings = $this->related_settings_for($model_name);
2574
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2575
+	}
2576
+
2577
+
2578
+
2579
+	/**
2580
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2581
+	 * unless otherwise specified in the $query_params
2582
+	 *
2583
+	 * @param        int             /EE_Base_Class $id_or_obj
2584
+	 * @param string $model_name     like 'Event', or 'Registration'
2585
+	 * @param array  $query_params   like EEM_Base::get_all's
2586
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2587
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2588
+	 *                               that by the setting $distinct to TRUE;
2589
+	 * @return int
2590
+	 * @throws \EE_Error
2591
+	 */
2592
+	public function count_related(
2593
+		$id_or_obj,
2594
+		$model_name,
2595
+		$query_params = array(),
2596
+		$field_to_count = null,
2597
+		$distinct = false
2598
+	) {
2599
+		$related_model = $this->get_related_model_obj($model_name);
2600
+		//we're just going to use the query params on the related model's normal get_all query,
2601
+		//except add a condition to say to match the current mod
2602
+		if (! isset($query_params['default_where_conditions'])) {
2603
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2604
+		}
2605
+		$this_model_name = $this->get_this_model_name();
2606
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2607
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2608
+		return $related_model->count($query_params, $field_to_count, $distinct);
2609
+	}
2610
+
2611
+
2612
+
2613
+	/**
2614
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2615
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2616
+	 *
2617
+	 * @param        int           /EE_Base_Class $id_or_obj
2618
+	 * @param string $model_name   like 'Event', or 'Registration'
2619
+	 * @param array  $query_params like EEM_Base::get_all's
2620
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2621
+	 * @return float
2622
+	 * @throws \EE_Error
2623
+	 */
2624
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2625
+	{
2626
+		$related_model = $this->get_related_model_obj($model_name);
2627
+		if (! is_array($query_params)) {
2628
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2629
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2630
+					gettype($query_params)), '4.6.0');
2631
+			$query_params = array();
2632
+		}
2633
+		//we're just going to use the query params on the related model's normal get_all query,
2634
+		//except add a condition to say to match the current mod
2635
+		if (! isset($query_params['default_where_conditions'])) {
2636
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2637
+		}
2638
+		$this_model_name = $this->get_this_model_name();
2639
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2640
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2641
+		return $related_model->sum($query_params, $field_to_sum);
2642
+	}
2643
+
2644
+
2645
+
2646
+	/**
2647
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2648
+	 * $modelObject
2649
+	 *
2650
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2651
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2652
+	 * @param array               $query_params     like EEM_Base::get_all's
2653
+	 * @return EE_Base_Class
2654
+	 * @throws \EE_Error
2655
+	 */
2656
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2657
+	{
2658
+		$query_params['limit'] = 1;
2659
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2660
+		if ($results) {
2661
+			return array_shift($results);
2662
+		} else {
2663
+			return null;
2664
+		}
2665
+	}
2666
+
2667
+
2668
+
2669
+	/**
2670
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2671
+	 *
2672
+	 * @return string
2673
+	 */
2674
+	public function get_this_model_name()
2675
+	{
2676
+		return str_replace("EEM_", "", get_class($this));
2677
+	}
2678
+
2679
+
2680
+
2681
+	/**
2682
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2683
+	 *
2684
+	 * @return EE_Any_Foreign_Model_Name_Field
2685
+	 * @throws EE_Error
2686
+	 */
2687
+	public function get_field_containing_related_model_name()
2688
+	{
2689
+		foreach ($this->field_settings(true) as $field) {
2690
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2691
+				$field_with_model_name = $field;
2692
+			}
2693
+		}
2694
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2695
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2696
+				$this->get_this_model_name()));
2697
+		}
2698
+		return $field_with_model_name;
2699
+	}
2700
+
2701
+
2702
+
2703
+	/**
2704
+	 * Inserts a new entry into the database, for each table.
2705
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2706
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2707
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2708
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2709
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2710
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2711
+	 *
2712
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2713
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2714
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2715
+	 *                              of EEM_Base)
2716
+	 * @return int new primary key on main table that got inserted
2717
+	 * @throws EE_Error
2718
+	 */
2719
+	public function insert($field_n_values)
2720
+	{
2721
+		/**
2722
+		 * Filters the fields and their values before inserting an item using the models
2723
+		 *
2724
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2725
+		 * @param EEM_Base $model           the model used
2726
+		 */
2727
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2728
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2729
+			$main_table = $this->_get_main_table();
2730
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2731
+			if ($new_id !== false) {
2732
+				foreach ($this->_get_other_tables() as $other_table) {
2733
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2734
+				}
2735
+			}
2736
+			/**
2737
+			 * Done just after attempting to insert a new model object
2738
+			 *
2739
+			 * @param EEM_Base   $model           used
2740
+			 * @param array      $fields_n_values fields and their values
2741
+			 * @param int|string the              ID of the newly-inserted model object
2742
+			 */
2743
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2744
+			return $new_id;
2745
+		} else {
2746
+			return false;
2747
+		}
2748
+	}
2749
+
2750
+
2751
+
2752
+	/**
2753
+	 * Checks that the result would satisfy the unique indexes on this model
2754
+	 *
2755
+	 * @param array  $field_n_values
2756
+	 * @param string $action
2757
+	 * @return boolean
2758
+	 * @throws \EE_Error
2759
+	 */
2760
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2761
+	{
2762
+		foreach ($this->unique_indexes() as $index_name => $index) {
2763
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2764
+			if ($this->exists(array($uniqueness_where_params))) {
2765
+				EE_Error::add_error(
2766
+					sprintf(
2767
+						__(
2768
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2769
+							"event_espresso"
2770
+						),
2771
+						$action,
2772
+						$this->_get_class_name(),
2773
+						$index_name,
2774
+						implode(",", $index->field_names()),
2775
+						http_build_query($uniqueness_where_params)
2776
+					),
2777
+					__FILE__,
2778
+					__FUNCTION__,
2779
+					__LINE__
2780
+				);
2781
+				return false;
2782
+			}
2783
+		}
2784
+		return true;
2785
+	}
2786
+
2787
+
2788
+
2789
+	/**
2790
+	 * Checks the database for an item that conflicts (ie, if this item were
2791
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2792
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2793
+	 * can be either an EE_Base_Class or an array of fields n values
2794
+	 *
2795
+	 * @param EE_Base_Class|array $obj_or_fields_array
2796
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2797
+	 *                                                 when looking for conflicts
2798
+	 *                                                 (ie, if false, we ignore the model object's primary key
2799
+	 *                                                 when finding "conflicts". If true, it's also considered).
2800
+	 *                                                 Only works for INT primary key,
2801
+	 *                                                 STRING primary keys cannot be ignored
2802
+	 * @throws EE_Error
2803
+	 * @return EE_Base_Class|array
2804
+	 */
2805
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2806
+	{
2807
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2808
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2809
+		} elseif (is_array($obj_or_fields_array)) {
2810
+			$fields_n_values = $obj_or_fields_array;
2811
+		} else {
2812
+			throw new EE_Error(
2813
+				sprintf(
2814
+					__(
2815
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2816
+						"event_espresso"
2817
+					),
2818
+					get_class($this),
2819
+					$obj_or_fields_array
2820
+				)
2821
+			);
2822
+		}
2823
+		$query_params = array();
2824
+		if ($this->has_primary_key_field()
2825
+			&& ($include_primary_key
2826
+				|| $this->get_primary_key_field()
2827
+				   instanceof
2828
+				   EE_Primary_Key_String_Field)
2829
+			&& isset($fields_n_values[$this->primary_key_name()])
2830
+		) {
2831
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2832
+		}
2833
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2834
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2835
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2836
+		}
2837
+		//if there is nothing to base this search on, then we shouldn't find anything
2838
+		if (empty($query_params)) {
2839
+			return array();
2840
+		} else {
2841
+			return $this->get_one($query_params);
2842
+		}
2843
+	}
2844
+
2845
+
2846
+
2847
+	/**
2848
+	 * Like count, but is optimized and returns a boolean instead of an int
2849
+	 *
2850
+	 * @param array $query_params
2851
+	 * @return boolean
2852
+	 * @throws \EE_Error
2853
+	 */
2854
+	public function exists($query_params)
2855
+	{
2856
+		$query_params['limit'] = 1;
2857
+		return $this->count($query_params) > 0;
2858
+	}
2859
+
2860
+
2861
+
2862
+	/**
2863
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2864
+	 *
2865
+	 * @param int|string $id
2866
+	 * @return boolean
2867
+	 * @throws \EE_Error
2868
+	 */
2869
+	public function exists_by_ID($id)
2870
+	{
2871
+		return $this->exists(
2872
+			array(
2873
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2874
+				array(
2875
+					$this->primary_key_name() => $id,
2876
+				),
2877
+			)
2878
+		);
2879
+	}
2880
+
2881
+
2882
+
2883
+	/**
2884
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2885
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2886
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2887
+	 * on the main table)
2888
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2889
+	 * cases where we want to call it directly rather than via insert().
2890
+	 *
2891
+	 * @access   protected
2892
+	 * @param EE_Table_Base $table
2893
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2894
+	 *                                       float
2895
+	 * @param int           $new_id          for now we assume only int keys
2896
+	 * @throws EE_Error
2897
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2898
+	 * @return int ID of new row inserted, or FALSE on failure
2899
+	 */
2900
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2901
+	{
2902
+		global $wpdb;
2903
+		$insertion_col_n_values = array();
2904
+		$format_for_insertion = array();
2905
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2906
+		foreach ($fields_on_table as $field_name => $field_obj) {
2907
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2908
+			if ($field_obj->is_auto_increment()) {
2909
+				continue;
2910
+			}
2911
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2912
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2913
+			if ($prepared_value !== null) {
2914
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2915
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2916
+			}
2917
+		}
2918
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2919
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2920
+			//so add the fk to the main table as a column
2921
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2922
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2923
+		}
2924
+		//insert the new entry
2925
+		$result = $this->_do_wpdb_query('insert',
2926
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2927
+		if ($result === false) {
2928
+			return false;
2929
+		}
2930
+		//ok, now what do we return for the ID of the newly-inserted thing?
2931
+		if ($this->has_primary_key_field()) {
2932
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2933
+				return $wpdb->insert_id;
2934
+			} else {
2935
+				//it's not an auto-increment primary key, so
2936
+				//it must have been supplied
2937
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2938
+			}
2939
+		} else {
2940
+			//we can't return a  primary key because there is none. instead return
2941
+			//a unique string indicating this model
2942
+			return $this->get_index_primary_key_string($fields_n_values);
2943
+		}
2944
+	}
2945
+
2946
+
2947
+
2948
+	/**
2949
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2950
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2951
+	 * and there is no default, we pass it along. WPDB will take care of it)
2952
+	 *
2953
+	 * @param EE_Model_Field_Base $field_obj
2954
+	 * @param array               $fields_n_values
2955
+	 * @return mixed string|int|float depending on what the table column will be expecting
2956
+	 * @throws \EE_Error
2957
+	 */
2958
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2959
+	{
2960
+		//if this field doesn't allow nullable, don't allow it
2961
+		if (
2962
+			! $field_obj->is_nullable()
2963
+			&& (
2964
+				! isset($fields_n_values[$field_obj->get_name()])
2965
+				|| $fields_n_values[$field_obj->get_name()] === null
2966
+			)
2967
+		) {
2968
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2969
+		}
2970
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2971
+			? $fields_n_values[$field_obj->get_name()]
2972
+			: null;
2973
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2974
+	}
2975
+
2976
+
2977
+
2978
+	/**
2979
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2980
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2981
+	 * the field's prepare_for_set() method.
2982
+	 *
2983
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2984
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2985
+	 *                                   top of file)
2986
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2987
+	 *                                   $value is a custom selection
2988
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2989
+	 */
2990
+	private function _prepare_value_for_use_in_db($value, $field)
2991
+	{
2992
+		if ($field && $field instanceof EE_Model_Field_Base) {
2993
+			switch ($this->_values_already_prepared_by_model_object) {
2994
+				/** @noinspection PhpMissingBreakStatementInspection */
2995
+				case self::not_prepared_by_model_object:
2996
+					$value = $field->prepare_for_set($value);
2997
+				//purposefully left out "return"
2998
+				case self::prepared_by_model_object:
2999
+					$value = $field->prepare_for_use_in_db($value);
3000
+				case self::prepared_for_use_in_db:
3001
+					//leave the value alone
3002
+			}
3003
+			return $value;
3004
+		} else {
3005
+			return $value;
3006
+		}
3007
+	}
3008
+
3009
+
3010
+
3011
+	/**
3012
+	 * Returns the main table on this model
3013
+	 *
3014
+	 * @return EE_Primary_Table
3015
+	 * @throws EE_Error
3016
+	 */
3017
+	protected function _get_main_table()
3018
+	{
3019
+		foreach ($this->_tables as $table) {
3020
+			if ($table instanceof EE_Primary_Table) {
3021
+				return $table;
3022
+			}
3023
+		}
3024
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3025
+			'event_espresso'), get_class($this)));
3026
+	}
3027
+
3028
+
3029
+
3030
+	/**
3031
+	 * table
3032
+	 * returns EE_Primary_Table table name
3033
+	 *
3034
+	 * @return string
3035
+	 * @throws \EE_Error
3036
+	 */
3037
+	public function table()
3038
+	{
3039
+		return $this->_get_main_table()->get_table_name();
3040
+	}
3041
+
3042
+
3043
+
3044
+	/**
3045
+	 * table
3046
+	 * returns first EE_Secondary_Table table name
3047
+	 *
3048
+	 * @return string
3049
+	 */
3050
+	public function second_table()
3051
+	{
3052
+		// grab second table from tables array
3053
+		$second_table = end($this->_tables);
3054
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3055
+	}
3056
+
3057
+
3058
+
3059
+	/**
3060
+	 * get_table_obj_by_alias
3061
+	 * returns table name given it's alias
3062
+	 *
3063
+	 * @param string $table_alias
3064
+	 * @return EE_Primary_Table | EE_Secondary_Table
3065
+	 */
3066
+	public function get_table_obj_by_alias($table_alias = '')
3067
+	{
3068
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3069
+	}
3070
+
3071
+
3072
+
3073
+	/**
3074
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3075
+	 *
3076
+	 * @return EE_Secondary_Table[]
3077
+	 */
3078
+	protected function _get_other_tables()
3079
+	{
3080
+		$other_tables = array();
3081
+		foreach ($this->_tables as $table_alias => $table) {
3082
+			if ($table instanceof EE_Secondary_Table) {
3083
+				$other_tables[$table_alias] = $table;
3084
+			}
3085
+		}
3086
+		return $other_tables;
3087
+	}
3088
+
3089
+
3090
+
3091
+	/**
3092
+	 * Finds all the fields that correspond to the given table
3093
+	 *
3094
+	 * @param string $table_alias , array key in EEM_Base::_tables
3095
+	 * @return EE_Model_Field_Base[]
3096
+	 */
3097
+	public function _get_fields_for_table($table_alias)
3098
+	{
3099
+		return $this->_fields[$table_alias];
3100
+	}
3101
+
3102
+
3103
+
3104
+	/**
3105
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3106
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3107
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3108
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3109
+	 * related Registration, Transaction, and Payment models.
3110
+	 *
3111
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3112
+	 * @return EE_Model_Query_Info_Carrier
3113
+	 * @throws \EE_Error
3114
+	 */
3115
+	public function _extract_related_models_from_query($query_params)
3116
+	{
3117
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3118
+		if (array_key_exists(0, $query_params)) {
3119
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3120
+		}
3121
+		if (array_key_exists('group_by', $query_params)) {
3122
+			if (is_array($query_params['group_by'])) {
3123
+				$this->_extract_related_models_from_sub_params_array_values(
3124
+					$query_params['group_by'],
3125
+					$query_info_carrier,
3126
+					'group_by'
3127
+				);
3128
+			} elseif (! empty ($query_params['group_by'])) {
3129
+				$this->_extract_related_model_info_from_query_param(
3130
+					$query_params['group_by'],
3131
+					$query_info_carrier,
3132
+					'group_by'
3133
+				);
3134
+			}
3135
+		}
3136
+		if (array_key_exists('having', $query_params)) {
3137
+			$this->_extract_related_models_from_sub_params_array_keys(
3138
+				$query_params[0],
3139
+				$query_info_carrier,
3140
+				'having'
3141
+			);
3142
+		}
3143
+		if (array_key_exists('order_by', $query_params)) {
3144
+			if (is_array($query_params['order_by'])) {
3145
+				$this->_extract_related_models_from_sub_params_array_keys(
3146
+					$query_params['order_by'],
3147
+					$query_info_carrier,
3148
+					'order_by'
3149
+				);
3150
+			} elseif (! empty($query_params['order_by'])) {
3151
+				$this->_extract_related_model_info_from_query_param(
3152
+					$query_params['order_by'],
3153
+					$query_info_carrier,
3154
+					'order_by'
3155
+				);
3156
+			}
3157
+		}
3158
+		if (array_key_exists('force_join', $query_params)) {
3159
+			$this->_extract_related_models_from_sub_params_array_values(
3160
+				$query_params['force_join'],
3161
+				$query_info_carrier,
3162
+				'force_join'
3163
+			);
3164
+		}
3165
+		return $query_info_carrier;
3166
+	}
3167
+
3168
+
3169
+
3170
+	/**
3171
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3172
+	 *
3173
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3174
+	 *                                                      $query_params['having']
3175
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3176
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3177
+	 * @throws EE_Error
3178
+	 * @return \EE_Model_Query_Info_Carrier
3179
+	 */
3180
+	private function _extract_related_models_from_sub_params_array_keys(
3181
+		$sub_query_params,
3182
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3183
+		$query_param_type
3184
+	) {
3185
+		if (! empty($sub_query_params)) {
3186
+			$sub_query_params = (array)$sub_query_params;
3187
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3188
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3189
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3190
+					$query_param_type);
3191
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3192
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3193
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3194
+				//of array('Registration.TXN_ID'=>23)
3195
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3196
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3197
+					if (! is_array($possibly_array_of_params)) {
3198
+						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'))",
3199
+							"event_espresso"),
3200
+							$param, $possibly_array_of_params));
3201
+					} else {
3202
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3203
+							$model_query_info_carrier, $query_param_type);
3204
+					}
3205
+				} elseif ($query_param_type === 0 //ie WHERE
3206
+						  && is_array($possibly_array_of_params)
3207
+						  && isset($possibly_array_of_params[2])
3208
+						  && $possibly_array_of_params[2] == true
3209
+				) {
3210
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3211
+					//indicating that $possible_array_of_params[1] is actually a field name,
3212
+					//from which we should extract query parameters!
3213
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3214
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3215
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3216
+					}
3217
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3218
+						$model_query_info_carrier, $query_param_type);
3219
+				}
3220
+			}
3221
+		}
3222
+		return $model_query_info_carrier;
3223
+	}
3224
+
3225
+
3226
+
3227
+	/**
3228
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3229
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3230
+	 *
3231
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3232
+	 *                                                      $query_params['having']
3233
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3234
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3235
+	 * @throws EE_Error
3236
+	 * @return \EE_Model_Query_Info_Carrier
3237
+	 */
3238
+	private function _extract_related_models_from_sub_params_array_values(
3239
+		$sub_query_params,
3240
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3241
+		$query_param_type
3242
+	) {
3243
+		if (! empty($sub_query_params)) {
3244
+			if (! is_array($sub_query_params)) {
3245
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3246
+					$sub_query_params));
3247
+			}
3248
+			foreach ($sub_query_params as $param) {
3249
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3250
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3251
+					$query_param_type);
3252
+			}
3253
+		}
3254
+		return $model_query_info_carrier;
3255
+	}
3256
+
3257
+
3258
+
3259
+	/**
3260
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3261
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3262
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3263
+	 * but use them in a different order. Eg, we need to know what models we are querying
3264
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3265
+	 * other models before we can finalize the where clause SQL.
3266
+	 *
3267
+	 * @param array $query_params
3268
+	 * @throws EE_Error
3269
+	 * @return EE_Model_Query_Info_Carrier
3270
+	 */
3271
+	public function _create_model_query_info_carrier($query_params)
3272
+	{
3273
+		if (! is_array($query_params)) {
3274
+			EE_Error::doing_it_wrong(
3275
+				'EEM_Base::_create_model_query_info_carrier',
3276
+				sprintf(
3277
+					__(
3278
+						'$query_params should be an array, you passed a variable of type %s',
3279
+						'event_espresso'
3280
+					),
3281
+					gettype($query_params)
3282
+				),
3283
+				'4.6.0'
3284
+			);
3285
+			$query_params = array();
3286
+		}
3287
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3288
+		//first check if we should alter the query to account for caps or not
3289
+		//because the caps might require us to do extra joins
3290
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3291
+			$query_params[0] = $where_query_params = array_replace_recursive(
3292
+				$where_query_params,
3293
+				$this->caps_where_conditions(
3294
+					$query_params['caps']
3295
+				)
3296
+			);
3297
+		}
3298
+		$query_object = $this->_extract_related_models_from_query($query_params);
3299
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3300
+		foreach ($where_query_params as $key => $value) {
3301
+			if (is_int($key)) {
3302
+				throw new EE_Error(
3303
+					sprintf(
3304
+						__(
3305
+							"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.",
3306
+							"event_espresso"
3307
+						),
3308
+						$key,
3309
+						var_export($value, true),
3310
+						var_export($query_params, true),
3311
+						get_class($this)
3312
+					)
3313
+				);
3314
+			}
3315
+		}
3316
+		if (
3317
+			array_key_exists('default_where_conditions', $query_params)
3318
+			&& ! empty($query_params['default_where_conditions'])
3319
+		) {
3320
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3321
+		} else {
3322
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3323
+		}
3324
+		$where_query_params = array_merge(
3325
+			$this->_get_default_where_conditions_for_models_in_query(
3326
+				$query_object,
3327
+				$use_default_where_conditions,
3328
+				$where_query_params
3329
+			),
3330
+			$where_query_params
3331
+		);
3332
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3333
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3334
+		// So we need to setup a subquery and use that for the main join.
3335
+		// Note for now this only works on the primary table for the model.
3336
+		// So for instance, you could set the limit array like this:
3337
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3338
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3339
+			$query_object->set_main_model_join_sql(
3340
+				$this->_construct_limit_join_select(
3341
+					$query_params['on_join_limit'][0],
3342
+					$query_params['on_join_limit'][1]
3343
+				)
3344
+			);
3345
+		}
3346
+		//set limit
3347
+		if (array_key_exists('limit', $query_params)) {
3348
+			if (is_array($query_params['limit'])) {
3349
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3350
+					$e = sprintf(
3351
+						__(
3352
+							"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)",
3353
+							"event_espresso"
3354
+						),
3355
+						http_build_query($query_params['limit'])
3356
+					);
3357
+					throw new EE_Error($e . "|" . $e);
3358
+				}
3359
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3360
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3361
+			} elseif (! empty ($query_params['limit'])) {
3362
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3363
+			}
3364
+		}
3365
+		//set order by
3366
+		if (array_key_exists('order_by', $query_params)) {
3367
+			if (is_array($query_params['order_by'])) {
3368
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3369
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3370
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3371
+				if (array_key_exists('order', $query_params)) {
3372
+					throw new EE_Error(
3373
+						sprintf(
3374
+							__(
3375
+								"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 ",
3376
+								"event_espresso"
3377
+							),
3378
+							get_class($this),
3379
+							implode(", ", array_keys($query_params['order_by'])),
3380
+							implode(", ", $query_params['order_by']),
3381
+							$query_params['order']
3382
+						)
3383
+					);
3384
+				}
3385
+				$this->_extract_related_models_from_sub_params_array_keys(
3386
+					$query_params['order_by'],
3387
+					$query_object,
3388
+					'order_by'
3389
+				);
3390
+				//assume it's an array of fields to order by
3391
+				$order_array = array();
3392
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3393
+					$order = $this->_extract_order($order);
3394
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3395
+				}
3396
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3397
+			} elseif (! empty ($query_params['order_by'])) {
3398
+				$this->_extract_related_model_info_from_query_param(
3399
+					$query_params['order_by'],
3400
+					$query_object,
3401
+					'order',
3402
+					$query_params['order_by']
3403
+				);
3404
+				$order = isset($query_params['order'])
3405
+					? $this->_extract_order($query_params['order'])
3406
+					: 'DESC';
3407
+				$query_object->set_order_by_sql(
3408
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3409
+				);
3410
+			}
3411
+		}
3412
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3413
+		if (! array_key_exists('order_by', $query_params)
3414
+			&& array_key_exists('order', $query_params)
3415
+			&& ! empty($query_params['order'])
3416
+		) {
3417
+			$pk_field = $this->get_primary_key_field();
3418
+			$order = $this->_extract_order($query_params['order']);
3419
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3420
+		}
3421
+		//set group by
3422
+		if (array_key_exists('group_by', $query_params)) {
3423
+			if (is_array($query_params['group_by'])) {
3424
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3425
+				$group_by_array = array();
3426
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3427
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3428
+				}
3429
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3430
+			} elseif (! empty ($query_params['group_by'])) {
3431
+				$query_object->set_group_by_sql(
3432
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3433
+				);
3434
+			}
3435
+		}
3436
+		//set having
3437
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3438
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3439
+		}
3440
+		//now, just verify they didn't pass anything wack
3441
+		foreach ($query_params as $query_key => $query_value) {
3442
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3443
+				throw new EE_Error(
3444
+					sprintf(
3445
+						__(
3446
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3447
+							'event_espresso'
3448
+						),
3449
+						$query_key,
3450
+						get_class($this),
3451
+						//						print_r( $this->_allowed_query_params, TRUE )
3452
+						implode(',', $this->_allowed_query_params)
3453
+					)
3454
+				);
3455
+			}
3456
+		}
3457
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3458
+		if (empty($main_model_join_sql)) {
3459
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3460
+		}
3461
+		return $query_object;
3462
+	}
3463
+
3464
+
3465
+
3466
+	/**
3467
+	 * Gets the where conditions that should be imposed on the query based on the
3468
+	 * context (eg reading frontend, backend, edit or delete).
3469
+	 *
3470
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3471
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3472
+	 * @throws \EE_Error
3473
+	 */
3474
+	public function caps_where_conditions($context = self::caps_read)
3475
+	{
3476
+		EEM_Base::verify_is_valid_cap_context($context);
3477
+		$cap_where_conditions = array();
3478
+		$cap_restrictions = $this->caps_missing($context);
3479
+		/**
3480
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3481
+		 */
3482
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3483
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3484
+				$restriction_if_no_cap->get_default_where_conditions());
3485
+		}
3486
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3487
+			$cap_restrictions);
3488
+	}
3489
+
3490
+
3491
+
3492
+	/**
3493
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3494
+	 * otherwise throws an exception
3495
+	 *
3496
+	 * @param string $should_be_order_string
3497
+	 * @return string either ASC, asc, DESC or desc
3498
+	 * @throws EE_Error
3499
+	 */
3500
+	private function _extract_order($should_be_order_string)
3501
+	{
3502
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3503
+			return $should_be_order_string;
3504
+		} else {
3505
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3506
+				"event_espresso"), get_class($this), $should_be_order_string));
3507
+		}
3508
+	}
3509
+
3510
+
3511
+
3512
+	/**
3513
+	 * Looks at all the models which are included in this query, and asks each
3514
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3515
+	 * so they can be merged
3516
+	 *
3517
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3518
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3519
+	 *                                                                  'none' means NO default where conditions will
3520
+	 *                                                                  be used AT ALL during this query.
3521
+	 *                                                                  'other_models_only' means default where
3522
+	 *                                                                  conditions from other models will be used, but
3523
+	 *                                                                  not for this primary model. 'all', the default,
3524
+	 *                                                                  means default where conditions will apply as
3525
+	 *                                                                  normal
3526
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3527
+	 * @throws EE_Error
3528
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3529
+	 */
3530
+	private function _get_default_where_conditions_for_models_in_query(
3531
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3532
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3533
+		$where_query_params = array()
3534
+	) {
3535
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3536
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3537
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3538
+				"event_espresso"), $use_default_where_conditions,
3539
+				implode(", ", $allowed_used_default_where_conditions_values)));
3540
+		}
3541
+		$universal_query_params = array();
3542
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3543
+			$universal_query_params = $this->_get_default_where_conditions();
3544
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3545
+			$universal_query_params = $this->_get_minimum_where_conditions();
3546
+		}
3547
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3548
+			$related_model = $this->get_related_model_obj($model_name);
3549
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3550
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3551
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3552
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3553
+			} else {
3554
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3555
+				continue;
3556
+			}
3557
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3558
+				$related_model_universal_where_params,
3559
+				$where_query_params,
3560
+				$related_model,
3561
+				$model_relation_path
3562
+			);
3563
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3564
+				$universal_query_params,
3565
+				$overrides
3566
+			);
3567
+		}
3568
+		return $universal_query_params;
3569
+	}
3570
+
3571
+
3572
+
3573
+	/**
3574
+	 * Determines whether or not we should use default where conditions for the model in question
3575
+	 * (this model, or other related models).
3576
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3577
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3578
+	 * We should use default where conditions on related models when they requested to use default where conditions
3579
+	 * on all models, or specifically just on other related models
3580
+	 * @param      $default_where_conditions_value
3581
+	 * @param bool $for_this_model false means this is for OTHER related models
3582
+	 * @return bool
3583
+	 */
3584
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3585
+	{
3586
+		return (
3587
+				   $for_this_model
3588
+				   && in_array(
3589
+					   $default_where_conditions_value,
3590
+					   array(
3591
+						   EEM_Base::default_where_conditions_all,
3592
+						   EEM_Base::default_where_conditions_this_only,
3593
+						   EEM_Base::default_where_conditions_minimum_others,
3594
+					   ),
3595
+					   true
3596
+				   )
3597
+			   )
3598
+			   || (
3599
+				   ! $for_this_model
3600
+				   && in_array(
3601
+					   $default_where_conditions_value,
3602
+					   array(
3603
+						   EEM_Base::default_where_conditions_all,
3604
+						   EEM_Base::default_where_conditions_others_only,
3605
+					   ),
3606
+					   true
3607
+				   )
3608
+			   );
3609
+	}
3610
+
3611
+	/**
3612
+	 * Determines whether or not we should use default minimum conditions for the model in question
3613
+	 * (this model, or other related models).
3614
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3615
+	 * where conditions.
3616
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3617
+	 * on this model or others
3618
+	 * @param      $default_where_conditions_value
3619
+	 * @param bool $for_this_model false means this is for OTHER related models
3620
+	 * @return bool
3621
+	 */
3622
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3623
+	{
3624
+		return (
3625
+				   $for_this_model
3626
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3627
+			   )
3628
+			   || (
3629
+				   ! $for_this_model
3630
+				   && in_array(
3631
+					   $default_where_conditions_value,
3632
+					   array(
3633
+						   EEM_Base::default_where_conditions_minimum_others,
3634
+						   EEM_Base::default_where_conditions_minimum_all,
3635
+					   ),
3636
+					   true
3637
+				   )
3638
+			   );
3639
+	}
3640
+
3641
+
3642
+	/**
3643
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3644
+	 * then we also add a special where condition which allows for that model's primary key
3645
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3646
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3647
+	 *
3648
+	 * @param array    $default_where_conditions
3649
+	 * @param array    $provided_where_conditions
3650
+	 * @param EEM_Base $model
3651
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3652
+	 * @return array like EEM_Base::get_all's $query_params[0]
3653
+	 * @throws \EE_Error
3654
+	 */
3655
+	private function _override_defaults_or_make_null_friendly(
3656
+		$default_where_conditions,
3657
+		$provided_where_conditions,
3658
+		$model,
3659
+		$model_relation_path
3660
+	) {
3661
+		$null_friendly_where_conditions = array();
3662
+		$none_overridden = true;
3663
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3664
+		foreach ($default_where_conditions as $key => $val) {
3665
+			if (isset($provided_where_conditions[$key])) {
3666
+				$none_overridden = false;
3667
+			} else {
3668
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3669
+			}
3670
+		}
3671
+		if ($none_overridden && $default_where_conditions) {
3672
+			if ($model->has_primary_key_field()) {
3673
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3674
+																				. "."
3675
+																				. $model->primary_key_name()] = array('IS NULL');
3676
+			}/*else{
3677 3677
 				//@todo NO PK, use other defaults
3678 3678
 			}*/
3679
-        }
3680
-        return $null_friendly_where_conditions;
3681
-    }
3682
-
3683
-
3684
-
3685
-    /**
3686
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3687
-     * default where conditions on all get_all, update, and delete queries done by this model.
3688
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3689
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3690
-     *
3691
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3692
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3693
-     */
3694
-    private function _get_default_where_conditions($model_relation_path = null)
3695
-    {
3696
-        if ($this->_ignore_where_strategy) {
3697
-            return array();
3698
-        }
3699
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3700
-    }
3701
-
3702
-
3703
-
3704
-    /**
3705
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3706
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3707
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3708
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3709
-     * Similar to _get_default_where_conditions
3710
-     *
3711
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3712
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3713
-     */
3714
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3715
-    {
3716
-        if ($this->_ignore_where_strategy) {
3717
-            return array();
3718
-        }
3719
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3720
-    }
3721
-
3722
-
3723
-
3724
-    /**
3725
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3726
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3727
-     *
3728
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3729
-     * @return string
3730
-     * @throws \EE_Error
3731
-     */
3732
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3733
-    {
3734
-        $selects = $this->_get_columns_to_select_for_this_model();
3735
-        foreach (
3736
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3737
-            $name_of_other_model_included
3738
-        ) {
3739
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3740
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3741
-            foreach ($other_model_selects as $key => $value) {
3742
-                $selects[] = $value;
3743
-            }
3744
-        }
3745
-        return implode(", ", $selects);
3746
-    }
3747
-
3748
-
3749
-
3750
-    /**
3751
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3752
-     * So that's going to be the columns for all the fields on the model
3753
-     *
3754
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3755
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3756
-     */
3757
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3758
-    {
3759
-        $fields = $this->field_settings();
3760
-        $selects = array();
3761
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3762
-            $this->get_this_model_name());
3763
-        foreach ($fields as $field_obj) {
3764
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3765
-                         . $field_obj->get_table_alias()
3766
-                         . "."
3767
-                         . $field_obj->get_table_column()
3768
-                         . " AS '"
3769
-                         . $table_alias_with_model_relation_chain_prefix
3770
-                         . $field_obj->get_table_alias()
3771
-                         . "."
3772
-                         . $field_obj->get_table_column()
3773
-                         . "'";
3774
-        }
3775
-        //make sure we are also getting the PKs of each table
3776
-        $tables = $this->get_tables();
3777
-        if (count($tables) > 1) {
3778
-            foreach ($tables as $table_obj) {
3779
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3780
-                                       . $table_obj->get_fully_qualified_pk_column();
3781
-                if (! in_array($qualified_pk_column, $selects)) {
3782
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3783
-                }
3784
-            }
3785
-        }
3786
-        return $selects;
3787
-    }
3788
-
3789
-
3790
-
3791
-    /**
3792
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3793
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3794
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3795
-     * SQL for joining, and the data types
3796
-     *
3797
-     * @param null|string                 $original_query_param
3798
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3799
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3800
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3801
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3802
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3803
-     *                                                          or 'Registration's
3804
-     * @param string                      $original_query_param what it originally was (eg
3805
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3806
-     *                                                          matches $query_param
3807
-     * @throws EE_Error
3808
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3809
-     */
3810
-    private function _extract_related_model_info_from_query_param(
3811
-        $query_param,
3812
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3813
-        $query_param_type,
3814
-        $original_query_param = null
3815
-    ) {
3816
-        if ($original_query_param === null) {
3817
-            $original_query_param = $query_param;
3818
-        }
3819
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3820
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3821
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3822
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3823
-        //check to see if we have a field on this model
3824
-        $this_model_fields = $this->field_settings(true);
3825
-        if (array_key_exists($query_param, $this_model_fields)) {
3826
-            if ($allow_fields) {
3827
-                return;
3828
-            } else {
3829
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3830
-                    "event_espresso"),
3831
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3832
-            }
3833
-        } //check if this is a special logic query param
3834
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3835
-            if ($allow_logic_query_params) {
3836
-                return;
3837
-            } else {
3838
-                throw new EE_Error(
3839
-                    sprintf(
3840
-                        __('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',
3841
-                            'event_espresso'),
3842
-                        implode('", "', $this->_logic_query_param_keys),
3843
-                        $query_param,
3844
-                        get_class($this),
3845
-                        '<br />',
3846
-                        "\t"
3847
-                        . ' $passed_in_query_info = <pre>'
3848
-                        . print_r($passed_in_query_info, true)
3849
-                        . '</pre>'
3850
-                        . "\n\t"
3851
-                        . ' $query_param_type = '
3852
-                        . $query_param_type
3853
-                        . "\n\t"
3854
-                        . ' $original_query_param = '
3855
-                        . $original_query_param
3856
-                    )
3857
-                );
3858
-            }
3859
-        } //check if it's a custom selection
3860
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3861
-            return;
3862
-        }
3863
-        //check if has a model name at the beginning
3864
-        //and
3865
-        //check if it's a field on a related model
3866
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3867
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3868
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3869
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3870
-                if ($query_param === '') {
3871
-                    //nothing left to $query_param
3872
-                    //we should actually end in a field name, not a model like this!
3873
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3874
-                        "event_espresso"),
3875
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3876
-                } else {
3877
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3878
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3879
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3880
-                    return;
3881
-                }
3882
-            } elseif ($query_param === $valid_related_model_name) {
3883
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3884
-                return;
3885
-            }
3886
-        }
3887
-        //ok so $query_param didn't start with a model name
3888
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3889
-        //it's wack, that's what it is
3890
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3891
-            "event_espresso"),
3892
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3893
-    }
3894
-
3895
-
3896
-
3897
-    /**
3898
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3899
-     * and store it on $passed_in_query_info
3900
-     *
3901
-     * @param string                      $model_name
3902
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3903
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3904
-     *                                                          model and $model_name. Eg, if we are querying Event,
3905
-     *                                                          and are adding a join to 'Payment' with the original
3906
-     *                                                          query param key
3907
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3908
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3909
-     *                                                          Payment wants to add default query params so that it
3910
-     *                                                          will know what models to prepend onto its default query
3911
-     *                                                          params or in case it wants to rename tables (in case
3912
-     *                                                          there are multiple joins to the same table)
3913
-     * @return void
3914
-     * @throws \EE_Error
3915
-     */
3916
-    private function _add_join_to_model(
3917
-        $model_name,
3918
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3919
-        $original_query_param
3920
-    ) {
3921
-        $relation_obj = $this->related_settings_for($model_name);
3922
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3923
-        //check if the relation is HABTM, because then we're essentially doing two joins
3924
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3925
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3926
-            $join_model_obj = $relation_obj->get_join_model();
3927
-            //replace the model specified with the join model for this relation chain, whi
3928
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3929
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3930
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3931
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3932
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3933
-            $passed_in_query_info->merge($new_query_info);
3934
-        }
3935
-        //now just join to the other table pointed to by the relation object, and add its data types
3936
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3937
-            array($model_relation_chain => $model_name),
3938
-            $relation_obj->get_join_statement($model_relation_chain));
3939
-        $passed_in_query_info->merge($new_query_info);
3940
-    }
3941
-
3942
-
3943
-
3944
-    /**
3945
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3946
-     *
3947
-     * @param array $where_params like EEM_Base::get_all
3948
-     * @return string of SQL
3949
-     * @throws \EE_Error
3950
-     */
3951
-    private function _construct_where_clause($where_params)
3952
-    {
3953
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3954
-        if ($SQL) {
3955
-            return " WHERE " . $SQL;
3956
-        } else {
3957
-            return '';
3958
-        }
3959
-    }
3960
-
3961
-
3962
-
3963
-    /**
3964
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3965
-     * and should be passed HAVING parameters, not WHERE parameters
3966
-     *
3967
-     * @param array $having_params
3968
-     * @return string
3969
-     * @throws \EE_Error
3970
-     */
3971
-    private function _construct_having_clause($having_params)
3972
-    {
3973
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3974
-        if ($SQL) {
3975
-            return " HAVING " . $SQL;
3976
-        } else {
3977
-            return '';
3978
-        }
3979
-    }
3980
-
3981
-
3982
-
3983
-    /**
3984
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3985
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3986
-     * EEM_Attendee.
3987
-     *
3988
-     * @param string $field_name
3989
-     * @param string $model_name
3990
-     * @return EE_Model_Field_Base
3991
-     * @throws EE_Error
3992
-     */
3993
-    protected function _get_field_on_model($field_name, $model_name)
3994
-    {
3995
-        $model_class = 'EEM_' . $model_name;
3996
-        $model_filepath = $model_class . ".model.php";
3997
-        if (is_readable($model_filepath)) {
3998
-            require_once($model_filepath);
3999
-            $model_instance = call_user_func($model_name . "::instance");
4000
-            /* @var $model_instance EEM_Base */
4001
-            return $model_instance->field_settings_for($field_name);
4002
-        } else {
4003
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
4004
-                'event_espresso'), $model_name, $model_class, $model_filepath));
4005
-        }
4006
-    }
4007
-
4008
-
4009
-
4010
-    /**
4011
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4012
-     * Event_Meta.meta_value = 'foo'))"
4013
-     *
4014
-     * @param array  $where_params see EEM_Base::get_all for documentation
4015
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4016
-     * @throws EE_Error
4017
-     * @return string of SQL
4018
-     */
4019
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4020
-    {
4021
-        $where_clauses = array();
4022
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4023
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4024
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4025
-                switch ($query_param) {
4026
-                    case 'not':
4027
-                    case 'NOT':
4028
-                        $where_clauses[] = "! ("
4029
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4030
-                                $glue)
4031
-                                           . ")";
4032
-                        break;
4033
-                    case 'and':
4034
-                    case 'AND':
4035
-                        $where_clauses[] = " ("
4036
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4037
-                                ' AND ')
4038
-                                           . ")";
4039
-                        break;
4040
-                    case 'or':
4041
-                    case 'OR':
4042
-                        $where_clauses[] = " ("
4043
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4044
-                                ' OR ')
4045
-                                           . ")";
4046
-                        break;
4047
-                }
4048
-            } else {
4049
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4050
-                //if it's not a normal field, maybe it's a custom selection?
4051
-                if (! $field_obj) {
4052
-                    if (isset($this->_custom_selections[$query_param][1])) {
4053
-                        $field_obj = $this->_custom_selections[$query_param][1];
4054
-                    } else {
4055
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4056
-                            "event_espresso"), $query_param));
4057
-                    }
4058
-                }
4059
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4060
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4061
-            }
4062
-        }
4063
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4064
-    }
4065
-
4066
-
4067
-
4068
-    /**
4069
-     * Takes the input parameter and extract the table name (alias) and column name
4070
-     *
4071
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4072
-     * @throws EE_Error
4073
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4074
-     */
4075
-    private function _deduce_column_name_from_query_param($query_param)
4076
-    {
4077
-        $field = $this->_deduce_field_from_query_param($query_param);
4078
-        if ($field) {
4079
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4080
-                $query_param);
4081
-            return $table_alias_prefix . $field->get_qualified_column();
4082
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4083
-            //maybe it's custom selection item?
4084
-            //if so, just use it as the "column name"
4085
-            return $query_param;
4086
-        } else {
4087
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4088
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4089
-        }
4090
-    }
4091
-
4092
-
4093
-
4094
-    /**
4095
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4096
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4097
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4098
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4099
-     *
4100
-     * @param string $condition_query_param_key
4101
-     * @return string
4102
-     */
4103
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4104
-    {
4105
-        $pos_of_star = strpos($condition_query_param_key, '*');
4106
-        if ($pos_of_star === false) {
4107
-            return $condition_query_param_key;
4108
-        } else {
4109
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4110
-            return $condition_query_param_sans_star;
4111
-        }
4112
-    }
4113
-
4114
-
4115
-
4116
-    /**
4117
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4118
-     *
4119
-     * @param                            mixed      array | string    $op_and_value
4120
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4121
-     * @throws EE_Error
4122
-     * @return string
4123
-     */
4124
-    private function _construct_op_and_value($op_and_value, $field_obj)
4125
-    {
4126
-        if (is_array($op_and_value)) {
4127
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4128
-            if (! $operator) {
4129
-                $php_array_like_string = array();
4130
-                foreach ($op_and_value as $key => $value) {
4131
-                    $php_array_like_string[] = "$key=>$value";
4132
-                }
4133
-                throw new EE_Error(
4134
-                    sprintf(
4135
-                        __(
4136
-                            "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))",
4137
-                            "event_espresso"
4138
-                        ),
4139
-                        implode(",", $php_array_like_string)
4140
-                    )
4141
-                );
4142
-            }
4143
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4144
-        } else {
4145
-            $operator = '=';
4146
-            $value = $op_and_value;
4147
-        }
4148
-        //check to see if the value is actually another field
4149
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4150
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4151
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4152
-            //in this case, the value should be an array, or at least a comma-separated list
4153
-            //it will need to handle a little differently
4154
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4155
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4156
-            return $operator . SP . $cleaned_value;
4157
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4158
-            //the value should be an array with count of two.
4159
-            if (count($value) !== 2) {
4160
-                throw new EE_Error(
4161
-                    sprintf(
4162
-                        __(
4163
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4164
-                            'event_espresso'
4165
-                        ),
4166
-                        "BETWEEN"
4167
-                    )
4168
-                );
4169
-            }
4170
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4171
-            return $operator . SP . $cleaned_value;
4172
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4173
-            if ($value !== null) {
4174
-                throw new EE_Error(
4175
-                    sprintf(
4176
-                        __(
4177
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4178
-                            "event_espresso"
4179
-                        ),
4180
-                        $value,
4181
-                        $operator
4182
-                    )
4183
-                );
4184
-            }
4185
-            return $operator;
4186
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4187
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4188
-            //remove other junk. So just treat it as a string.
4189
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4190
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4191
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4192
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4193
-            throw new EE_Error(
4194
-                sprintf(
4195
-                    __(
4196
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4197
-                        'event_espresso'
4198
-                    ),
4199
-                    $operator,
4200
-                    $operator
4201
-                )
4202
-            );
4203
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4204
-            throw new EE_Error(
4205
-                sprintf(
4206
-                    __(
4207
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4208
-                        'event_espresso'
4209
-                    ),
4210
-                    $operator,
4211
-                    $operator
4212
-                )
4213
-            );
4214
-        } else {
4215
-            throw new EE_Error(
4216
-                sprintf(
4217
-                    __(
4218
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4219
-                        "event_espresso"
4220
-                    ),
4221
-                    http_build_query($op_and_value)
4222
-                )
4223
-            );
4224
-        }
4225
-    }
4226
-
4227
-
4228
-
4229
-    /**
4230
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4231
-     *
4232
-     * @param array                      $values
4233
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4234
-     *                                              '%s'
4235
-     * @return string
4236
-     * @throws \EE_Error
4237
-     */
4238
-    public function _construct_between_value($values, $field_obj)
4239
-    {
4240
-        $cleaned_values = array();
4241
-        foreach ($values as $value) {
4242
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4243
-        }
4244
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4245
-    }
4246
-
4247
-
4248
-
4249
-    /**
4250
-     * Takes an array or a comma-separated list of $values and cleans them
4251
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4252
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4253
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4254
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4255
-     *
4256
-     * @param mixed                      $values    array or comma-separated string
4257
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4258
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4259
-     * @throws \EE_Error
4260
-     */
4261
-    public function _construct_in_value($values, $field_obj)
4262
-    {
4263
-        //check if the value is a CSV list
4264
-        if (is_string($values)) {
4265
-            //in which case, turn it into an array
4266
-            $values = explode(",", $values);
4267
-        }
4268
-        $cleaned_values = array();
4269
-        foreach ($values as $value) {
4270
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4271
-        }
4272
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4273
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4274
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4275
-        if (empty($cleaned_values)) {
4276
-            $all_fields = $this->field_settings();
4277
-            $a_field = array_shift($all_fields);
4278
-            $main_table = $this->_get_main_table();
4279
-            $cleaned_values[] = "SELECT "
4280
-                                . $a_field->get_table_column()
4281
-                                . " FROM "
4282
-                                . $main_table->get_table_name()
4283
-                                . " WHERE FALSE";
4284
-        }
4285
-        return "(" . implode(",", $cleaned_values) . ")";
4286
-    }
4287
-
4288
-
4289
-
4290
-    /**
4291
-     * @param mixed                      $value
4292
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4293
-     * @throws EE_Error
4294
-     * @return false|null|string
4295
-     */
4296
-    private function _wpdb_prepare_using_field($value, $field_obj)
4297
-    {
4298
-        /** @type WPDB $wpdb */
4299
-        global $wpdb;
4300
-        if ($field_obj instanceof EE_Model_Field_Base) {
4301
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4302
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4303
-        } else {//$field_obj should really just be a data type
4304
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4305
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4306
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4307
-            }
4308
-            return $wpdb->prepare($field_obj, $value);
4309
-        }
4310
-    }
4311
-
4312
-
4313
-
4314
-    /**
4315
-     * Takes the input parameter and finds the model field that it indicates.
4316
-     *
4317
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4318
-     * @throws EE_Error
4319
-     * @return EE_Model_Field_Base
4320
-     */
4321
-    protected function _deduce_field_from_query_param($query_param_name)
4322
-    {
4323
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4324
-        //which will help us find the database table and column
4325
-        $query_param_parts = explode(".", $query_param_name);
4326
-        if (empty($query_param_parts)) {
4327
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4328
-                'event_espresso'), $query_param_name));
4329
-        }
4330
-        $number_of_parts = count($query_param_parts);
4331
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4332
-        if ($number_of_parts === 1) {
4333
-            $field_name = $last_query_param_part;
4334
-            $model_obj = $this;
4335
-        } else {// $number_of_parts >= 2
4336
-            //the last part is the column name, and there are only 2parts. therefore...
4337
-            $field_name = $last_query_param_part;
4338
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4339
-        }
4340
-        try {
4341
-            return $model_obj->field_settings_for($field_name);
4342
-        } catch (EE_Error $e) {
4343
-            return null;
4344
-        }
4345
-    }
4346
-
4347
-
4348
-
4349
-    /**
4350
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4351
-     * alias and column which corresponds to it
4352
-     *
4353
-     * @param string $field_name
4354
-     * @throws EE_Error
4355
-     * @return string
4356
-     */
4357
-    public function _get_qualified_column_for_field($field_name)
4358
-    {
4359
-        $all_fields = $this->field_settings();
4360
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4361
-        if ($field) {
4362
-            return $field->get_qualified_column();
4363
-        } else {
4364
-            throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4365
-                'event_espresso'), $field_name, get_class($this)));
4366
-        }
4367
-    }
4368
-
4369
-
4370
-
4371
-    /**
4372
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4373
-     * Example usage:
4374
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4375
-     *      array(),
4376
-     *      ARRAY_A,
4377
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4378
-     *  );
4379
-     * is equivalent to
4380
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4381
-     * and
4382
-     *  EEM_Event::instance()->get_all_wpdb_results(
4383
-     *      array(
4384
-     *          array(
4385
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4386
-     *          ),
4387
-     *          ARRAY_A,
4388
-     *          implode(
4389
-     *              ', ',
4390
-     *              array_merge(
4391
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4392
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4393
-     *              )
4394
-     *          )
4395
-     *      )
4396
-     *  );
4397
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4398
-     *
4399
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4400
-     *                                            and the one whose fields you are selecting for example: when querying
4401
-     *                                            tickets model and selecting fields from the tickets model you would
4402
-     *                                            leave this parameter empty, because no models are needed to join
4403
-     *                                            between the queried model and the selected one. Likewise when
4404
-     *                                            querying the datetime model and selecting fields from the tickets
4405
-     *                                            model, it would also be left empty, because there is a direct
4406
-     *                                            relation from datetimes to tickets, so no model is needed to join
4407
-     *                                            them together. However, when querying from the event model and
4408
-     *                                            selecting fields from the ticket model, you should provide the string
4409
-     *                                            'Datetime', indicating that the event model must first join to the
4410
-     *                                            datetime model in order to find its relation to ticket model.
4411
-     *                                            Also, when querying from the venue model and selecting fields from
4412
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4413
-     *                                            indicating you need to join the venue model to the event model,
4414
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4415
-     *                                            This string is used to deduce the prefix that gets added onto the
4416
-     *                                            models' tables qualified columns
4417
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4418
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4419
-     *                                            qualified column names
4420
-     * @return array|string
4421
-     */
4422
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4423
-    {
4424
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4425
-        $qualified_columns = array();
4426
-        foreach ($this->field_settings() as $field_name => $field) {
4427
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4428
-        }
4429
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4430
-    }
4431
-
4432
-
4433
-
4434
-    /**
4435
-     * constructs the select use on special limit joins
4436
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4437
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4438
-     * (as that is typically where the limits would be set).
4439
-     *
4440
-     * @param  string       $table_alias The table the select is being built for
4441
-     * @param  mixed|string $limit       The limit for this select
4442
-     * @return string                The final select join element for the query.
4443
-     */
4444
-    public function _construct_limit_join_select($table_alias, $limit)
4445
-    {
4446
-        $SQL = '';
4447
-        foreach ($this->_tables as $table_obj) {
4448
-            if ($table_obj instanceof EE_Primary_Table) {
4449
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4450
-                    ? $table_obj->get_select_join_limit($limit)
4451
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4452
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4453
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4454
-                    ? $table_obj->get_select_join_limit_join($limit)
4455
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4456
-            }
4457
-        }
4458
-        return $SQL;
4459
-    }
4460
-
4461
-
4462
-
4463
-    /**
4464
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4465
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4466
-     *
4467
-     * @return string SQL
4468
-     * @throws \EE_Error
4469
-     */
4470
-    public function _construct_internal_join()
4471
-    {
4472
-        $SQL = $this->_get_main_table()->get_table_sql();
4473
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4474
-        return $SQL;
4475
-    }
4476
-
4477
-
4478
-
4479
-    /**
4480
-     * Constructs the SQL for joining all the tables on this model.
4481
-     * Normally $alias should be the primary table's alias, but in cases where
4482
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4483
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4484
-     * alias, this will construct SQL like:
4485
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4486
-     * With $alias being a secondary table's alias, this will construct SQL like:
4487
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4488
-     *
4489
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4490
-     * @return string
4491
-     */
4492
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4493
-    {
4494
-        $SQL = '';
4495
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4496
-        foreach ($this->_tables as $table_obj) {
4497
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4498
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4499
-                    //so we're joining to this table, meaning the table is already in
4500
-                    //the FROM statement, BUT the primary table isn't. So we want
4501
-                    //to add the inverse join sql
4502
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4503
-                } else {
4504
-                    //just add a regular JOIN to this table from the primary table
4505
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4506
-                }
4507
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4508
-        }
4509
-        return $SQL;
4510
-    }
4511
-
4512
-
4513
-
4514
-    /**
4515
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4516
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4517
-     * their data type (eg, '%s', '%d', etc)
4518
-     *
4519
-     * @return array
4520
-     */
4521
-    public function _get_data_types()
4522
-    {
4523
-        $data_types = array();
4524
-        foreach ($this->field_settings() as $field_obj) {
4525
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4526
-            /** @var $field_obj EE_Model_Field_Base */
4527
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4528
-        }
4529
-        return $data_types;
4530
-    }
4531
-
4532
-
4533
-
4534
-    /**
4535
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4536
-     *
4537
-     * @param string $model_name
4538
-     * @throws EE_Error
4539
-     * @return EEM_Base
4540
-     */
4541
-    public function get_related_model_obj($model_name)
4542
-    {
4543
-        $model_classname = "EEM_" . $model_name;
4544
-        if (! class_exists($model_classname)) {
4545
-            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",
4546
-                'event_espresso'), $model_name, $model_classname));
4547
-        }
4548
-        return call_user_func($model_classname . "::instance");
4549
-    }
4550
-
4551
-
4552
-
4553
-    /**
4554
-     * Returns the array of EE_ModelRelations for this model.
4555
-     *
4556
-     * @return EE_Model_Relation_Base[]
4557
-     */
4558
-    public function relation_settings()
4559
-    {
4560
-        return $this->_model_relations;
4561
-    }
4562
-
4563
-
4564
-
4565
-    /**
4566
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4567
-     * because without THOSE models, this model probably doesn't have much purpose.
4568
-     * (Eg, without an event, datetimes have little purpose.)
4569
-     *
4570
-     * @return EE_Belongs_To_Relation[]
4571
-     */
4572
-    public function belongs_to_relations()
4573
-    {
4574
-        $belongs_to_relations = array();
4575
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4576
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4577
-                $belongs_to_relations[$model_name] = $relation_obj;
4578
-            }
4579
-        }
4580
-        return $belongs_to_relations;
4581
-    }
4582
-
4583
-
4584
-
4585
-    /**
4586
-     * Returns the specified EE_Model_Relation, or throws an exception
4587
-     *
4588
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4589
-     * @throws EE_Error
4590
-     * @return EE_Model_Relation_Base
4591
-     */
4592
-    public function related_settings_for($relation_name)
4593
-    {
4594
-        $relatedModels = $this->relation_settings();
4595
-        if (! array_key_exists($relation_name, $relatedModels)) {
4596
-            throw new EE_Error(
4597
-                sprintf(
4598
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4599
-                        'event_espresso'),
4600
-                    $relation_name,
4601
-                    $this->_get_class_name(),
4602
-                    implode(', ', array_keys($relatedModels))
4603
-                )
4604
-            );
4605
-        }
4606
-        return $relatedModels[$relation_name];
4607
-    }
4608
-
4609
-
4610
-
4611
-    /**
4612
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4613
-     * fields
4614
-     *
4615
-     * @param string $fieldName
4616
-     * @throws EE_Error
4617
-     * @return EE_Model_Field_Base
4618
-     */
4619
-    public function field_settings_for($fieldName)
4620
-    {
4621
-        $fieldSettings = $this->field_settings(true);
4622
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4623
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4624
-                get_class($this)));
4625
-        }
4626
-        return $fieldSettings[$fieldName];
4627
-    }
4628
-
4629
-
4630
-
4631
-    /**
4632
-     * Checks if this field exists on this model
4633
-     *
4634
-     * @param string $fieldName a key in the model's _field_settings array
4635
-     * @return boolean
4636
-     */
4637
-    public function has_field($fieldName)
4638
-    {
4639
-        $fieldSettings = $this->field_settings(true);
4640
-        if (isset($fieldSettings[$fieldName])) {
4641
-            return true;
4642
-        } else {
4643
-            return false;
4644
-        }
4645
-    }
4646
-
4647
-
4648
-
4649
-    /**
4650
-     * Returns whether or not this model has a relation to the specified model
4651
-     *
4652
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4653
-     * @return boolean
4654
-     */
4655
-    public function has_relation($relation_name)
4656
-    {
4657
-        $relations = $this->relation_settings();
4658
-        if (isset($relations[$relation_name])) {
4659
-            return true;
4660
-        } else {
4661
-            return false;
4662
-        }
4663
-    }
4664
-
4665
-
4666
-
4667
-    /**
4668
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4669
-     * Eg, on EE_Answer that would be ANS_ID field object
4670
-     *
4671
-     * @param $field_obj
4672
-     * @return boolean
4673
-     */
4674
-    public function is_primary_key_field($field_obj)
4675
-    {
4676
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4677
-    }
4678
-
4679
-
4680
-
4681
-    /**
4682
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4683
-     * Eg, on EE_Answer that would be ANS_ID field object
4684
-     *
4685
-     * @return EE_Model_Field_Base
4686
-     * @throws EE_Error
4687
-     */
4688
-    public function get_primary_key_field()
4689
-    {
4690
-        if ($this->_primary_key_field === null) {
4691
-            foreach ($this->field_settings(true) as $field_obj) {
4692
-                if ($this->is_primary_key_field($field_obj)) {
4693
-                    $this->_primary_key_field = $field_obj;
4694
-                    break;
4695
-                }
4696
-            }
4697
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4698
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4699
-                    get_class($this)));
4700
-            }
4701
-        }
4702
-        return $this->_primary_key_field;
4703
-    }
4704
-
4705
-
4706
-
4707
-    /**
4708
-     * Returns whether or not not there is a primary key on this model.
4709
-     * Internally does some caching.
4710
-     *
4711
-     * @return boolean
4712
-     */
4713
-    public function has_primary_key_field()
4714
-    {
4715
-        if ($this->_has_primary_key_field === null) {
4716
-            try {
4717
-                $this->get_primary_key_field();
4718
-                $this->_has_primary_key_field = true;
4719
-            } catch (EE_Error $e) {
4720
-                $this->_has_primary_key_field = false;
4721
-            }
4722
-        }
4723
-        return $this->_has_primary_key_field;
4724
-    }
4725
-
4726
-
4727
-
4728
-    /**
4729
-     * Finds the first field of type $field_class_name.
4730
-     *
4731
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4732
-     *                                 EE_Foreign_Key_Field, etc
4733
-     * @return EE_Model_Field_Base or null if none is found
4734
-     */
4735
-    public function get_a_field_of_type($field_class_name)
4736
-    {
4737
-        foreach ($this->field_settings() as $field) {
4738
-            if ($field instanceof $field_class_name) {
4739
-                return $field;
4740
-            }
4741
-        }
4742
-        return null;
4743
-    }
4744
-
4745
-
4746
-
4747
-    /**
4748
-     * Gets a foreign key field pointing to model.
4749
-     *
4750
-     * @param string $model_name eg Event, Registration, not EEM_Event
4751
-     * @return EE_Foreign_Key_Field_Base
4752
-     * @throws EE_Error
4753
-     */
4754
-    public function get_foreign_key_to($model_name)
4755
-    {
4756
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4757
-            foreach ($this->field_settings() as $field) {
4758
-                if (
4759
-                    $field instanceof EE_Foreign_Key_Field_Base
4760
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4761
-                ) {
4762
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4763
-                    break;
4764
-                }
4765
-            }
4766
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4767
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4768
-                    'event_espresso'), $model_name, get_class($this)));
4769
-            }
4770
-        }
4771
-        return $this->_cache_foreign_key_to_fields[$model_name];
4772
-    }
4773
-
4774
-
4775
-
4776
-    /**
4777
-     * Gets the table name (including $wpdb->prefix) for the table alias
4778
-     *
4779
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4780
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4781
-     *                            Either one works
4782
-     * @return string
4783
-     */
4784
-    public function get_table_for_alias($table_alias)
4785
-    {
4786
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4787
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4788
-    }
4789
-
4790
-
4791
-
4792
-    /**
4793
-     * Returns a flat array of all field son this model, instead of organizing them
4794
-     * by table_alias as they are in the constructor.
4795
-     *
4796
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4797
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4798
-     */
4799
-    public function field_settings($include_db_only_fields = false)
4800
-    {
4801
-        if ($include_db_only_fields) {
4802
-            if ($this->_cached_fields === null) {
4803
-                $this->_cached_fields = array();
4804
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4805
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4806
-                        $this->_cached_fields[$field_name] = $field_obj;
4807
-                    }
4808
-                }
4809
-            }
4810
-            return $this->_cached_fields;
4811
-        } else {
4812
-            if ($this->_cached_fields_non_db_only === null) {
4813
-                $this->_cached_fields_non_db_only = array();
4814
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4815
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4816
-                        /** @var $field_obj EE_Model_Field_Base */
4817
-                        if (! $field_obj->is_db_only_field()) {
4818
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4819
-                        }
4820
-                    }
4821
-                }
4822
-            }
4823
-            return $this->_cached_fields_non_db_only;
4824
-        }
4825
-    }
4826
-
4827
-
4828
-
4829
-    /**
4830
-     *        cycle though array of attendees and create objects out of each item
4831
-     *
4832
-     * @access        private
4833
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4834
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4835
-     *                           numerically indexed)
4836
-     * @throws \EE_Error
4837
-     */
4838
-    protected function _create_objects($rows = array())
4839
-    {
4840
-        $array_of_objects = array();
4841
-        if (empty($rows)) {
4842
-            return array();
4843
-        }
4844
-        $count_if_model_has_no_primary_key = 0;
4845
-        $has_primary_key = $this->has_primary_key_field();
4846
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4847
-        foreach ((array)$rows as $row) {
4848
-            if (empty($row)) {
4849
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4850
-                return array();
4851
-            }
4852
-            //check if we've already set this object in the results array,
4853
-            //in which case there's no need to process it further (again)
4854
-            if ($has_primary_key) {
4855
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4856
-                    $row,
4857
-                    $primary_key_field->get_qualified_column(),
4858
-                    $primary_key_field->get_table_column()
4859
-                );
4860
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4861
-                    continue;
4862
-                }
4863
-            }
4864
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4865
-            if (! $classInstance) {
4866
-                throw new EE_Error(
4867
-                    sprintf(
4868
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4869
-                        $this->get_this_model_name(),
4870
-                        http_build_query($row)
4871
-                    )
4872
-                );
4873
-            }
4874
-            //set the timezone on the instantiated objects
4875
-            $classInstance->set_timezone($this->_timezone);
4876
-            //make sure if there is any timezone setting present that we set the timezone for the object
4877
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4878
-            $array_of_objects[$key] = $classInstance;
4879
-            //also, for all the relations of type BelongsTo, see if we can cache
4880
-            //those related models
4881
-            //(we could do this for other relations too, but if there are conditions
4882
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4883
-            //so it requires a little more thought than just caching them immediately...)
4884
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4885
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4886
-                    //check if this model's INFO is present. If so, cache it on the model
4887
-                    $other_model = $relation_obj->get_other_model();
4888
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4889
-                    //if we managed to make a model object from the results, cache it on the main model object
4890
-                    if ($other_model_obj_maybe) {
4891
-                        //set timezone on these other model objects if they are present
4892
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4893
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4894
-                    }
4895
-                }
4896
-            }
4897
-        }
4898
-        return $array_of_objects;
4899
-    }
4900
-
4901
-
4902
-
4903
-    /**
4904
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4905
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4906
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4907
-     * object (as set in the model_field!).
4908
-     *
4909
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4910
-     */
4911
-    public function create_default_object()
4912
-    {
4913
-        $this_model_fields_and_values = array();
4914
-        //setup the row using default values;
4915
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4916
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4917
-        }
4918
-        $className = $this->_get_class_name();
4919
-        $classInstance = EE_Registry::instance()
4920
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4921
-        return $classInstance;
4922
-    }
4923
-
4924
-
4925
-
4926
-    /**
4927
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4928
-     *                             or an stdClass where each property is the name of a column,
4929
-     * @return EE_Base_Class
4930
-     * @throws \EE_Error
4931
-     */
4932
-    public function instantiate_class_from_array_or_object($cols_n_values)
4933
-    {
4934
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4935
-            $cols_n_values = get_object_vars($cols_n_values);
4936
-        }
4937
-        $primary_key = null;
4938
-        //make sure the array only has keys that are fields/columns on this model
4939
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4940
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4941
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4942
-        }
4943
-        $className = $this->_get_class_name();
4944
-        //check we actually found results that we can use to build our model object
4945
-        //if not, return null
4946
-        if ($this->has_primary_key_field()) {
4947
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4948
-                return null;
4949
-            }
4950
-        } else if ($this->unique_indexes()) {
4951
-            $first_column = reset($this_model_fields_n_values);
4952
-            if (empty($first_column)) {
4953
-                return null;
4954
-            }
4955
-        }
4956
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4957
-        if ($primary_key) {
4958
-            $classInstance = $this->get_from_entity_map($primary_key);
4959
-            if (! $classInstance) {
4960
-                $classInstance = EE_Registry::instance()
4961
-                                            ->load_class($className,
4962
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4963
-                // add this new object to the entity map
4964
-                $classInstance = $this->add_to_entity_map($classInstance);
4965
-            }
4966
-        } else {
4967
-            $classInstance = EE_Registry::instance()
4968
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4969
-                                            true, false);
4970
-        }
4971
-        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4972
-        $this->set_timezone($classInstance->get_timezone());
4973
-        return $classInstance;
4974
-    }
4975
-
4976
-
4977
-
4978
-    /**
4979
-     * Gets the model object from the  entity map if it exists
4980
-     *
4981
-     * @param int|string $id the ID of the model object
4982
-     * @return EE_Base_Class
4983
-     */
4984
-    public function get_from_entity_map($id)
4985
-    {
4986
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4987
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4988
-    }
4989
-
4990
-
4991
-
4992
-    /**
4993
-     * add_to_entity_map
4994
-     * Adds the object to the model's entity mappings
4995
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4996
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4997
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4998
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4999
-     *        then this method should be called immediately after the update query
5000
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5001
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5002
-     *
5003
-     * @param    EE_Base_Class $object
5004
-     * @throws EE_Error
5005
-     * @return \EE_Base_Class
5006
-     */
5007
-    public function add_to_entity_map(EE_Base_Class $object)
5008
-    {
5009
-        $className = $this->_get_class_name();
5010
-        if (! $object instanceof $className) {
5011
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5012
-                is_object($object) ? get_class($object) : $object, $className));
5013
-        }
5014
-        /** @var $object EE_Base_Class */
5015
-        if (! $object->ID()) {
5016
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5017
-                "event_espresso"), get_class($this)));
5018
-        }
5019
-        // double check it's not already there
5020
-        $classInstance = $this->get_from_entity_map($object->ID());
5021
-        if ($classInstance) {
5022
-            return $classInstance;
5023
-        } else {
5024
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5025
-            return $object;
5026
-        }
5027
-    }
5028
-
5029
-
5030
-
5031
-    /**
5032
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5033
-     * if no identifier is provided, then the entire entity map is emptied
5034
-     *
5035
-     * @param int|string $id the ID of the model object
5036
-     * @return boolean
5037
-     */
5038
-    public function clear_entity_map($id = null)
5039
-    {
5040
-        if (empty($id)) {
5041
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5042
-            return true;
5043
-        }
5044
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5045
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5046
-            return true;
5047
-        }
5048
-        return false;
5049
-    }
5050
-
5051
-
5052
-
5053
-    /**
5054
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5055
-     * Given an array where keys are column (or column alias) names and values,
5056
-     * returns an array of their corresponding field names and database values
5057
-     *
5058
-     * @param array $cols_n_values
5059
-     * @return array
5060
-     */
5061
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5062
-    {
5063
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5064
-    }
5065
-
5066
-
5067
-
5068
-    /**
5069
-     * _deduce_fields_n_values_from_cols_n_values
5070
-     * Given an array where keys are column (or column alias) names and values,
5071
-     * returns an array of their corresponding field names and database values
5072
-     *
5073
-     * @param string $cols_n_values
5074
-     * @return array
5075
-     */
5076
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5077
-    {
5078
-        $this_model_fields_n_values = array();
5079
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5080
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5081
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5082
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5083
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5084
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5085
-                    if (! $field_obj->is_db_only_field()) {
5086
-                        //prepare field as if its coming from db
5087
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5088
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5089
-                    }
5090
-                }
5091
-            } else {
5092
-                //the table's rows existed. Use their values
5093
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5094
-                    if (! $field_obj->is_db_only_field()) {
5095
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5096
-                            $cols_n_values, $field_obj->get_qualified_column(),
5097
-                            $field_obj->get_table_column()
5098
-                        );
5099
-                    }
5100
-                }
5101
-            }
5102
-        }
5103
-        return $this_model_fields_n_values;
5104
-    }
5105
-
5106
-
5107
-
5108
-    /**
5109
-     * @param $cols_n_values
5110
-     * @param $qualified_column
5111
-     * @param $regular_column
5112
-     * @return null
5113
-     */
5114
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5115
-    {
5116
-        $value = null;
5117
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5118
-        //does the field on the model relate to this column retrieved from the db?
5119
-        //or is it a db-only field? (not relating to the model)
5120
-        if (isset($cols_n_values[$qualified_column])) {
5121
-            $value = $cols_n_values[$qualified_column];
5122
-        } elseif (isset($cols_n_values[$regular_column])) {
5123
-            $value = $cols_n_values[$regular_column];
5124
-        }
5125
-        return $value;
5126
-    }
5127
-
5128
-
5129
-
5130
-    /**
5131
-     * refresh_entity_map_from_db
5132
-     * Makes sure the model object in the entity map at $id assumes the values
5133
-     * of the database (opposite of EE_base_Class::save())
5134
-     *
5135
-     * @param int|string $id
5136
-     * @return EE_Base_Class
5137
-     * @throws \EE_Error
5138
-     */
5139
-    public function refresh_entity_map_from_db($id)
5140
-    {
5141
-        $obj_in_map = $this->get_from_entity_map($id);
5142
-        if ($obj_in_map) {
5143
-            $wpdb_results = $this->_get_all_wpdb_results(
5144
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5145
-            );
5146
-            if ($wpdb_results && is_array($wpdb_results)) {
5147
-                $one_row = reset($wpdb_results);
5148
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5149
-                    $obj_in_map->set_from_db($field_name, $db_value);
5150
-                }
5151
-                //clear the cache of related model objects
5152
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5153
-                    $obj_in_map->clear_cache($relation_name, null, true);
5154
-                }
5155
-            }
5156
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5157
-            return $obj_in_map;
5158
-        } else {
5159
-            return $this->get_one_by_ID($id);
5160
-        }
5161
-    }
5162
-
5163
-
5164
-
5165
-    /**
5166
-     * refresh_entity_map_with
5167
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5168
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5169
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5170
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5171
-     *
5172
-     * @param int|string    $id
5173
-     * @param EE_Base_Class $replacing_model_obj
5174
-     * @return \EE_Base_Class
5175
-     * @throws \EE_Error
5176
-     */
5177
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5178
-    {
5179
-        $obj_in_map = $this->get_from_entity_map($id);
5180
-        if ($obj_in_map) {
5181
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5182
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5183
-                    $obj_in_map->set($field_name, $value);
5184
-                }
5185
-                //make the model object in the entity map's cache match the $replacing_model_obj
5186
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5187
-                    $obj_in_map->clear_cache($relation_name, null, true);
5188
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5189
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5190
-                    }
5191
-                }
5192
-            }
5193
-            return $obj_in_map;
5194
-        } else {
5195
-            $this->add_to_entity_map($replacing_model_obj);
5196
-            return $replacing_model_obj;
5197
-        }
5198
-    }
5199
-
5200
-
5201
-
5202
-    /**
5203
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5204
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5205
-     * require_once($this->_getClassName().".class.php");
5206
-     *
5207
-     * @return string
5208
-     */
5209
-    private function _get_class_name()
5210
-    {
5211
-        return "EE_" . $this->get_this_model_name();
5212
-    }
5213
-
5214
-
5215
-
5216
-    /**
5217
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5218
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5219
-     * it would be 'Events'.
5220
-     *
5221
-     * @param int $quantity
5222
-     * @return string
5223
-     */
5224
-    public function item_name($quantity = 1)
5225
-    {
5226
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5227
-    }
5228
-
5229
-
5230
-
5231
-    /**
5232
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5233
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5234
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5235
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5236
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5237
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5238
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5239
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5240
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5241
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5242
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5243
-     *        return $previousReturnValue.$returnString;
5244
-     * }
5245
-     * require('EEM_Answer.model.php');
5246
-     * $answer=EEM_Answer::instance();
5247
-     * echo $answer->my_callback('monkeys',100);
5248
-     * //will output "you called my_callback! and passed args:monkeys,100"
5249
-     *
5250
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5251
-     * @param array  $args       array of original arguments passed to the function
5252
-     * @throws EE_Error
5253
-     * @return mixed whatever the plugin which calls add_filter decides
5254
-     */
5255
-    public function __call($methodName, $args)
5256
-    {
5257
-        $className = get_class($this);
5258
-        $tagName = "FHEE__{$className}__{$methodName}";
5259
-        if (! has_filter($tagName)) {
5260
-            throw new EE_Error(
5261
-                sprintf(
5262
-                    __('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 );',
5263
-                        'event_espresso'),
5264
-                    $methodName,
5265
-                    $className,
5266
-                    $tagName,
5267
-                    '<br />'
5268
-                )
5269
-            );
5270
-        }
5271
-        return apply_filters($tagName, null, $this, $args);
5272
-    }
5273
-
5274
-
5275
-
5276
-    /**
5277
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5278
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5279
-     *
5280
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5281
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5282
-     *                                                       the object's class name
5283
-     *                                                       or object's ID
5284
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5285
-     *                                                       exists in the database. If it does not, we add it
5286
-     * @throws EE_Error
5287
-     * @return EE_Base_Class
5288
-     */
5289
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5290
-    {
5291
-        $className = $this->_get_class_name();
5292
-        if ($base_class_obj_or_id instanceof $className) {
5293
-            $model_object = $base_class_obj_or_id;
5294
-        } else {
5295
-            $primary_key_field = $this->get_primary_key_field();
5296
-            if (
5297
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5298
-                && (
5299
-                    is_int($base_class_obj_or_id)
5300
-                    || is_string($base_class_obj_or_id)
5301
-                )
5302
-            ) {
5303
-                // assume it's an ID.
5304
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5305
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5306
-            } else if (
5307
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5308
-                && is_string($base_class_obj_or_id)
5309
-            ) {
5310
-                // assume its a string representation of the object
5311
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5312
-            } else {
5313
-                throw new EE_Error(
5314
-                    sprintf(
5315
-                        __(
5316
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5317
-                            'event_espresso'
5318
-                        ),
5319
-                        $base_class_obj_or_id,
5320
-                        $this->_get_class_name(),
5321
-                        print_r($base_class_obj_or_id, true)
5322
-                    )
5323
-                );
5324
-            }
5325
-        }
5326
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5327
-            $model_object->save();
5328
-        }
5329
-        return $model_object;
5330
-    }
5331
-
5332
-
5333
-
5334
-    /**
5335
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5336
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5337
-     * returns it ID.
5338
-     *
5339
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5340
-     * @return int|string depending on the type of this model object's ID
5341
-     * @throws EE_Error
5342
-     */
5343
-    public function ensure_is_ID($base_class_obj_or_id)
5344
-    {
5345
-        $className = $this->_get_class_name();
5346
-        if ($base_class_obj_or_id instanceof $className) {
5347
-            /** @var $base_class_obj_or_id EE_Base_Class */
5348
-            $id = $base_class_obj_or_id->ID();
5349
-        } elseif (is_int($base_class_obj_or_id)) {
5350
-            //assume it's an ID
5351
-            $id = $base_class_obj_or_id;
5352
-        } elseif (is_string($base_class_obj_or_id)) {
5353
-            //assume its a string representation of the object
5354
-            $id = $base_class_obj_or_id;
5355
-        } else {
5356
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5357
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5358
-                print_r($base_class_obj_or_id, true)));
5359
-        }
5360
-        return $id;
5361
-    }
5362
-
5363
-
5364
-
5365
-    /**
5366
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5367
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5368
-     * been sanitized and converted into the appropriate domain.
5369
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5370
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5371
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5372
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5373
-     * $EVT = EEM_Event::instance(); $old_setting =
5374
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5375
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5376
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5377
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5378
-     *
5379
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5380
-     * @return void
5381
-     */
5382
-    public function assume_values_already_prepared_by_model_object(
5383
-        $values_already_prepared = self::not_prepared_by_model_object
5384
-    ) {
5385
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5386
-    }
5387
-
5388
-
5389
-
5390
-    /**
5391
-     * Read comments for assume_values_already_prepared_by_model_object()
5392
-     *
5393
-     * @return int
5394
-     */
5395
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5396
-    {
5397
-        return $this->_values_already_prepared_by_model_object;
5398
-    }
5399
-
5400
-
5401
-
5402
-    /**
5403
-     * Gets all the indexes on this model
5404
-     *
5405
-     * @return EE_Index[]
5406
-     */
5407
-    public function indexes()
5408
-    {
5409
-        return $this->_indexes;
5410
-    }
5411
-
5412
-
5413
-
5414
-    /**
5415
-     * Gets all the Unique Indexes on this model
5416
-     *
5417
-     * @return EE_Unique_Index[]
5418
-     */
5419
-    public function unique_indexes()
5420
-    {
5421
-        $unique_indexes = array();
5422
-        foreach ($this->_indexes as $name => $index) {
5423
-            if ($index instanceof EE_Unique_Index) {
5424
-                $unique_indexes [$name] = $index;
5425
-            }
5426
-        }
5427
-        return $unique_indexes;
5428
-    }
5429
-
5430
-
5431
-
5432
-    /**
5433
-     * Gets all the fields which, when combined, make the primary key.
5434
-     * This is usually just an array with 1 element (the primary key), but in cases
5435
-     * where there is no primary key, it's a combination of fields as defined
5436
-     * on a primary index
5437
-     *
5438
-     * @return EE_Model_Field_Base[] indexed by the field's name
5439
-     * @throws \EE_Error
5440
-     */
5441
-    public function get_combined_primary_key_fields()
5442
-    {
5443
-        foreach ($this->indexes() as $index) {
5444
-            if ($index instanceof EE_Primary_Key_Index) {
5445
-                return $index->fields();
5446
-            }
5447
-        }
5448
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5449
-    }
5450
-
5451
-
5452
-
5453
-    /**
5454
-     * Used to build a primary key string (when the model has no primary key),
5455
-     * which can be used a unique string to identify this model object.
5456
-     *
5457
-     * @param array $cols_n_values keys are field names, values are their values
5458
-     * @return string
5459
-     * @throws \EE_Error
5460
-     */
5461
-    public function get_index_primary_key_string($cols_n_values)
5462
-    {
5463
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5464
-            $this->get_combined_primary_key_fields());
5465
-        return http_build_query($cols_n_values_for_primary_key_index);
5466
-    }
5467
-
5468
-
5469
-
5470
-    /**
5471
-     * Gets the field values from the primary key string
5472
-     *
5473
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5474
-     * @param string $index_primary_key_string
5475
-     * @return null|array
5476
-     * @throws \EE_Error
5477
-     */
5478
-    public function parse_index_primary_key_string($index_primary_key_string)
5479
-    {
5480
-        $key_fields = $this->get_combined_primary_key_fields();
5481
-        //check all of them are in the $id
5482
-        $key_vals_in_combined_pk = array();
5483
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5484
-        foreach ($key_fields as $key_field_name => $field_obj) {
5485
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5486
-                return null;
5487
-            }
5488
-        }
5489
-        return $key_vals_in_combined_pk;
5490
-    }
5491
-
5492
-
5493
-
5494
-    /**
5495
-     * verifies that an array of key-value pairs for model fields has a key
5496
-     * for each field comprising the primary key index
5497
-     *
5498
-     * @param array $key_vals
5499
-     * @return boolean
5500
-     * @throws \EE_Error
5501
-     */
5502
-    public function has_all_combined_primary_key_fields($key_vals)
5503
-    {
5504
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5505
-        foreach ($keys_it_should_have as $key) {
5506
-            if (! isset($key_vals[$key])) {
5507
-                return false;
5508
-            }
5509
-        }
5510
-        return true;
5511
-    }
5512
-
5513
-
5514
-
5515
-    /**
5516
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5517
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5518
-     *
5519
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5520
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5521
-     * @throws EE_Error
5522
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5523
-     *                                                              indexed)
5524
-     */
5525
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5526
-    {
5527
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5528
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5529
-        } elseif (is_array($model_object_or_attributes_array)) {
5530
-            $attributes_array = $model_object_or_attributes_array;
5531
-        } else {
5532
-            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",
5533
-                "event_espresso"), $model_object_or_attributes_array));
5534
-        }
5535
-        //even copies obviously won't have the same ID, so remove the primary key
5536
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5537
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5538
-            unset($attributes_array[$this->primary_key_name()]);
5539
-        }
5540
-        if (isset($query_params[0])) {
5541
-            $query_params[0] = array_merge($attributes_array, $query_params);
5542
-        } else {
5543
-            $query_params[0] = $attributes_array;
5544
-        }
5545
-        return $this->get_all($query_params);
5546
-    }
5547
-
5548
-
5549
-
5550
-    /**
5551
-     * Gets the first copy we find. See get_all_copies for more details
5552
-     *
5553
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5554
-     * @param array $query_params
5555
-     * @return EE_Base_Class
5556
-     * @throws \EE_Error
5557
-     */
5558
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5559
-    {
5560
-        if (! is_array($query_params)) {
5561
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5562
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5563
-                    gettype($query_params)), '4.6.0');
5564
-            $query_params = array();
5565
-        }
5566
-        $query_params['limit'] = 1;
5567
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5568
-        if (is_array($copies)) {
5569
-            return array_shift($copies);
5570
-        } else {
5571
-            return null;
5572
-        }
5573
-    }
5574
-
5575
-
5576
-
5577
-    /**
5578
-     * Updates the item with the specified id. Ignores default query parameters because
5579
-     * we have specified the ID, and its assumed we KNOW what we're doing
5580
-     *
5581
-     * @param array      $fields_n_values keys are field names, values are their new values
5582
-     * @param int|string $id              the value of the primary key to update
5583
-     * @return int number of rows updated
5584
-     * @throws \EE_Error
5585
-     */
5586
-    public function update_by_ID($fields_n_values, $id)
5587
-    {
5588
-        $query_params = array(
5589
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5590
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5591
-        );
5592
-        return $this->update($fields_n_values, $query_params);
5593
-    }
5594
-
5595
-
5596
-
5597
-    /**
5598
-     * Changes an operator which was supplied to the models into one usable in SQL
5599
-     *
5600
-     * @param string $operator_supplied
5601
-     * @return string an operator which can be used in SQL
5602
-     * @throws EE_Error
5603
-     */
5604
-    private function _prepare_operator_for_sql($operator_supplied)
5605
-    {
5606
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5607
-            : null;
5608
-        if ($sql_operator) {
5609
-            return $sql_operator;
5610
-        } else {
5611
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5612
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5613
-        }
5614
-    }
5615
-
5616
-
5617
-
5618
-    /**
5619
-     * Gets an array where keys are the primary keys and values are their 'names'
5620
-     * (as determined by the model object's name() function, which is often overridden)
5621
-     *
5622
-     * @param array $query_params like get_all's
5623
-     * @return string[]
5624
-     * @throws \EE_Error
5625
-     */
5626
-    public function get_all_names($query_params = array())
5627
-    {
5628
-        $objs = $this->get_all($query_params);
5629
-        $names = array();
5630
-        foreach ($objs as $obj) {
5631
-            $names[$obj->ID()] = $obj->name();
5632
-        }
5633
-        return $names;
5634
-    }
5635
-
5636
-
5637
-
5638
-    /**
5639
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5640
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5641
-     * this is duplicated effort and reduces efficiency) you would be better to use
5642
-     * array_keys() on $model_objects.
5643
-     *
5644
-     * @param \EE_Base_Class[] $model_objects
5645
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5646
-     *                                               in the returned array
5647
-     * @return array
5648
-     * @throws \EE_Error
5649
-     */
5650
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5651
-    {
5652
-        if (! $this->has_primary_key_field()) {
5653
-            if (WP_DEBUG) {
5654
-                EE_Error::add_error(
5655
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5656
-                    __FILE__,
5657
-                    __FUNCTION__,
5658
-                    __LINE__
5659
-                );
5660
-            }
5661
-        }
5662
-        $IDs = array();
5663
-        foreach ($model_objects as $model_object) {
5664
-            $id = $model_object->ID();
5665
-            if (! $id) {
5666
-                if ($filter_out_empty_ids) {
5667
-                    continue;
5668
-                }
5669
-                if (WP_DEBUG) {
5670
-                    EE_Error::add_error(
5671
-                        __(
5672
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5673
-                            'event_espresso'
5674
-                        ),
5675
-                        __FILE__,
5676
-                        __FUNCTION__,
5677
-                        __LINE__
5678
-                    );
5679
-                }
5680
-            }
5681
-            $IDs[] = $id;
5682
-        }
5683
-        return $IDs;
5684
-    }
5685
-
5686
-
5687
-
5688
-    /**
5689
-     * Returns the string used in capabilities relating to this model. If there
5690
-     * are no capabilities that relate to this model returns false
5691
-     *
5692
-     * @return string|false
5693
-     */
5694
-    public function cap_slug()
5695
-    {
5696
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5697
-    }
5698
-
5699
-
5700
-
5701
-    /**
5702
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5703
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5704
-     * only returns the cap restrictions array in that context (ie, the array
5705
-     * at that key)
5706
-     *
5707
-     * @param string $context
5708
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5709
-     * @throws \EE_Error
5710
-     */
5711
-    public function cap_restrictions($context = EEM_Base::caps_read)
5712
-    {
5713
-        EEM_Base::verify_is_valid_cap_context($context);
5714
-        //check if we ought to run the restriction generator first
5715
-        if (
5716
-            isset($this->_cap_restriction_generators[$context])
5717
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5718
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5719
-        ) {
5720
-            $this->_cap_restrictions[$context] = array_merge(
5721
-                $this->_cap_restrictions[$context],
5722
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5723
-            );
5724
-        }
5725
-        //and make sure we've finalized the construction of each restriction
5726
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5727
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5728
-                $where_conditions_obj->_finalize_construct($this);
5729
-            }
5730
-        }
5731
-        return $this->_cap_restrictions[$context];
5732
-    }
5733
-
5734
-
5735
-
5736
-    /**
5737
-     * Indicating whether or not this model thinks its a wp core model
5738
-     *
5739
-     * @return boolean
5740
-     */
5741
-    public function is_wp_core_model()
5742
-    {
5743
-        return $this->_wp_core_model;
5744
-    }
5745
-
5746
-
5747
-
5748
-    /**
5749
-     * Gets all the caps that are missing which impose a restriction on
5750
-     * queries made in this context
5751
-     *
5752
-     * @param string $context one of EEM_Base::caps_ constants
5753
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5754
-     * @throws \EE_Error
5755
-     */
5756
-    public function caps_missing($context = EEM_Base::caps_read)
5757
-    {
5758
-        $missing_caps = array();
5759
-        $cap_restrictions = $this->cap_restrictions($context);
5760
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5761
-            if (! EE_Capabilities::instance()
5762
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5763
-            ) {
5764
-                $missing_caps[$cap] = $restriction_if_no_cap;
5765
-            }
5766
-        }
5767
-        return $missing_caps;
5768
-    }
5769
-
5770
-
5771
-
5772
-    /**
5773
-     * Gets the mapping from capability contexts to action strings used in capability names
5774
-     *
5775
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5776
-     * one of 'read', 'edit', or 'delete'
5777
-     */
5778
-    public function cap_contexts_to_cap_action_map()
5779
-    {
5780
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5781
-            $this);
5782
-    }
5783
-
5784
-
5785
-
5786
-    /**
5787
-     * Gets the action string for the specified capability context
5788
-     *
5789
-     * @param string $context
5790
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5791
-     * @throws \EE_Error
5792
-     */
5793
-    public function cap_action_for_context($context)
5794
-    {
5795
-        $mapping = $this->cap_contexts_to_cap_action_map();
5796
-        if (isset($mapping[$context])) {
5797
-            return $mapping[$context];
5798
-        }
5799
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5800
-            return $action;
5801
-        }
5802
-        throw new EE_Error(
5803
-            sprintf(
5804
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5805
-                $context,
5806
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5807
-            )
5808
-        );
5809
-    }
5810
-
5811
-
5812
-
5813
-    /**
5814
-     * Returns all the capability contexts which are valid when querying models
5815
-     *
5816
-     * @return array
5817
-     */
5818
-    public static function valid_cap_contexts()
5819
-    {
5820
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5821
-            self::caps_read,
5822
-            self::caps_read_admin,
5823
-            self::caps_edit,
5824
-            self::caps_delete,
5825
-        ));
5826
-    }
5827
-
5828
-
5829
-
5830
-    /**
5831
-     * Returns all valid options for 'default_where_conditions'
5832
-     *
5833
-     * @return array
5834
-     */
5835
-    public static function valid_default_where_conditions()
5836
-    {
5837
-        return array(
5838
-            EEM_Base::default_where_conditions_all,
5839
-            EEM_Base::default_where_conditions_this_only,
5840
-            EEM_Base::default_where_conditions_others_only,
5841
-            EEM_Base::default_where_conditions_minimum_all,
5842
-            EEM_Base::default_where_conditions_minimum_others,
5843
-            EEM_Base::default_where_conditions_none
5844
-        );
5845
-    }
5846
-
5847
-    // public static function default_where_conditions_full
5848
-    /**
5849
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5850
-     *
5851
-     * @param string $context
5852
-     * @return bool
5853
-     * @throws \EE_Error
5854
-     */
5855
-    static public function verify_is_valid_cap_context($context)
5856
-    {
5857
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5858
-        if (in_array($context, $valid_cap_contexts)) {
5859
-            return true;
5860
-        } else {
5861
-            throw new EE_Error(
5862
-                sprintf(
5863
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5864
-                        'event_espresso'),
5865
-                    $context,
5866
-                    'EEM_Base',
5867
-                    implode(',', $valid_cap_contexts)
5868
-                )
5869
-            );
5870
-        }
5871
-    }
5872
-
5873
-
5874
-
5875
-    /**
5876
-     * Clears all the models field caches. This is only useful when a sub-class
5877
-     * might have added a field or something and these caches might be invalidated
5878
-     */
5879
-    protected function _invalidate_field_caches()
5880
-    {
5881
-        $this->_cache_foreign_key_to_fields = array();
5882
-        $this->_cached_fields = null;
5883
-        $this->_cached_fields_non_db_only = null;
5884
-    }
5885
-
5886
-
5887
-
5888
-    /**
5889
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5890
-     * (eg "and", "or", "not").
5891
-     *
5892
-     * @return array
5893
-     */
5894
-    public function logic_query_param_keys()
5895
-    {
5896
-        return $this->_logic_query_param_keys;
5897
-    }
5898
-
5899
-
5900
-
5901
-    /**
5902
-     * Determines whether or not the where query param array key is for a logic query param.
5903
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5904
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5905
-     *
5906
-     * @param $query_param_key
5907
-     * @return bool
5908
-     */
5909
-    public function is_logic_query_param_key($query_param_key)
5910
-    {
5911
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5912
-            if ($query_param_key === $logic_query_param_key
5913
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5914
-            ) {
5915
-                return true;
5916
-            }
5917
-        }
5918
-        return false;
5919
-    }
3679
+		}
3680
+		return $null_friendly_where_conditions;
3681
+	}
3682
+
3683
+
3684
+
3685
+	/**
3686
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3687
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3688
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3689
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3690
+	 *
3691
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3692
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3693
+	 */
3694
+	private function _get_default_where_conditions($model_relation_path = null)
3695
+	{
3696
+		if ($this->_ignore_where_strategy) {
3697
+			return array();
3698
+		}
3699
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3700
+	}
3701
+
3702
+
3703
+
3704
+	/**
3705
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3706
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3707
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3708
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3709
+	 * Similar to _get_default_where_conditions
3710
+	 *
3711
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3712
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3713
+	 */
3714
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3715
+	{
3716
+		if ($this->_ignore_where_strategy) {
3717
+			return array();
3718
+		}
3719
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3720
+	}
3721
+
3722
+
3723
+
3724
+	/**
3725
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3726
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3727
+	 *
3728
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3729
+	 * @return string
3730
+	 * @throws \EE_Error
3731
+	 */
3732
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3733
+	{
3734
+		$selects = $this->_get_columns_to_select_for_this_model();
3735
+		foreach (
3736
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3737
+			$name_of_other_model_included
3738
+		) {
3739
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3740
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3741
+			foreach ($other_model_selects as $key => $value) {
3742
+				$selects[] = $value;
3743
+			}
3744
+		}
3745
+		return implode(", ", $selects);
3746
+	}
3747
+
3748
+
3749
+
3750
+	/**
3751
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3752
+	 * So that's going to be the columns for all the fields on the model
3753
+	 *
3754
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3755
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3756
+	 */
3757
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3758
+	{
3759
+		$fields = $this->field_settings();
3760
+		$selects = array();
3761
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3762
+			$this->get_this_model_name());
3763
+		foreach ($fields as $field_obj) {
3764
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3765
+						 . $field_obj->get_table_alias()
3766
+						 . "."
3767
+						 . $field_obj->get_table_column()
3768
+						 . " AS '"
3769
+						 . $table_alias_with_model_relation_chain_prefix
3770
+						 . $field_obj->get_table_alias()
3771
+						 . "."
3772
+						 . $field_obj->get_table_column()
3773
+						 . "'";
3774
+		}
3775
+		//make sure we are also getting the PKs of each table
3776
+		$tables = $this->get_tables();
3777
+		if (count($tables) > 1) {
3778
+			foreach ($tables as $table_obj) {
3779
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3780
+									   . $table_obj->get_fully_qualified_pk_column();
3781
+				if (! in_array($qualified_pk_column, $selects)) {
3782
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3783
+				}
3784
+			}
3785
+		}
3786
+		return $selects;
3787
+	}
3788
+
3789
+
3790
+
3791
+	/**
3792
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3793
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3794
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3795
+	 * SQL for joining, and the data types
3796
+	 *
3797
+	 * @param null|string                 $original_query_param
3798
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3799
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3800
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3801
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3802
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3803
+	 *                                                          or 'Registration's
3804
+	 * @param string                      $original_query_param what it originally was (eg
3805
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3806
+	 *                                                          matches $query_param
3807
+	 * @throws EE_Error
3808
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3809
+	 */
3810
+	private function _extract_related_model_info_from_query_param(
3811
+		$query_param,
3812
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3813
+		$query_param_type,
3814
+		$original_query_param = null
3815
+	) {
3816
+		if ($original_query_param === null) {
3817
+			$original_query_param = $query_param;
3818
+		}
3819
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3820
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3821
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3822
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3823
+		//check to see if we have a field on this model
3824
+		$this_model_fields = $this->field_settings(true);
3825
+		if (array_key_exists($query_param, $this_model_fields)) {
3826
+			if ($allow_fields) {
3827
+				return;
3828
+			} else {
3829
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3830
+					"event_espresso"),
3831
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3832
+			}
3833
+		} //check if this is a special logic query param
3834
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3835
+			if ($allow_logic_query_params) {
3836
+				return;
3837
+			} else {
3838
+				throw new EE_Error(
3839
+					sprintf(
3840
+						__('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',
3841
+							'event_espresso'),
3842
+						implode('", "', $this->_logic_query_param_keys),
3843
+						$query_param,
3844
+						get_class($this),
3845
+						'<br />',
3846
+						"\t"
3847
+						. ' $passed_in_query_info = <pre>'
3848
+						. print_r($passed_in_query_info, true)
3849
+						. '</pre>'
3850
+						. "\n\t"
3851
+						. ' $query_param_type = '
3852
+						. $query_param_type
3853
+						. "\n\t"
3854
+						. ' $original_query_param = '
3855
+						. $original_query_param
3856
+					)
3857
+				);
3858
+			}
3859
+		} //check if it's a custom selection
3860
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3861
+			return;
3862
+		}
3863
+		//check if has a model name at the beginning
3864
+		//and
3865
+		//check if it's a field on a related model
3866
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3867
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3868
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3869
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3870
+				if ($query_param === '') {
3871
+					//nothing left to $query_param
3872
+					//we should actually end in a field name, not a model like this!
3873
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3874
+						"event_espresso"),
3875
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3876
+				} else {
3877
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3878
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3879
+						$passed_in_query_info, $query_param_type, $original_query_param);
3880
+					return;
3881
+				}
3882
+			} elseif ($query_param === $valid_related_model_name) {
3883
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3884
+				return;
3885
+			}
3886
+		}
3887
+		//ok so $query_param didn't start with a model name
3888
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3889
+		//it's wack, that's what it is
3890
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3891
+			"event_espresso"),
3892
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3893
+	}
3894
+
3895
+
3896
+
3897
+	/**
3898
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3899
+	 * and store it on $passed_in_query_info
3900
+	 *
3901
+	 * @param string                      $model_name
3902
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3903
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3904
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3905
+	 *                                                          and are adding a join to 'Payment' with the original
3906
+	 *                                                          query param key
3907
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3908
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3909
+	 *                                                          Payment wants to add default query params so that it
3910
+	 *                                                          will know what models to prepend onto its default query
3911
+	 *                                                          params or in case it wants to rename tables (in case
3912
+	 *                                                          there are multiple joins to the same table)
3913
+	 * @return void
3914
+	 * @throws \EE_Error
3915
+	 */
3916
+	private function _add_join_to_model(
3917
+		$model_name,
3918
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3919
+		$original_query_param
3920
+	) {
3921
+		$relation_obj = $this->related_settings_for($model_name);
3922
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3923
+		//check if the relation is HABTM, because then we're essentially doing two joins
3924
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3925
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3926
+			$join_model_obj = $relation_obj->get_join_model();
3927
+			//replace the model specified with the join model for this relation chain, whi
3928
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3929
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3930
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3931
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3932
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3933
+			$passed_in_query_info->merge($new_query_info);
3934
+		}
3935
+		//now just join to the other table pointed to by the relation object, and add its data types
3936
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3937
+			array($model_relation_chain => $model_name),
3938
+			$relation_obj->get_join_statement($model_relation_chain));
3939
+		$passed_in_query_info->merge($new_query_info);
3940
+	}
3941
+
3942
+
3943
+
3944
+	/**
3945
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3946
+	 *
3947
+	 * @param array $where_params like EEM_Base::get_all
3948
+	 * @return string of SQL
3949
+	 * @throws \EE_Error
3950
+	 */
3951
+	private function _construct_where_clause($where_params)
3952
+	{
3953
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3954
+		if ($SQL) {
3955
+			return " WHERE " . $SQL;
3956
+		} else {
3957
+			return '';
3958
+		}
3959
+	}
3960
+
3961
+
3962
+
3963
+	/**
3964
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3965
+	 * and should be passed HAVING parameters, not WHERE parameters
3966
+	 *
3967
+	 * @param array $having_params
3968
+	 * @return string
3969
+	 * @throws \EE_Error
3970
+	 */
3971
+	private function _construct_having_clause($having_params)
3972
+	{
3973
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3974
+		if ($SQL) {
3975
+			return " HAVING " . $SQL;
3976
+		} else {
3977
+			return '';
3978
+		}
3979
+	}
3980
+
3981
+
3982
+
3983
+	/**
3984
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3985
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3986
+	 * EEM_Attendee.
3987
+	 *
3988
+	 * @param string $field_name
3989
+	 * @param string $model_name
3990
+	 * @return EE_Model_Field_Base
3991
+	 * @throws EE_Error
3992
+	 */
3993
+	protected function _get_field_on_model($field_name, $model_name)
3994
+	{
3995
+		$model_class = 'EEM_' . $model_name;
3996
+		$model_filepath = $model_class . ".model.php";
3997
+		if (is_readable($model_filepath)) {
3998
+			require_once($model_filepath);
3999
+			$model_instance = call_user_func($model_name . "::instance");
4000
+			/* @var $model_instance EEM_Base */
4001
+			return $model_instance->field_settings_for($field_name);
4002
+		} else {
4003
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
4004
+				'event_espresso'), $model_name, $model_class, $model_filepath));
4005
+		}
4006
+	}
4007
+
4008
+
4009
+
4010
+	/**
4011
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4012
+	 * Event_Meta.meta_value = 'foo'))"
4013
+	 *
4014
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4015
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4016
+	 * @throws EE_Error
4017
+	 * @return string of SQL
4018
+	 */
4019
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4020
+	{
4021
+		$where_clauses = array();
4022
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4023
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4024
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4025
+				switch ($query_param) {
4026
+					case 'not':
4027
+					case 'NOT':
4028
+						$where_clauses[] = "! ("
4029
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4030
+								$glue)
4031
+										   . ")";
4032
+						break;
4033
+					case 'and':
4034
+					case 'AND':
4035
+						$where_clauses[] = " ("
4036
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4037
+								' AND ')
4038
+										   . ")";
4039
+						break;
4040
+					case 'or':
4041
+					case 'OR':
4042
+						$where_clauses[] = " ("
4043
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4044
+								' OR ')
4045
+										   . ")";
4046
+						break;
4047
+				}
4048
+			} else {
4049
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4050
+				//if it's not a normal field, maybe it's a custom selection?
4051
+				if (! $field_obj) {
4052
+					if (isset($this->_custom_selections[$query_param][1])) {
4053
+						$field_obj = $this->_custom_selections[$query_param][1];
4054
+					} else {
4055
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4056
+							"event_espresso"), $query_param));
4057
+					}
4058
+				}
4059
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4060
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4061
+			}
4062
+		}
4063
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4064
+	}
4065
+
4066
+
4067
+
4068
+	/**
4069
+	 * Takes the input parameter and extract the table name (alias) and column name
4070
+	 *
4071
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4072
+	 * @throws EE_Error
4073
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4074
+	 */
4075
+	private function _deduce_column_name_from_query_param($query_param)
4076
+	{
4077
+		$field = $this->_deduce_field_from_query_param($query_param);
4078
+		if ($field) {
4079
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4080
+				$query_param);
4081
+			return $table_alias_prefix . $field->get_qualified_column();
4082
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4083
+			//maybe it's custom selection item?
4084
+			//if so, just use it as the "column name"
4085
+			return $query_param;
4086
+		} else {
4087
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4088
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4089
+		}
4090
+	}
4091
+
4092
+
4093
+
4094
+	/**
4095
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4096
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4097
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4098
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4099
+	 *
4100
+	 * @param string $condition_query_param_key
4101
+	 * @return string
4102
+	 */
4103
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4104
+	{
4105
+		$pos_of_star = strpos($condition_query_param_key, '*');
4106
+		if ($pos_of_star === false) {
4107
+			return $condition_query_param_key;
4108
+		} else {
4109
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4110
+			return $condition_query_param_sans_star;
4111
+		}
4112
+	}
4113
+
4114
+
4115
+
4116
+	/**
4117
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4118
+	 *
4119
+	 * @param                            mixed      array | string    $op_and_value
4120
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4121
+	 * @throws EE_Error
4122
+	 * @return string
4123
+	 */
4124
+	private function _construct_op_and_value($op_and_value, $field_obj)
4125
+	{
4126
+		if (is_array($op_and_value)) {
4127
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4128
+			if (! $operator) {
4129
+				$php_array_like_string = array();
4130
+				foreach ($op_and_value as $key => $value) {
4131
+					$php_array_like_string[] = "$key=>$value";
4132
+				}
4133
+				throw new EE_Error(
4134
+					sprintf(
4135
+						__(
4136
+							"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))",
4137
+							"event_espresso"
4138
+						),
4139
+						implode(",", $php_array_like_string)
4140
+					)
4141
+				);
4142
+			}
4143
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4144
+		} else {
4145
+			$operator = '=';
4146
+			$value = $op_and_value;
4147
+		}
4148
+		//check to see if the value is actually another field
4149
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4150
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4151
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4152
+			//in this case, the value should be an array, or at least a comma-separated list
4153
+			//it will need to handle a little differently
4154
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4155
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4156
+			return $operator . SP . $cleaned_value;
4157
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4158
+			//the value should be an array with count of two.
4159
+			if (count($value) !== 2) {
4160
+				throw new EE_Error(
4161
+					sprintf(
4162
+						__(
4163
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4164
+							'event_espresso'
4165
+						),
4166
+						"BETWEEN"
4167
+					)
4168
+				);
4169
+			}
4170
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4171
+			return $operator . SP . $cleaned_value;
4172
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4173
+			if ($value !== null) {
4174
+				throw new EE_Error(
4175
+					sprintf(
4176
+						__(
4177
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4178
+							"event_espresso"
4179
+						),
4180
+						$value,
4181
+						$operator
4182
+					)
4183
+				);
4184
+			}
4185
+			return $operator;
4186
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4187
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4188
+			//remove other junk. So just treat it as a string.
4189
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4190
+		} elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4191
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4192
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4193
+			throw new EE_Error(
4194
+				sprintf(
4195
+					__(
4196
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4197
+						'event_espresso'
4198
+					),
4199
+					$operator,
4200
+					$operator
4201
+				)
4202
+			);
4203
+		} elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4204
+			throw new EE_Error(
4205
+				sprintf(
4206
+					__(
4207
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4208
+						'event_espresso'
4209
+					),
4210
+					$operator,
4211
+					$operator
4212
+				)
4213
+			);
4214
+		} else {
4215
+			throw new EE_Error(
4216
+				sprintf(
4217
+					__(
4218
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4219
+						"event_espresso"
4220
+					),
4221
+					http_build_query($op_and_value)
4222
+				)
4223
+			);
4224
+		}
4225
+	}
4226
+
4227
+
4228
+
4229
+	/**
4230
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4231
+	 *
4232
+	 * @param array                      $values
4233
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4234
+	 *                                              '%s'
4235
+	 * @return string
4236
+	 * @throws \EE_Error
4237
+	 */
4238
+	public function _construct_between_value($values, $field_obj)
4239
+	{
4240
+		$cleaned_values = array();
4241
+		foreach ($values as $value) {
4242
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4243
+		}
4244
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4245
+	}
4246
+
4247
+
4248
+
4249
+	/**
4250
+	 * Takes an array or a comma-separated list of $values and cleans them
4251
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4252
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4253
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4254
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4255
+	 *
4256
+	 * @param mixed                      $values    array or comma-separated string
4257
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4258
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4259
+	 * @throws \EE_Error
4260
+	 */
4261
+	public function _construct_in_value($values, $field_obj)
4262
+	{
4263
+		//check if the value is a CSV list
4264
+		if (is_string($values)) {
4265
+			//in which case, turn it into an array
4266
+			$values = explode(",", $values);
4267
+		}
4268
+		$cleaned_values = array();
4269
+		foreach ($values as $value) {
4270
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4271
+		}
4272
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4273
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4274
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4275
+		if (empty($cleaned_values)) {
4276
+			$all_fields = $this->field_settings();
4277
+			$a_field = array_shift($all_fields);
4278
+			$main_table = $this->_get_main_table();
4279
+			$cleaned_values[] = "SELECT "
4280
+								. $a_field->get_table_column()
4281
+								. " FROM "
4282
+								. $main_table->get_table_name()
4283
+								. " WHERE FALSE";
4284
+		}
4285
+		return "(" . implode(",", $cleaned_values) . ")";
4286
+	}
4287
+
4288
+
4289
+
4290
+	/**
4291
+	 * @param mixed                      $value
4292
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4293
+	 * @throws EE_Error
4294
+	 * @return false|null|string
4295
+	 */
4296
+	private function _wpdb_prepare_using_field($value, $field_obj)
4297
+	{
4298
+		/** @type WPDB $wpdb */
4299
+		global $wpdb;
4300
+		if ($field_obj instanceof EE_Model_Field_Base) {
4301
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4302
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4303
+		} else {//$field_obj should really just be a data type
4304
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4305
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4306
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4307
+			}
4308
+			return $wpdb->prepare($field_obj, $value);
4309
+		}
4310
+	}
4311
+
4312
+
4313
+
4314
+	/**
4315
+	 * Takes the input parameter and finds the model field that it indicates.
4316
+	 *
4317
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4318
+	 * @throws EE_Error
4319
+	 * @return EE_Model_Field_Base
4320
+	 */
4321
+	protected function _deduce_field_from_query_param($query_param_name)
4322
+	{
4323
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4324
+		//which will help us find the database table and column
4325
+		$query_param_parts = explode(".", $query_param_name);
4326
+		if (empty($query_param_parts)) {
4327
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4328
+				'event_espresso'), $query_param_name));
4329
+		}
4330
+		$number_of_parts = count($query_param_parts);
4331
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4332
+		if ($number_of_parts === 1) {
4333
+			$field_name = $last_query_param_part;
4334
+			$model_obj = $this;
4335
+		} else {// $number_of_parts >= 2
4336
+			//the last part is the column name, and there are only 2parts. therefore...
4337
+			$field_name = $last_query_param_part;
4338
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4339
+		}
4340
+		try {
4341
+			return $model_obj->field_settings_for($field_name);
4342
+		} catch (EE_Error $e) {
4343
+			return null;
4344
+		}
4345
+	}
4346
+
4347
+
4348
+
4349
+	/**
4350
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4351
+	 * alias and column which corresponds to it
4352
+	 *
4353
+	 * @param string $field_name
4354
+	 * @throws EE_Error
4355
+	 * @return string
4356
+	 */
4357
+	public function _get_qualified_column_for_field($field_name)
4358
+	{
4359
+		$all_fields = $this->field_settings();
4360
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4361
+		if ($field) {
4362
+			return $field->get_qualified_column();
4363
+		} else {
4364
+			throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4365
+				'event_espresso'), $field_name, get_class($this)));
4366
+		}
4367
+	}
4368
+
4369
+
4370
+
4371
+	/**
4372
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4373
+	 * Example usage:
4374
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4375
+	 *      array(),
4376
+	 *      ARRAY_A,
4377
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4378
+	 *  );
4379
+	 * is equivalent to
4380
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4381
+	 * and
4382
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4383
+	 *      array(
4384
+	 *          array(
4385
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4386
+	 *          ),
4387
+	 *          ARRAY_A,
4388
+	 *          implode(
4389
+	 *              ', ',
4390
+	 *              array_merge(
4391
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4392
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4393
+	 *              )
4394
+	 *          )
4395
+	 *      )
4396
+	 *  );
4397
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4398
+	 *
4399
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4400
+	 *                                            and the one whose fields you are selecting for example: when querying
4401
+	 *                                            tickets model and selecting fields from the tickets model you would
4402
+	 *                                            leave this parameter empty, because no models are needed to join
4403
+	 *                                            between the queried model and the selected one. Likewise when
4404
+	 *                                            querying the datetime model and selecting fields from the tickets
4405
+	 *                                            model, it would also be left empty, because there is a direct
4406
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4407
+	 *                                            them together. However, when querying from the event model and
4408
+	 *                                            selecting fields from the ticket model, you should provide the string
4409
+	 *                                            'Datetime', indicating that the event model must first join to the
4410
+	 *                                            datetime model in order to find its relation to ticket model.
4411
+	 *                                            Also, when querying from the venue model and selecting fields from
4412
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4413
+	 *                                            indicating you need to join the venue model to the event model,
4414
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4415
+	 *                                            This string is used to deduce the prefix that gets added onto the
4416
+	 *                                            models' tables qualified columns
4417
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4418
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4419
+	 *                                            qualified column names
4420
+	 * @return array|string
4421
+	 */
4422
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4423
+	{
4424
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4425
+		$qualified_columns = array();
4426
+		foreach ($this->field_settings() as $field_name => $field) {
4427
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4428
+		}
4429
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4430
+	}
4431
+
4432
+
4433
+
4434
+	/**
4435
+	 * constructs the select use on special limit joins
4436
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4437
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4438
+	 * (as that is typically where the limits would be set).
4439
+	 *
4440
+	 * @param  string       $table_alias The table the select is being built for
4441
+	 * @param  mixed|string $limit       The limit for this select
4442
+	 * @return string                The final select join element for the query.
4443
+	 */
4444
+	public function _construct_limit_join_select($table_alias, $limit)
4445
+	{
4446
+		$SQL = '';
4447
+		foreach ($this->_tables as $table_obj) {
4448
+			if ($table_obj instanceof EE_Primary_Table) {
4449
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4450
+					? $table_obj->get_select_join_limit($limit)
4451
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4452
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4453
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4454
+					? $table_obj->get_select_join_limit_join($limit)
4455
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4456
+			}
4457
+		}
4458
+		return $SQL;
4459
+	}
4460
+
4461
+
4462
+
4463
+	/**
4464
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4465
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4466
+	 *
4467
+	 * @return string SQL
4468
+	 * @throws \EE_Error
4469
+	 */
4470
+	public function _construct_internal_join()
4471
+	{
4472
+		$SQL = $this->_get_main_table()->get_table_sql();
4473
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4474
+		return $SQL;
4475
+	}
4476
+
4477
+
4478
+
4479
+	/**
4480
+	 * Constructs the SQL for joining all the tables on this model.
4481
+	 * Normally $alias should be the primary table's alias, but in cases where
4482
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4483
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4484
+	 * alias, this will construct SQL like:
4485
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4486
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4487
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4488
+	 *
4489
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4490
+	 * @return string
4491
+	 */
4492
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4493
+	{
4494
+		$SQL = '';
4495
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4496
+		foreach ($this->_tables as $table_obj) {
4497
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4498
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4499
+					//so we're joining to this table, meaning the table is already in
4500
+					//the FROM statement, BUT the primary table isn't. So we want
4501
+					//to add the inverse join sql
4502
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4503
+				} else {
4504
+					//just add a regular JOIN to this table from the primary table
4505
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4506
+				}
4507
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4508
+		}
4509
+		return $SQL;
4510
+	}
4511
+
4512
+
4513
+
4514
+	/**
4515
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4516
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4517
+	 * their data type (eg, '%s', '%d', etc)
4518
+	 *
4519
+	 * @return array
4520
+	 */
4521
+	public function _get_data_types()
4522
+	{
4523
+		$data_types = array();
4524
+		foreach ($this->field_settings() as $field_obj) {
4525
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4526
+			/** @var $field_obj EE_Model_Field_Base */
4527
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4528
+		}
4529
+		return $data_types;
4530
+	}
4531
+
4532
+
4533
+
4534
+	/**
4535
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4536
+	 *
4537
+	 * @param string $model_name
4538
+	 * @throws EE_Error
4539
+	 * @return EEM_Base
4540
+	 */
4541
+	public function get_related_model_obj($model_name)
4542
+	{
4543
+		$model_classname = "EEM_" . $model_name;
4544
+		if (! class_exists($model_classname)) {
4545
+			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",
4546
+				'event_espresso'), $model_name, $model_classname));
4547
+		}
4548
+		return call_user_func($model_classname . "::instance");
4549
+	}
4550
+
4551
+
4552
+
4553
+	/**
4554
+	 * Returns the array of EE_ModelRelations for this model.
4555
+	 *
4556
+	 * @return EE_Model_Relation_Base[]
4557
+	 */
4558
+	public function relation_settings()
4559
+	{
4560
+		return $this->_model_relations;
4561
+	}
4562
+
4563
+
4564
+
4565
+	/**
4566
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4567
+	 * because without THOSE models, this model probably doesn't have much purpose.
4568
+	 * (Eg, without an event, datetimes have little purpose.)
4569
+	 *
4570
+	 * @return EE_Belongs_To_Relation[]
4571
+	 */
4572
+	public function belongs_to_relations()
4573
+	{
4574
+		$belongs_to_relations = array();
4575
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4576
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4577
+				$belongs_to_relations[$model_name] = $relation_obj;
4578
+			}
4579
+		}
4580
+		return $belongs_to_relations;
4581
+	}
4582
+
4583
+
4584
+
4585
+	/**
4586
+	 * Returns the specified EE_Model_Relation, or throws an exception
4587
+	 *
4588
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4589
+	 * @throws EE_Error
4590
+	 * @return EE_Model_Relation_Base
4591
+	 */
4592
+	public function related_settings_for($relation_name)
4593
+	{
4594
+		$relatedModels = $this->relation_settings();
4595
+		if (! array_key_exists($relation_name, $relatedModels)) {
4596
+			throw new EE_Error(
4597
+				sprintf(
4598
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4599
+						'event_espresso'),
4600
+					$relation_name,
4601
+					$this->_get_class_name(),
4602
+					implode(', ', array_keys($relatedModels))
4603
+				)
4604
+			);
4605
+		}
4606
+		return $relatedModels[$relation_name];
4607
+	}
4608
+
4609
+
4610
+
4611
+	/**
4612
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4613
+	 * fields
4614
+	 *
4615
+	 * @param string $fieldName
4616
+	 * @throws EE_Error
4617
+	 * @return EE_Model_Field_Base
4618
+	 */
4619
+	public function field_settings_for($fieldName)
4620
+	{
4621
+		$fieldSettings = $this->field_settings(true);
4622
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4623
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4624
+				get_class($this)));
4625
+		}
4626
+		return $fieldSettings[$fieldName];
4627
+	}
4628
+
4629
+
4630
+
4631
+	/**
4632
+	 * Checks if this field exists on this model
4633
+	 *
4634
+	 * @param string $fieldName a key in the model's _field_settings array
4635
+	 * @return boolean
4636
+	 */
4637
+	public function has_field($fieldName)
4638
+	{
4639
+		$fieldSettings = $this->field_settings(true);
4640
+		if (isset($fieldSettings[$fieldName])) {
4641
+			return true;
4642
+		} else {
4643
+			return false;
4644
+		}
4645
+	}
4646
+
4647
+
4648
+
4649
+	/**
4650
+	 * Returns whether or not this model has a relation to the specified model
4651
+	 *
4652
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4653
+	 * @return boolean
4654
+	 */
4655
+	public function has_relation($relation_name)
4656
+	{
4657
+		$relations = $this->relation_settings();
4658
+		if (isset($relations[$relation_name])) {
4659
+			return true;
4660
+		} else {
4661
+			return false;
4662
+		}
4663
+	}
4664
+
4665
+
4666
+
4667
+	/**
4668
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4669
+	 * Eg, on EE_Answer that would be ANS_ID field object
4670
+	 *
4671
+	 * @param $field_obj
4672
+	 * @return boolean
4673
+	 */
4674
+	public function is_primary_key_field($field_obj)
4675
+	{
4676
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4677
+	}
4678
+
4679
+
4680
+
4681
+	/**
4682
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4683
+	 * Eg, on EE_Answer that would be ANS_ID field object
4684
+	 *
4685
+	 * @return EE_Model_Field_Base
4686
+	 * @throws EE_Error
4687
+	 */
4688
+	public function get_primary_key_field()
4689
+	{
4690
+		if ($this->_primary_key_field === null) {
4691
+			foreach ($this->field_settings(true) as $field_obj) {
4692
+				if ($this->is_primary_key_field($field_obj)) {
4693
+					$this->_primary_key_field = $field_obj;
4694
+					break;
4695
+				}
4696
+			}
4697
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4698
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4699
+					get_class($this)));
4700
+			}
4701
+		}
4702
+		return $this->_primary_key_field;
4703
+	}
4704
+
4705
+
4706
+
4707
+	/**
4708
+	 * Returns whether or not not there is a primary key on this model.
4709
+	 * Internally does some caching.
4710
+	 *
4711
+	 * @return boolean
4712
+	 */
4713
+	public function has_primary_key_field()
4714
+	{
4715
+		if ($this->_has_primary_key_field === null) {
4716
+			try {
4717
+				$this->get_primary_key_field();
4718
+				$this->_has_primary_key_field = true;
4719
+			} catch (EE_Error $e) {
4720
+				$this->_has_primary_key_field = false;
4721
+			}
4722
+		}
4723
+		return $this->_has_primary_key_field;
4724
+	}
4725
+
4726
+
4727
+
4728
+	/**
4729
+	 * Finds the first field of type $field_class_name.
4730
+	 *
4731
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4732
+	 *                                 EE_Foreign_Key_Field, etc
4733
+	 * @return EE_Model_Field_Base or null if none is found
4734
+	 */
4735
+	public function get_a_field_of_type($field_class_name)
4736
+	{
4737
+		foreach ($this->field_settings() as $field) {
4738
+			if ($field instanceof $field_class_name) {
4739
+				return $field;
4740
+			}
4741
+		}
4742
+		return null;
4743
+	}
4744
+
4745
+
4746
+
4747
+	/**
4748
+	 * Gets a foreign key field pointing to model.
4749
+	 *
4750
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4751
+	 * @return EE_Foreign_Key_Field_Base
4752
+	 * @throws EE_Error
4753
+	 */
4754
+	public function get_foreign_key_to($model_name)
4755
+	{
4756
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4757
+			foreach ($this->field_settings() as $field) {
4758
+				if (
4759
+					$field instanceof EE_Foreign_Key_Field_Base
4760
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4761
+				) {
4762
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4763
+					break;
4764
+				}
4765
+			}
4766
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4767
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4768
+					'event_espresso'), $model_name, get_class($this)));
4769
+			}
4770
+		}
4771
+		return $this->_cache_foreign_key_to_fields[$model_name];
4772
+	}
4773
+
4774
+
4775
+
4776
+	/**
4777
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4778
+	 *
4779
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4780
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4781
+	 *                            Either one works
4782
+	 * @return string
4783
+	 */
4784
+	public function get_table_for_alias($table_alias)
4785
+	{
4786
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4787
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4788
+	}
4789
+
4790
+
4791
+
4792
+	/**
4793
+	 * Returns a flat array of all field son this model, instead of organizing them
4794
+	 * by table_alias as they are in the constructor.
4795
+	 *
4796
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4797
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4798
+	 */
4799
+	public function field_settings($include_db_only_fields = false)
4800
+	{
4801
+		if ($include_db_only_fields) {
4802
+			if ($this->_cached_fields === null) {
4803
+				$this->_cached_fields = array();
4804
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4805
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4806
+						$this->_cached_fields[$field_name] = $field_obj;
4807
+					}
4808
+				}
4809
+			}
4810
+			return $this->_cached_fields;
4811
+		} else {
4812
+			if ($this->_cached_fields_non_db_only === null) {
4813
+				$this->_cached_fields_non_db_only = array();
4814
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4815
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4816
+						/** @var $field_obj EE_Model_Field_Base */
4817
+						if (! $field_obj->is_db_only_field()) {
4818
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4819
+						}
4820
+					}
4821
+				}
4822
+			}
4823
+			return $this->_cached_fields_non_db_only;
4824
+		}
4825
+	}
4826
+
4827
+
4828
+
4829
+	/**
4830
+	 *        cycle though array of attendees and create objects out of each item
4831
+	 *
4832
+	 * @access        private
4833
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4834
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4835
+	 *                           numerically indexed)
4836
+	 * @throws \EE_Error
4837
+	 */
4838
+	protected function _create_objects($rows = array())
4839
+	{
4840
+		$array_of_objects = array();
4841
+		if (empty($rows)) {
4842
+			return array();
4843
+		}
4844
+		$count_if_model_has_no_primary_key = 0;
4845
+		$has_primary_key = $this->has_primary_key_field();
4846
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4847
+		foreach ((array)$rows as $row) {
4848
+			if (empty($row)) {
4849
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4850
+				return array();
4851
+			}
4852
+			//check if we've already set this object in the results array,
4853
+			//in which case there's no need to process it further (again)
4854
+			if ($has_primary_key) {
4855
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4856
+					$row,
4857
+					$primary_key_field->get_qualified_column(),
4858
+					$primary_key_field->get_table_column()
4859
+				);
4860
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4861
+					continue;
4862
+				}
4863
+			}
4864
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4865
+			if (! $classInstance) {
4866
+				throw new EE_Error(
4867
+					sprintf(
4868
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4869
+						$this->get_this_model_name(),
4870
+						http_build_query($row)
4871
+					)
4872
+				);
4873
+			}
4874
+			//set the timezone on the instantiated objects
4875
+			$classInstance->set_timezone($this->_timezone);
4876
+			//make sure if there is any timezone setting present that we set the timezone for the object
4877
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4878
+			$array_of_objects[$key] = $classInstance;
4879
+			//also, for all the relations of type BelongsTo, see if we can cache
4880
+			//those related models
4881
+			//(we could do this for other relations too, but if there are conditions
4882
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4883
+			//so it requires a little more thought than just caching them immediately...)
4884
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4885
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4886
+					//check if this model's INFO is present. If so, cache it on the model
4887
+					$other_model = $relation_obj->get_other_model();
4888
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4889
+					//if we managed to make a model object from the results, cache it on the main model object
4890
+					if ($other_model_obj_maybe) {
4891
+						//set timezone on these other model objects if they are present
4892
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4893
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4894
+					}
4895
+				}
4896
+			}
4897
+		}
4898
+		return $array_of_objects;
4899
+	}
4900
+
4901
+
4902
+
4903
+	/**
4904
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4905
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4906
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4907
+	 * object (as set in the model_field!).
4908
+	 *
4909
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4910
+	 */
4911
+	public function create_default_object()
4912
+	{
4913
+		$this_model_fields_and_values = array();
4914
+		//setup the row using default values;
4915
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4916
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4917
+		}
4918
+		$className = $this->_get_class_name();
4919
+		$classInstance = EE_Registry::instance()
4920
+									->load_class($className, array($this_model_fields_and_values), false, false);
4921
+		return $classInstance;
4922
+	}
4923
+
4924
+
4925
+
4926
+	/**
4927
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4928
+	 *                             or an stdClass where each property is the name of a column,
4929
+	 * @return EE_Base_Class
4930
+	 * @throws \EE_Error
4931
+	 */
4932
+	public function instantiate_class_from_array_or_object($cols_n_values)
4933
+	{
4934
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4935
+			$cols_n_values = get_object_vars($cols_n_values);
4936
+		}
4937
+		$primary_key = null;
4938
+		//make sure the array only has keys that are fields/columns on this model
4939
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4940
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4941
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4942
+		}
4943
+		$className = $this->_get_class_name();
4944
+		//check we actually found results that we can use to build our model object
4945
+		//if not, return null
4946
+		if ($this->has_primary_key_field()) {
4947
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4948
+				return null;
4949
+			}
4950
+		} else if ($this->unique_indexes()) {
4951
+			$first_column = reset($this_model_fields_n_values);
4952
+			if (empty($first_column)) {
4953
+				return null;
4954
+			}
4955
+		}
4956
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4957
+		if ($primary_key) {
4958
+			$classInstance = $this->get_from_entity_map($primary_key);
4959
+			if (! $classInstance) {
4960
+				$classInstance = EE_Registry::instance()
4961
+											->load_class($className,
4962
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4963
+				// add this new object to the entity map
4964
+				$classInstance = $this->add_to_entity_map($classInstance);
4965
+			}
4966
+		} else {
4967
+			$classInstance = EE_Registry::instance()
4968
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4969
+											true, false);
4970
+		}
4971
+		//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4972
+		$this->set_timezone($classInstance->get_timezone());
4973
+		return $classInstance;
4974
+	}
4975
+
4976
+
4977
+
4978
+	/**
4979
+	 * Gets the model object from the  entity map if it exists
4980
+	 *
4981
+	 * @param int|string $id the ID of the model object
4982
+	 * @return EE_Base_Class
4983
+	 */
4984
+	public function get_from_entity_map($id)
4985
+	{
4986
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4987
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4988
+	}
4989
+
4990
+
4991
+
4992
+	/**
4993
+	 * add_to_entity_map
4994
+	 * Adds the object to the model's entity mappings
4995
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4996
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4997
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4998
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4999
+	 *        then this method should be called immediately after the update query
5000
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5001
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5002
+	 *
5003
+	 * @param    EE_Base_Class $object
5004
+	 * @throws EE_Error
5005
+	 * @return \EE_Base_Class
5006
+	 */
5007
+	public function add_to_entity_map(EE_Base_Class $object)
5008
+	{
5009
+		$className = $this->_get_class_name();
5010
+		if (! $object instanceof $className) {
5011
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5012
+				is_object($object) ? get_class($object) : $object, $className));
5013
+		}
5014
+		/** @var $object EE_Base_Class */
5015
+		if (! $object->ID()) {
5016
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5017
+				"event_espresso"), get_class($this)));
5018
+		}
5019
+		// double check it's not already there
5020
+		$classInstance = $this->get_from_entity_map($object->ID());
5021
+		if ($classInstance) {
5022
+			return $classInstance;
5023
+		} else {
5024
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5025
+			return $object;
5026
+		}
5027
+	}
5028
+
5029
+
5030
+
5031
+	/**
5032
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5033
+	 * if no identifier is provided, then the entire entity map is emptied
5034
+	 *
5035
+	 * @param int|string $id the ID of the model object
5036
+	 * @return boolean
5037
+	 */
5038
+	public function clear_entity_map($id = null)
5039
+	{
5040
+		if (empty($id)) {
5041
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5042
+			return true;
5043
+		}
5044
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5045
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5046
+			return true;
5047
+		}
5048
+		return false;
5049
+	}
5050
+
5051
+
5052
+
5053
+	/**
5054
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5055
+	 * Given an array where keys are column (or column alias) names and values,
5056
+	 * returns an array of their corresponding field names and database values
5057
+	 *
5058
+	 * @param array $cols_n_values
5059
+	 * @return array
5060
+	 */
5061
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5062
+	{
5063
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5064
+	}
5065
+
5066
+
5067
+
5068
+	/**
5069
+	 * _deduce_fields_n_values_from_cols_n_values
5070
+	 * Given an array where keys are column (or column alias) names and values,
5071
+	 * returns an array of their corresponding field names and database values
5072
+	 *
5073
+	 * @param string $cols_n_values
5074
+	 * @return array
5075
+	 */
5076
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5077
+	{
5078
+		$this_model_fields_n_values = array();
5079
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5080
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5081
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5082
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5083
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5084
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5085
+					if (! $field_obj->is_db_only_field()) {
5086
+						//prepare field as if its coming from db
5087
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5088
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5089
+					}
5090
+				}
5091
+			} else {
5092
+				//the table's rows existed. Use their values
5093
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5094
+					if (! $field_obj->is_db_only_field()) {
5095
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5096
+							$cols_n_values, $field_obj->get_qualified_column(),
5097
+							$field_obj->get_table_column()
5098
+						);
5099
+					}
5100
+				}
5101
+			}
5102
+		}
5103
+		return $this_model_fields_n_values;
5104
+	}
5105
+
5106
+
5107
+
5108
+	/**
5109
+	 * @param $cols_n_values
5110
+	 * @param $qualified_column
5111
+	 * @param $regular_column
5112
+	 * @return null
5113
+	 */
5114
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5115
+	{
5116
+		$value = null;
5117
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5118
+		//does the field on the model relate to this column retrieved from the db?
5119
+		//or is it a db-only field? (not relating to the model)
5120
+		if (isset($cols_n_values[$qualified_column])) {
5121
+			$value = $cols_n_values[$qualified_column];
5122
+		} elseif (isset($cols_n_values[$regular_column])) {
5123
+			$value = $cols_n_values[$regular_column];
5124
+		}
5125
+		return $value;
5126
+	}
5127
+
5128
+
5129
+
5130
+	/**
5131
+	 * refresh_entity_map_from_db
5132
+	 * Makes sure the model object in the entity map at $id assumes the values
5133
+	 * of the database (opposite of EE_base_Class::save())
5134
+	 *
5135
+	 * @param int|string $id
5136
+	 * @return EE_Base_Class
5137
+	 * @throws \EE_Error
5138
+	 */
5139
+	public function refresh_entity_map_from_db($id)
5140
+	{
5141
+		$obj_in_map = $this->get_from_entity_map($id);
5142
+		if ($obj_in_map) {
5143
+			$wpdb_results = $this->_get_all_wpdb_results(
5144
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5145
+			);
5146
+			if ($wpdb_results && is_array($wpdb_results)) {
5147
+				$one_row = reset($wpdb_results);
5148
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5149
+					$obj_in_map->set_from_db($field_name, $db_value);
5150
+				}
5151
+				//clear the cache of related model objects
5152
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5153
+					$obj_in_map->clear_cache($relation_name, null, true);
5154
+				}
5155
+			}
5156
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5157
+			return $obj_in_map;
5158
+		} else {
5159
+			return $this->get_one_by_ID($id);
5160
+		}
5161
+	}
5162
+
5163
+
5164
+
5165
+	/**
5166
+	 * refresh_entity_map_with
5167
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5168
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5169
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5170
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5171
+	 *
5172
+	 * @param int|string    $id
5173
+	 * @param EE_Base_Class $replacing_model_obj
5174
+	 * @return \EE_Base_Class
5175
+	 * @throws \EE_Error
5176
+	 */
5177
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5178
+	{
5179
+		$obj_in_map = $this->get_from_entity_map($id);
5180
+		if ($obj_in_map) {
5181
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5182
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5183
+					$obj_in_map->set($field_name, $value);
5184
+				}
5185
+				//make the model object in the entity map's cache match the $replacing_model_obj
5186
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5187
+					$obj_in_map->clear_cache($relation_name, null, true);
5188
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5189
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5190
+					}
5191
+				}
5192
+			}
5193
+			return $obj_in_map;
5194
+		} else {
5195
+			$this->add_to_entity_map($replacing_model_obj);
5196
+			return $replacing_model_obj;
5197
+		}
5198
+	}
5199
+
5200
+
5201
+
5202
+	/**
5203
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5204
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5205
+	 * require_once($this->_getClassName().".class.php");
5206
+	 *
5207
+	 * @return string
5208
+	 */
5209
+	private function _get_class_name()
5210
+	{
5211
+		return "EE_" . $this->get_this_model_name();
5212
+	}
5213
+
5214
+
5215
+
5216
+	/**
5217
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5218
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5219
+	 * it would be 'Events'.
5220
+	 *
5221
+	 * @param int $quantity
5222
+	 * @return string
5223
+	 */
5224
+	public function item_name($quantity = 1)
5225
+	{
5226
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5227
+	}
5228
+
5229
+
5230
+
5231
+	/**
5232
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5233
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5234
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5235
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5236
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5237
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5238
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5239
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5240
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5241
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5242
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5243
+	 *        return $previousReturnValue.$returnString;
5244
+	 * }
5245
+	 * require('EEM_Answer.model.php');
5246
+	 * $answer=EEM_Answer::instance();
5247
+	 * echo $answer->my_callback('monkeys',100);
5248
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5249
+	 *
5250
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5251
+	 * @param array  $args       array of original arguments passed to the function
5252
+	 * @throws EE_Error
5253
+	 * @return mixed whatever the plugin which calls add_filter decides
5254
+	 */
5255
+	public function __call($methodName, $args)
5256
+	{
5257
+		$className = get_class($this);
5258
+		$tagName = "FHEE__{$className}__{$methodName}";
5259
+		if (! has_filter($tagName)) {
5260
+			throw new EE_Error(
5261
+				sprintf(
5262
+					__('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 );',
5263
+						'event_espresso'),
5264
+					$methodName,
5265
+					$className,
5266
+					$tagName,
5267
+					'<br />'
5268
+				)
5269
+			);
5270
+		}
5271
+		return apply_filters($tagName, null, $this, $args);
5272
+	}
5273
+
5274
+
5275
+
5276
+	/**
5277
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5278
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5279
+	 *
5280
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5281
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5282
+	 *                                                       the object's class name
5283
+	 *                                                       or object's ID
5284
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5285
+	 *                                                       exists in the database. If it does not, we add it
5286
+	 * @throws EE_Error
5287
+	 * @return EE_Base_Class
5288
+	 */
5289
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5290
+	{
5291
+		$className = $this->_get_class_name();
5292
+		if ($base_class_obj_or_id instanceof $className) {
5293
+			$model_object = $base_class_obj_or_id;
5294
+		} else {
5295
+			$primary_key_field = $this->get_primary_key_field();
5296
+			if (
5297
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5298
+				&& (
5299
+					is_int($base_class_obj_or_id)
5300
+					|| is_string($base_class_obj_or_id)
5301
+				)
5302
+			) {
5303
+				// assume it's an ID.
5304
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5305
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5306
+			} else if (
5307
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5308
+				&& is_string($base_class_obj_or_id)
5309
+			) {
5310
+				// assume its a string representation of the object
5311
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5312
+			} else {
5313
+				throw new EE_Error(
5314
+					sprintf(
5315
+						__(
5316
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5317
+							'event_espresso'
5318
+						),
5319
+						$base_class_obj_or_id,
5320
+						$this->_get_class_name(),
5321
+						print_r($base_class_obj_or_id, true)
5322
+					)
5323
+				);
5324
+			}
5325
+		}
5326
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5327
+			$model_object->save();
5328
+		}
5329
+		return $model_object;
5330
+	}
5331
+
5332
+
5333
+
5334
+	/**
5335
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5336
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5337
+	 * returns it ID.
5338
+	 *
5339
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5340
+	 * @return int|string depending on the type of this model object's ID
5341
+	 * @throws EE_Error
5342
+	 */
5343
+	public function ensure_is_ID($base_class_obj_or_id)
5344
+	{
5345
+		$className = $this->_get_class_name();
5346
+		if ($base_class_obj_or_id instanceof $className) {
5347
+			/** @var $base_class_obj_or_id EE_Base_Class */
5348
+			$id = $base_class_obj_or_id->ID();
5349
+		} elseif (is_int($base_class_obj_or_id)) {
5350
+			//assume it's an ID
5351
+			$id = $base_class_obj_or_id;
5352
+		} elseif (is_string($base_class_obj_or_id)) {
5353
+			//assume its a string representation of the object
5354
+			$id = $base_class_obj_or_id;
5355
+		} else {
5356
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5357
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5358
+				print_r($base_class_obj_or_id, true)));
5359
+		}
5360
+		return $id;
5361
+	}
5362
+
5363
+
5364
+
5365
+	/**
5366
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5367
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5368
+	 * been sanitized and converted into the appropriate domain.
5369
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5370
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5371
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5372
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5373
+	 * $EVT = EEM_Event::instance(); $old_setting =
5374
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5375
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5376
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5377
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5378
+	 *
5379
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5380
+	 * @return void
5381
+	 */
5382
+	public function assume_values_already_prepared_by_model_object(
5383
+		$values_already_prepared = self::not_prepared_by_model_object
5384
+	) {
5385
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5386
+	}
5387
+
5388
+
5389
+
5390
+	/**
5391
+	 * Read comments for assume_values_already_prepared_by_model_object()
5392
+	 *
5393
+	 * @return int
5394
+	 */
5395
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5396
+	{
5397
+		return $this->_values_already_prepared_by_model_object;
5398
+	}
5399
+
5400
+
5401
+
5402
+	/**
5403
+	 * Gets all the indexes on this model
5404
+	 *
5405
+	 * @return EE_Index[]
5406
+	 */
5407
+	public function indexes()
5408
+	{
5409
+		return $this->_indexes;
5410
+	}
5411
+
5412
+
5413
+
5414
+	/**
5415
+	 * Gets all the Unique Indexes on this model
5416
+	 *
5417
+	 * @return EE_Unique_Index[]
5418
+	 */
5419
+	public function unique_indexes()
5420
+	{
5421
+		$unique_indexes = array();
5422
+		foreach ($this->_indexes as $name => $index) {
5423
+			if ($index instanceof EE_Unique_Index) {
5424
+				$unique_indexes [$name] = $index;
5425
+			}
5426
+		}
5427
+		return $unique_indexes;
5428
+	}
5429
+
5430
+
5431
+
5432
+	/**
5433
+	 * Gets all the fields which, when combined, make the primary key.
5434
+	 * This is usually just an array with 1 element (the primary key), but in cases
5435
+	 * where there is no primary key, it's a combination of fields as defined
5436
+	 * on a primary index
5437
+	 *
5438
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5439
+	 * @throws \EE_Error
5440
+	 */
5441
+	public function get_combined_primary_key_fields()
5442
+	{
5443
+		foreach ($this->indexes() as $index) {
5444
+			if ($index instanceof EE_Primary_Key_Index) {
5445
+				return $index->fields();
5446
+			}
5447
+		}
5448
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5449
+	}
5450
+
5451
+
5452
+
5453
+	/**
5454
+	 * Used to build a primary key string (when the model has no primary key),
5455
+	 * which can be used a unique string to identify this model object.
5456
+	 *
5457
+	 * @param array $cols_n_values keys are field names, values are their values
5458
+	 * @return string
5459
+	 * @throws \EE_Error
5460
+	 */
5461
+	public function get_index_primary_key_string($cols_n_values)
5462
+	{
5463
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5464
+			$this->get_combined_primary_key_fields());
5465
+		return http_build_query($cols_n_values_for_primary_key_index);
5466
+	}
5467
+
5468
+
5469
+
5470
+	/**
5471
+	 * Gets the field values from the primary key string
5472
+	 *
5473
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5474
+	 * @param string $index_primary_key_string
5475
+	 * @return null|array
5476
+	 * @throws \EE_Error
5477
+	 */
5478
+	public function parse_index_primary_key_string($index_primary_key_string)
5479
+	{
5480
+		$key_fields = $this->get_combined_primary_key_fields();
5481
+		//check all of them are in the $id
5482
+		$key_vals_in_combined_pk = array();
5483
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5484
+		foreach ($key_fields as $key_field_name => $field_obj) {
5485
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5486
+				return null;
5487
+			}
5488
+		}
5489
+		return $key_vals_in_combined_pk;
5490
+	}
5491
+
5492
+
5493
+
5494
+	/**
5495
+	 * verifies that an array of key-value pairs for model fields has a key
5496
+	 * for each field comprising the primary key index
5497
+	 *
5498
+	 * @param array $key_vals
5499
+	 * @return boolean
5500
+	 * @throws \EE_Error
5501
+	 */
5502
+	public function has_all_combined_primary_key_fields($key_vals)
5503
+	{
5504
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5505
+		foreach ($keys_it_should_have as $key) {
5506
+			if (! isset($key_vals[$key])) {
5507
+				return false;
5508
+			}
5509
+		}
5510
+		return true;
5511
+	}
5512
+
5513
+
5514
+
5515
+	/**
5516
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5517
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5518
+	 *
5519
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5520
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5521
+	 * @throws EE_Error
5522
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5523
+	 *                                                              indexed)
5524
+	 */
5525
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5526
+	{
5527
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5528
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5529
+		} elseif (is_array($model_object_or_attributes_array)) {
5530
+			$attributes_array = $model_object_or_attributes_array;
5531
+		} else {
5532
+			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",
5533
+				"event_espresso"), $model_object_or_attributes_array));
5534
+		}
5535
+		//even copies obviously won't have the same ID, so remove the primary key
5536
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5537
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5538
+			unset($attributes_array[$this->primary_key_name()]);
5539
+		}
5540
+		if (isset($query_params[0])) {
5541
+			$query_params[0] = array_merge($attributes_array, $query_params);
5542
+		} else {
5543
+			$query_params[0] = $attributes_array;
5544
+		}
5545
+		return $this->get_all($query_params);
5546
+	}
5547
+
5548
+
5549
+
5550
+	/**
5551
+	 * Gets the first copy we find. See get_all_copies for more details
5552
+	 *
5553
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5554
+	 * @param array $query_params
5555
+	 * @return EE_Base_Class
5556
+	 * @throws \EE_Error
5557
+	 */
5558
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5559
+	{
5560
+		if (! is_array($query_params)) {
5561
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5562
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5563
+					gettype($query_params)), '4.6.0');
5564
+			$query_params = array();
5565
+		}
5566
+		$query_params['limit'] = 1;
5567
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5568
+		if (is_array($copies)) {
5569
+			return array_shift($copies);
5570
+		} else {
5571
+			return null;
5572
+		}
5573
+	}
5574
+
5575
+
5576
+
5577
+	/**
5578
+	 * Updates the item with the specified id. Ignores default query parameters because
5579
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5580
+	 *
5581
+	 * @param array      $fields_n_values keys are field names, values are their new values
5582
+	 * @param int|string $id              the value of the primary key to update
5583
+	 * @return int number of rows updated
5584
+	 * @throws \EE_Error
5585
+	 */
5586
+	public function update_by_ID($fields_n_values, $id)
5587
+	{
5588
+		$query_params = array(
5589
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5590
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5591
+		);
5592
+		return $this->update($fields_n_values, $query_params);
5593
+	}
5594
+
5595
+
5596
+
5597
+	/**
5598
+	 * Changes an operator which was supplied to the models into one usable in SQL
5599
+	 *
5600
+	 * @param string $operator_supplied
5601
+	 * @return string an operator which can be used in SQL
5602
+	 * @throws EE_Error
5603
+	 */
5604
+	private function _prepare_operator_for_sql($operator_supplied)
5605
+	{
5606
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5607
+			: null;
5608
+		if ($sql_operator) {
5609
+			return $sql_operator;
5610
+		} else {
5611
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5612
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5613
+		}
5614
+	}
5615
+
5616
+
5617
+
5618
+	/**
5619
+	 * Gets an array where keys are the primary keys and values are their 'names'
5620
+	 * (as determined by the model object's name() function, which is often overridden)
5621
+	 *
5622
+	 * @param array $query_params like get_all's
5623
+	 * @return string[]
5624
+	 * @throws \EE_Error
5625
+	 */
5626
+	public function get_all_names($query_params = array())
5627
+	{
5628
+		$objs = $this->get_all($query_params);
5629
+		$names = array();
5630
+		foreach ($objs as $obj) {
5631
+			$names[$obj->ID()] = $obj->name();
5632
+		}
5633
+		return $names;
5634
+	}
5635
+
5636
+
5637
+
5638
+	/**
5639
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5640
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5641
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5642
+	 * array_keys() on $model_objects.
5643
+	 *
5644
+	 * @param \EE_Base_Class[] $model_objects
5645
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5646
+	 *                                               in the returned array
5647
+	 * @return array
5648
+	 * @throws \EE_Error
5649
+	 */
5650
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5651
+	{
5652
+		if (! $this->has_primary_key_field()) {
5653
+			if (WP_DEBUG) {
5654
+				EE_Error::add_error(
5655
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5656
+					__FILE__,
5657
+					__FUNCTION__,
5658
+					__LINE__
5659
+				);
5660
+			}
5661
+		}
5662
+		$IDs = array();
5663
+		foreach ($model_objects as $model_object) {
5664
+			$id = $model_object->ID();
5665
+			if (! $id) {
5666
+				if ($filter_out_empty_ids) {
5667
+					continue;
5668
+				}
5669
+				if (WP_DEBUG) {
5670
+					EE_Error::add_error(
5671
+						__(
5672
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5673
+							'event_espresso'
5674
+						),
5675
+						__FILE__,
5676
+						__FUNCTION__,
5677
+						__LINE__
5678
+					);
5679
+				}
5680
+			}
5681
+			$IDs[] = $id;
5682
+		}
5683
+		return $IDs;
5684
+	}
5685
+
5686
+
5687
+
5688
+	/**
5689
+	 * Returns the string used in capabilities relating to this model. If there
5690
+	 * are no capabilities that relate to this model returns false
5691
+	 *
5692
+	 * @return string|false
5693
+	 */
5694
+	public function cap_slug()
5695
+	{
5696
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5697
+	}
5698
+
5699
+
5700
+
5701
+	/**
5702
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5703
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5704
+	 * only returns the cap restrictions array in that context (ie, the array
5705
+	 * at that key)
5706
+	 *
5707
+	 * @param string $context
5708
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5709
+	 * @throws \EE_Error
5710
+	 */
5711
+	public function cap_restrictions($context = EEM_Base::caps_read)
5712
+	{
5713
+		EEM_Base::verify_is_valid_cap_context($context);
5714
+		//check if we ought to run the restriction generator first
5715
+		if (
5716
+			isset($this->_cap_restriction_generators[$context])
5717
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5718
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5719
+		) {
5720
+			$this->_cap_restrictions[$context] = array_merge(
5721
+				$this->_cap_restrictions[$context],
5722
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5723
+			);
5724
+		}
5725
+		//and make sure we've finalized the construction of each restriction
5726
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5727
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5728
+				$where_conditions_obj->_finalize_construct($this);
5729
+			}
5730
+		}
5731
+		return $this->_cap_restrictions[$context];
5732
+	}
5733
+
5734
+
5735
+
5736
+	/**
5737
+	 * Indicating whether or not this model thinks its a wp core model
5738
+	 *
5739
+	 * @return boolean
5740
+	 */
5741
+	public function is_wp_core_model()
5742
+	{
5743
+		return $this->_wp_core_model;
5744
+	}
5745
+
5746
+
5747
+
5748
+	/**
5749
+	 * Gets all the caps that are missing which impose a restriction on
5750
+	 * queries made in this context
5751
+	 *
5752
+	 * @param string $context one of EEM_Base::caps_ constants
5753
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5754
+	 * @throws \EE_Error
5755
+	 */
5756
+	public function caps_missing($context = EEM_Base::caps_read)
5757
+	{
5758
+		$missing_caps = array();
5759
+		$cap_restrictions = $this->cap_restrictions($context);
5760
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5761
+			if (! EE_Capabilities::instance()
5762
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5763
+			) {
5764
+				$missing_caps[$cap] = $restriction_if_no_cap;
5765
+			}
5766
+		}
5767
+		return $missing_caps;
5768
+	}
5769
+
5770
+
5771
+
5772
+	/**
5773
+	 * Gets the mapping from capability contexts to action strings used in capability names
5774
+	 *
5775
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5776
+	 * one of 'read', 'edit', or 'delete'
5777
+	 */
5778
+	public function cap_contexts_to_cap_action_map()
5779
+	{
5780
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5781
+			$this);
5782
+	}
5783
+
5784
+
5785
+
5786
+	/**
5787
+	 * Gets the action string for the specified capability context
5788
+	 *
5789
+	 * @param string $context
5790
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5791
+	 * @throws \EE_Error
5792
+	 */
5793
+	public function cap_action_for_context($context)
5794
+	{
5795
+		$mapping = $this->cap_contexts_to_cap_action_map();
5796
+		if (isset($mapping[$context])) {
5797
+			return $mapping[$context];
5798
+		}
5799
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5800
+			return $action;
5801
+		}
5802
+		throw new EE_Error(
5803
+			sprintf(
5804
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5805
+				$context,
5806
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5807
+			)
5808
+		);
5809
+	}
5810
+
5811
+
5812
+
5813
+	/**
5814
+	 * Returns all the capability contexts which are valid when querying models
5815
+	 *
5816
+	 * @return array
5817
+	 */
5818
+	public static function valid_cap_contexts()
5819
+	{
5820
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5821
+			self::caps_read,
5822
+			self::caps_read_admin,
5823
+			self::caps_edit,
5824
+			self::caps_delete,
5825
+		));
5826
+	}
5827
+
5828
+
5829
+
5830
+	/**
5831
+	 * Returns all valid options for 'default_where_conditions'
5832
+	 *
5833
+	 * @return array
5834
+	 */
5835
+	public static function valid_default_where_conditions()
5836
+	{
5837
+		return array(
5838
+			EEM_Base::default_where_conditions_all,
5839
+			EEM_Base::default_where_conditions_this_only,
5840
+			EEM_Base::default_where_conditions_others_only,
5841
+			EEM_Base::default_where_conditions_minimum_all,
5842
+			EEM_Base::default_where_conditions_minimum_others,
5843
+			EEM_Base::default_where_conditions_none
5844
+		);
5845
+	}
5846
+
5847
+	// public static function default_where_conditions_full
5848
+	/**
5849
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5850
+	 *
5851
+	 * @param string $context
5852
+	 * @return bool
5853
+	 * @throws \EE_Error
5854
+	 */
5855
+	static public function verify_is_valid_cap_context($context)
5856
+	{
5857
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5858
+		if (in_array($context, $valid_cap_contexts)) {
5859
+			return true;
5860
+		} else {
5861
+			throw new EE_Error(
5862
+				sprintf(
5863
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5864
+						'event_espresso'),
5865
+					$context,
5866
+					'EEM_Base',
5867
+					implode(',', $valid_cap_contexts)
5868
+				)
5869
+			);
5870
+		}
5871
+	}
5872
+
5873
+
5874
+
5875
+	/**
5876
+	 * Clears all the models field caches. This is only useful when a sub-class
5877
+	 * might have added a field or something and these caches might be invalidated
5878
+	 */
5879
+	protected function _invalidate_field_caches()
5880
+	{
5881
+		$this->_cache_foreign_key_to_fields = array();
5882
+		$this->_cached_fields = null;
5883
+		$this->_cached_fields_non_db_only = null;
5884
+	}
5885
+
5886
+
5887
+
5888
+	/**
5889
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5890
+	 * (eg "and", "or", "not").
5891
+	 *
5892
+	 * @return array
5893
+	 */
5894
+	public function logic_query_param_keys()
5895
+	{
5896
+		return $this->_logic_query_param_keys;
5897
+	}
5898
+
5899
+
5900
+
5901
+	/**
5902
+	 * Determines whether or not the where query param array key is for a logic query param.
5903
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5904
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5905
+	 *
5906
+	 * @param $query_param_key
5907
+	 * @return bool
5908
+	 */
5909
+	public function is_logic_query_param_key($query_param_key)
5910
+	{
5911
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5912
+			if ($query_param_key === $logic_query_param_key
5913
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5914
+			) {
5915
+				return true;
5916
+			}
5917
+		}
5918
+		return false;
5919
+	}
5920 5920
 
5921 5921
 
5922 5922
 
Please login to merge, or discard this patch.
core/db_models/fields/EE_Post_Content_Field.php 2 patches
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -8,133 +8,133 @@
 block discarded – undo
8 8
 class EE_Post_Content_Field extends EE_Text_Field_Base
9 9
 {
10 10
 
11
-    /**
12
-     * @param string $table_column
13
-     * @param string $nicename
14
-     * @param bool   $nullable
15
-     * @param null   $default_value
16
-     */
17
-    public function __construct($table_column, $nicename, $nullable, $default_value = null)
18
-    {
19
-        parent::__construct($table_column, $nicename, $nullable, $default_value);
20
-        $this->setSchemaType('object');
21
-    }
11
+	/**
12
+	 * @param string $table_column
13
+	 * @param string $nicename
14
+	 * @param bool   $nullable
15
+	 * @param null   $default_value
16
+	 */
17
+	public function __construct($table_column, $nicename, $nullable, $default_value = null)
18
+	{
19
+		parent::__construct($table_column, $nicename, $nullable, $default_value);
20
+		$this->setSchemaType('object');
21
+	}
22 22
 
23 23
 
24
-    /**
25
-     * removes all tags which a WP Post wouldn't allow in its content normally
26
-     *
27
-     * @param string $value
28
-     * @return string
29
-     */
30
-    function prepare_for_set($value)
31
-    {
32
-        if (! current_user_can('unfiltered_html')) {
33
-            $value = wp_kses("$value", wp_kses_allowed_html('post'));
34
-        }
35
-        return parent::prepare_for_set($value);
36
-    }
24
+	/**
25
+	 * removes all tags which a WP Post wouldn't allow in its content normally
26
+	 *
27
+	 * @param string $value
28
+	 * @return string
29
+	 */
30
+	function prepare_for_set($value)
31
+	{
32
+		if (! current_user_can('unfiltered_html')) {
33
+			$value = wp_kses("$value", wp_kses_allowed_html('post'));
34
+		}
35
+		return parent::prepare_for_set($value);
36
+	}
37 37
 
38
-    function prepare_for_set_from_db($value_found_in_db_for_model_object)
39
-    {
40
-        return $value_found_in_db_for_model_object;
41
-    }
38
+	function prepare_for_set_from_db($value_found_in_db_for_model_object)
39
+	{
40
+		return $value_found_in_db_for_model_object;
41
+	}
42 42
 
43 43
 
44 44
 
45
-    /**
46
-     * Runs the content through `the_content`, or if prepares the content for placing in a form input
47
-     * @param string $value_on_field_to_be_outputted
48
-     * @param string   $schema possible values: 'form_input' or null (if null, will run through 'the_content')
49
-     * @return string
50
-     * @throws EE_Error when WP_DEBUG is on and recursive calling is detected
51
-     */
52
-    public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
53
-    {
54
-        switch($schema){
55
-            case 'form_input':
56
-                return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
57
-            case 'the_content':
45
+	/**
46
+	 * Runs the content through `the_content`, or if prepares the content for placing in a form input
47
+	 * @param string $value_on_field_to_be_outputted
48
+	 * @param string   $schema possible values: 'form_input' or null (if null, will run through 'the_content')
49
+	 * @return string
50
+	 * @throws EE_Error when WP_DEBUG is on and recursive calling is detected
51
+	 */
52
+	public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
53
+	{
54
+		switch($schema){
55
+			case 'form_input':
56
+				return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
57
+			case 'the_content':
58 58
 
59
-                if(doing_filter( 'the_content')){
60
-                    if( defined('WP_DEBUG') && WP_DEBUG){
61
-                        throw new EE_Error(
62
-                            sprintf(
63
-                                esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
64
-                                'EE_Post_Content_Field::prepare_for_pretty_echoing',
65
-                                '$schema',
66
-                                'the_content',
67
-                                'the_content_wp_core_only'
68
-                            )
69
-                        );
70
-                    } else {
71
-                        return $this->prepare_for_pretty_echoing($value_on_field_to_be_outputted, 'the_content_wp_core_only');
72
-                    }
73
-                }
74
-                return apply_filters(
75
-                    'the_content',
76
-                    parent::prepare_for_pretty_echoing(
77
-                        $value_on_field_to_be_outputted,
78
-                        $schema
79
-                    )
80
-                );
81
-            case 'the_content_wp_core_only':
82
-            default:
83
-                self::_setup_the_content_wp_core_only_filters();
84
-                $return_value = apply_filters(
85
-                    'the_content_wp_core_only',
86
-                    parent::prepare_for_pretty_echoing(
87
-                        $value_on_field_to_be_outputted,
88
-                        $schema
89
-                    )
90
-                );
91
-                //ya know what? adding these filters is super fast. Let's just
92
-                //avoid needing to maintain global state and set this up as-needed
93
-                remove_all_filters('the_content_wp_core_only');
94
-                do_action( 'AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
95
-                return $return_value;
96
-        }
97
-    }
59
+				if(doing_filter( 'the_content')){
60
+					if( defined('WP_DEBUG') && WP_DEBUG){
61
+						throw new EE_Error(
62
+							sprintf(
63
+								esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
64
+								'EE_Post_Content_Field::prepare_for_pretty_echoing',
65
+								'$schema',
66
+								'the_content',
67
+								'the_content_wp_core_only'
68
+							)
69
+						);
70
+					} else {
71
+						return $this->prepare_for_pretty_echoing($value_on_field_to_be_outputted, 'the_content_wp_core_only');
72
+					}
73
+				}
74
+				return apply_filters(
75
+					'the_content',
76
+					parent::prepare_for_pretty_echoing(
77
+						$value_on_field_to_be_outputted,
78
+						$schema
79
+					)
80
+				);
81
+			case 'the_content_wp_core_only':
82
+			default:
83
+				self::_setup_the_content_wp_core_only_filters();
84
+				$return_value = apply_filters(
85
+					'the_content_wp_core_only',
86
+					parent::prepare_for_pretty_echoing(
87
+						$value_on_field_to_be_outputted,
88
+						$schema
89
+					)
90
+				);
91
+				//ya know what? adding these filters is super fast. Let's just
92
+				//avoid needing to maintain global state and set this up as-needed
93
+				remove_all_filters('the_content_wp_core_only');
94
+				do_action( 'AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
95
+				return $return_value;
96
+		}
97
+	}
98 98
 
99 99
 
100 100
 
101
-    /**
102
-     * Verifies we've setup the standard WP core filters on  'the_content_wp_core_only' filter
103
-     */
104
-    protected static function _setup_the_content_wp_core_only_filters()
105
-    {
106
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
107
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
108
-        add_filter('the_content_wp_core_only', 'wptexturize', 10);
109
-        add_filter('the_content_wp_core_only', 'wpautop', 10);
110
-        add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
111
-        add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
112
-        if(function_exists('wp_make_content_images_responsive')) {
113
-            add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
114
-        }
115
-        add_filter('the_content_wp_core_only', 'do_shortcode', 11);
116
-        add_filter('the_content_wp_core_only', 'convert_smilies', 20);
117
-    }
101
+	/**
102
+	 * Verifies we've setup the standard WP core filters on  'the_content_wp_core_only' filter
103
+	 */
104
+	protected static function _setup_the_content_wp_core_only_filters()
105
+	{
106
+		add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
107
+		add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
108
+		add_filter('the_content_wp_core_only', 'wptexturize', 10);
109
+		add_filter('the_content_wp_core_only', 'wpautop', 10);
110
+		add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
111
+		add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
112
+		if(function_exists('wp_make_content_images_responsive')) {
113
+			add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
114
+		}
115
+		add_filter('the_content_wp_core_only', 'do_shortcode', 11);
116
+		add_filter('the_content_wp_core_only', 'convert_smilies', 20);
117
+	}
118 118
 
119 119
 
120 120
 
121
-    public function getSchemaProperties()
122
-    {
123
-        return array(
124
-            'raw' => array(
125
-                'description' =>  sprintf(
126
-                    __('%s - the content as it exists in the database.', 'event_espresso'),
127
-                    $this->get_nicename()
128
-                ),
129
-                'type' => 'string'
130
-            ),
131
-            'rendered' => array(
132
-                'description' =>  sprintf(
133
-                    __('%s - the content rendered for display.', 'event_espresso'),
134
-                    $this->get_nicename()
135
-                ),
136
-                'type' => 'string'
137
-            )
138
-        );
139
-    }
121
+	public function getSchemaProperties()
122
+	{
123
+		return array(
124
+			'raw' => array(
125
+				'description' =>  sprintf(
126
+					__('%s - the content as it exists in the database.', 'event_espresso'),
127
+					$this->get_nicename()
128
+				),
129
+				'type' => 'string'
130
+			),
131
+			'rendered' => array(
132
+				'description' =>  sprintf(
133
+					__('%s - the content rendered for display.', 'event_espresso'),
134
+					$this->get_nicename()
135
+				),
136
+				'type' => 'string'
137
+			)
138
+		);
139
+	}
140 140
 }
141 141
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
      */
30 30
     function prepare_for_set($value)
31 31
     {
32
-        if (! current_user_can('unfiltered_html')) {
32
+        if ( ! current_user_can('unfiltered_html')) {
33 33
             $value = wp_kses("$value", wp_kses_allowed_html('post'));
34 34
         }
35 35
         return parent::prepare_for_set($value);
@@ -51,13 +51,13 @@  discard block
 block discarded – undo
51 51
      */
52 52
     public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
53 53
     {
54
-        switch($schema){
54
+        switch ($schema) {
55 55
             case 'form_input':
56 56
                 return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
57 57
             case 'the_content':
58 58
 
59
-                if(doing_filter( 'the_content')){
60
-                    if( defined('WP_DEBUG') && WP_DEBUG){
59
+                if (doing_filter('the_content')) {
60
+                    if (defined('WP_DEBUG') && WP_DEBUG) {
61 61
                         throw new EE_Error(
62 62
                             sprintf(
63 63
                                 esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
                 //ya know what? adding these filters is super fast. Let's just
92 92
                 //avoid needing to maintain global state and set this up as-needed
93 93
                 remove_all_filters('the_content_wp_core_only');
94
-                do_action( 'AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
94
+                do_action('AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
95 95
                 return $return_value;
96 96
         }
97 97
     }
@@ -103,13 +103,13 @@  discard block
 block discarded – undo
103 103
      */
104 104
     protected static function _setup_the_content_wp_core_only_filters()
105 105
     {
106
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
107
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
106
+        add_filter('the_content_wp_core_only', array($GLOBALS['wp_embed'], 'run_shortcode'), 8);
107
+        add_filter('the_content_wp_core_only', array($GLOBALS['wp_embed'], 'autoembed'), 8);
108 108
         add_filter('the_content_wp_core_only', 'wptexturize', 10);
109 109
         add_filter('the_content_wp_core_only', 'wpautop', 10);
110 110
         add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
111 111
         add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
112
-        if(function_exists('wp_make_content_images_responsive')) {
112
+        if (function_exists('wp_make_content_images_responsive')) {
113 113
             add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
114 114
         }
115 115
         add_filter('the_content_wp_core_only', 'do_shortcode', 11);
Please login to merge, or discard this patch.
core/db_classes/EE_CPT_Base.class.php 2 patches
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -36,9 +36,9 @@  discard block
 block discarded – undo
36 36
 	 */
37 37
 	protected $_feature_image = array();
38 38
 
39
-    /**
40
-     * @var WP_Post the WP_Post that corresponds with this CPT model object
41
-     */
39
+	/**
40
+	 * @var WP_Post the WP_Post that corresponds with this CPT model object
41
+	 */
42 42
 	protected $_wp_post;
43 43
 
44 44
 
@@ -46,75 +46,75 @@  discard block
 block discarded – undo
46 46
 
47 47
 
48 48
 
49
-    /**
50
-     * Returns the WP post associated with this CPT model object. If this CPT is saved, fetches it
51
-     * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
52
-     * @return WP_Post
53
-     */
54
-    public function wp_post(){
55
-        global $wpdb;
56
-        if (! $this->_wp_post instanceof WP_Post) {
57
-            if ($this->ID()) {
58
-                $this->_wp_post = get_post($this->ID());
59
-            } else {
60
-                $simulated_db_result = new stdClass();
61
-                foreach($this->get_model()->field_settings(true) as $field_name => $field_obj){
62
-                    if ($this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name() === $wpdb->posts){
63
-                        $column = $field_obj->get_table_column();
64
-
65
-                        if($field_obj instanceof EE_Datetime_Field){
66
-                            $value_on_model_obj = $this->get_DateTime_object($field_name);
67
-                        } elseif( $field_obj->is_db_only_field()){
68
-                            $value_on_model_obj = $field_obj->get_default_value();
69
-                        } else {
70
-                            $value_on_model_obj = $this->get_raw($field_name);
71
-                        }
72
-                        $simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
73
-                    }
74
-                }
75
-                $this->_wp_post = new WP_Post($simulated_db_result);
76
-            }
77
-            //and let's make retrieving the EE CPT object easy too
78
-            $classname = get_class($this);
79
-            if (! isset($this->_wp_post->{$classname})) {
80
-                $this->_wp_post->{$classname} = $this;
81
-            }
82
-        }
83
-        return $this->_wp_post;
84
-    }
85
-
86
-    /**
87
-     * When fetching a new value for a post field that uses the global $post for rendering,
88
-     * set the global $post temporarily to be this model object; and afterwards restore it
89
-     * @param string $fieldname
90
-     * @param bool $pretty
91
-     * @param string $extra_cache_ref
92
-     * @return mixed
93
-     */
94
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
95
-    {
96
-        global $post;
97
-
98
-        if ( $pretty
99
-            && (
100
-                ! (
101
-                       $post instanceof WP_Post
102
-                       && $post->ID
103
-                   )
104
-                || (int)$post->ID !== $this->ID()
105
-             )
106
-            && $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field ) {
107
-            $old_post = $post;
108
-            $post = $this->wp_post();
109
-            $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
110
-            $post = $old_post;
111
-        } else {
112
-            $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
113
-        }
114
-        return $return_value;
115
-    }
116
-
117
-    /**
49
+	/**
50
+	 * Returns the WP post associated with this CPT model object. If this CPT is saved, fetches it
51
+	 * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
52
+	 * @return WP_Post
53
+	 */
54
+	public function wp_post(){
55
+		global $wpdb;
56
+		if (! $this->_wp_post instanceof WP_Post) {
57
+			if ($this->ID()) {
58
+				$this->_wp_post = get_post($this->ID());
59
+			} else {
60
+				$simulated_db_result = new stdClass();
61
+				foreach($this->get_model()->field_settings(true) as $field_name => $field_obj){
62
+					if ($this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name() === $wpdb->posts){
63
+						$column = $field_obj->get_table_column();
64
+
65
+						if($field_obj instanceof EE_Datetime_Field){
66
+							$value_on_model_obj = $this->get_DateTime_object($field_name);
67
+						} elseif( $field_obj->is_db_only_field()){
68
+							$value_on_model_obj = $field_obj->get_default_value();
69
+						} else {
70
+							$value_on_model_obj = $this->get_raw($field_name);
71
+						}
72
+						$simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
73
+					}
74
+				}
75
+				$this->_wp_post = new WP_Post($simulated_db_result);
76
+			}
77
+			//and let's make retrieving the EE CPT object easy too
78
+			$classname = get_class($this);
79
+			if (! isset($this->_wp_post->{$classname})) {
80
+				$this->_wp_post->{$classname} = $this;
81
+			}
82
+		}
83
+		return $this->_wp_post;
84
+	}
85
+
86
+	/**
87
+	 * When fetching a new value for a post field that uses the global $post for rendering,
88
+	 * set the global $post temporarily to be this model object; and afterwards restore it
89
+	 * @param string $fieldname
90
+	 * @param bool $pretty
91
+	 * @param string $extra_cache_ref
92
+	 * @return mixed
93
+	 */
94
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
95
+	{
96
+		global $post;
97
+
98
+		if ( $pretty
99
+			&& (
100
+				! (
101
+					   $post instanceof WP_Post
102
+					   && $post->ID
103
+				   )
104
+				|| (int)$post->ID !== $this->ID()
105
+			 )
106
+			&& $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field ) {
107
+			$old_post = $post;
108
+			$post = $this->wp_post();
109
+			$return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
110
+			$post = $old_post;
111
+		} else {
112
+			$return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
113
+		}
114
+		return $return_value;
115
+	}
116
+
117
+	/**
118 118
 	 * Adds to the specified event category. If it category doesn't exist, creates it.
119 119
 	 * @param string $category_name
120 120
 	 * @param string $category_description    optional
@@ -399,14 +399,14 @@  discard block
 block discarded – undo
399 399
 
400 400
 
401 401
 
402
-    /**
403
-     * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
404
-     * @return array
405
-     */
406
-    public function __sleep()
407
-    {
408
-        $properties_to_serialize = parent::__sleep();
409
-        $properties_to_serialize = array_diff( $properties_to_serialize, array('_wp_post'));
410
-        return $properties_to_serialize;
411
-    }
402
+	/**
403
+	 * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
404
+	 * @return array
405
+	 */
406
+	public function __sleep()
407
+	{
408
+		$properties_to_serialize = parent::__sleep();
409
+		$properties_to_serialize = array_diff( $properties_to_serialize, array('_wp_post'));
410
+		return $properties_to_serialize;
411
+	}
412 412
 }
Please login to merge, or discard this patch.
Spacing   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1
-<?php if ( !defined( 'EVENT_ESPRESSO_VERSION' ) ) {
2
-	exit( 'No direct script access allowed' );
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -51,20 +51,20 @@  discard block
 block discarded – undo
51 51
      * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
52 52
      * @return WP_Post
53 53
      */
54
-    public function wp_post(){
54
+    public function wp_post() {
55 55
         global $wpdb;
56
-        if (! $this->_wp_post instanceof WP_Post) {
56
+        if ( ! $this->_wp_post instanceof WP_Post) {
57 57
             if ($this->ID()) {
58 58
                 $this->_wp_post = get_post($this->ID());
59 59
             } else {
60 60
                 $simulated_db_result = new stdClass();
61
-                foreach($this->get_model()->field_settings(true) as $field_name => $field_obj){
62
-                    if ($this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name() === $wpdb->posts){
61
+                foreach ($this->get_model()->field_settings(true) as $field_name => $field_obj) {
62
+                    if ($this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name() === $wpdb->posts) {
63 63
                         $column = $field_obj->get_table_column();
64 64
 
65
-                        if($field_obj instanceof EE_Datetime_Field){
65
+                        if ($field_obj instanceof EE_Datetime_Field) {
66 66
                             $value_on_model_obj = $this->get_DateTime_object($field_name);
67
-                        } elseif( $field_obj->is_db_only_field()){
67
+                        } elseif ($field_obj->is_db_only_field()) {
68 68
                             $value_on_model_obj = $field_obj->get_default_value();
69 69
                         } else {
70 70
                             $value_on_model_obj = $this->get_raw($field_name);
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
             }
77 77
             //and let's make retrieving the EE CPT object easy too
78 78
             $classname = get_class($this);
79
-            if (! isset($this->_wp_post->{$classname})) {
79
+            if ( ! isset($this->_wp_post->{$classname})) {
80 80
                 $this->_wp_post->{$classname} = $this;
81 81
             }
82 82
         }
@@ -95,15 +95,15 @@  discard block
 block discarded – undo
95 95
     {
96 96
         global $post;
97 97
 
98
-        if ( $pretty
98
+        if ($pretty
99 99
             && (
100 100
                 ! (
101 101
                        $post instanceof WP_Post
102 102
                        && $post->ID
103 103
                    )
104
-                || (int)$post->ID !== $this->ID()
104
+                || (int) $post->ID !== $this->ID()
105 105
              )
106
-            && $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field ) {
106
+            && $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field) {
107 107
             $old_post = $post;
108 108
             $post = $this->wp_post();
109 109
             $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
@@ -121,8 +121,8 @@  discard block
 block discarded – undo
121 121
 	 * @param int    $parent_term_taxonomy_id optional
122 122
 	 * @return EE_Term_Taxonomy
123 123
 	 */
124
-	function add_event_category( $category_name, $category_description = NULL, $parent_term_taxonomy_id = NULL ) {
125
-		return $this->get_model()->add_event_category( $this, $category_name, $category_description, $parent_term_taxonomy_id );
124
+	function add_event_category($category_name, $category_description = NULL, $parent_term_taxonomy_id = NULL) {
125
+		return $this->get_model()->add_event_category($this, $category_name, $category_description, $parent_term_taxonomy_id);
126 126
 	}
127 127
 
128 128
 
@@ -132,8 +132,8 @@  discard block
 block discarded – undo
132 132
 	 * @param string $category_name
133 133
 	 * @return bool
134 134
 	 */
135
-	function remove_event_category( $category_name ) {
136
-		return $this->get_model()->remove_event_category( $this, $category_name );
135
+	function remove_event_category($category_name) {
136
+		return $this->get_model()->remove_event_category($this, $category_name);
137 137
 	}
138 138
 
139 139
 
@@ -144,14 +144,14 @@  discard block
 block discarded – undo
144 144
 	 * @param EE_Term_Taxonomy $term_taxonomy
145 145
 	 * @return EE_Base_Class the relation was removed from
146 146
 	 */
147
-	function remove_relation_to_term_taxonomy( $term_taxonomy ) {
148
-		if ( !$term_taxonomy ) {
149
-			EE_Error::add_error( sprintf( __( "No Term_Taxonomy provided which to remove from model object of type %s and id %d", "event_espresso" ), get_class( $this ), $this->ID() ), __FILE__, __FUNCTION__, __LINE__ );
147
+	function remove_relation_to_term_taxonomy($term_taxonomy) {
148
+		if ( ! $term_taxonomy) {
149
+			EE_Error::add_error(sprintf(__("No Term_Taxonomy provided which to remove from model object of type %s and id %d", "event_espresso"), get_class($this), $this->ID()), __FILE__, __FUNCTION__, __LINE__);
150 150
 			return NULL;
151 151
 		}
152
-		$term_taxonomy->set_count( $term_taxonomy->count() - 1 );
152
+		$term_taxonomy->set_count($term_taxonomy->count() - 1);
153 153
 		$term_taxonomy->save();
154
-		return $this->_remove_relation_to( $term_taxonomy, 'Term_Taxonomy' );
154
+		return $this->_remove_relation_to($term_taxonomy, 'Term_Taxonomy');
155 155
 	}
156 156
 
157 157
 
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 	 * @return int
176 176
 	 */
177 177
 	public function parent() {
178
-		return $this->get( 'parent' );
178
+		return $this->get('parent');
179 179
 	}
180 180
 
181 181
 
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
 	 * @return string
186 186
 	 */
187 187
 	public function status() {
188
-		return $this->get( 'status' );
188
+		return $this->get('status');
189 189
 	}
190 190
 
191 191
 
@@ -193,8 +193,8 @@  discard block
 block discarded – undo
193 193
 	/**
194 194
 	 * @param string $status
195 195
 	 */
196
-	public function set_status( $status ) {
197
-		$this->set( 'status', $status );
196
+	public function set_status($status) {
197
+		$this->set('status', $status);
198 198
 	}
199 199
 
200 200
 
@@ -208,12 +208,12 @@  discard block
 block discarded – undo
208 208
 	 * @param string|array $attr Optional. Query string or array of attributes.
209 209
 	 * @return string HTML image element
210 210
 	 */
211
-	protected function _get_feature_image( $size, $attr ) {
211
+	protected function _get_feature_image($size, $attr) {
212 212
 		//first let's see if we already have the _feature_image property set AND if it has a cached element on it FOR the given size
213
-		$attr_key = is_array( $attr ) ? implode( '_', $attr ) : $attr;
214
-		$cache_key = is_array( $size ) ? implode( '_', $size ) . $attr_key : $size . $attr_key;
215
-		$this->_feature_image[ $cache_key ] = isset( $this->_feature_image[ $cache_key ] ) ? $this->_feature_image[ $cache_key ] : $this->get_model()->get_feature_image( $this->ID(), $size, $attr );
216
-		return $this->_feature_image[ $cache_key ];
213
+		$attr_key = is_array($attr) ? implode('_', $attr) : $attr;
214
+		$cache_key = is_array($size) ? implode('_', $size).$attr_key : $size.$attr_key;
215
+		$this->_feature_image[$cache_key] = isset($this->_feature_image[$cache_key]) ? $this->_feature_image[$cache_key] : $this->get_model()->get_feature_image($this->ID(), $size, $attr);
216
+		return $this->_feature_image[$cache_key];
217 217
 	}
218 218
 
219 219
 
@@ -224,8 +224,8 @@  discard block
 block discarded – undo
224 224
 	 * @param string|array $attr
225 225
 	 * @return string of html
226 226
 	 */
227
-	public function feature_image( $size = 'thumbnail', $attr = '' ) {
228
-		return $this->_get_feature_image( $size, $attr );
227
+	public function feature_image($size = 'thumbnail', $attr = '') {
228
+		return $this->_get_feature_image($size, $attr);
229 229
 	}
230 230
 
231 231
 
@@ -235,9 +235,9 @@  discard block
 block discarded – undo
235 235
 	 * @param  string|array $size can either be a string: 'thumbnail', 'medium', 'large', 'full' OR 2-item array representing width and height in pixels eg. array(32,32).
236 236
 	 * @return string|boolean          the url of the image or false if not found
237 237
 	 */
238
-	public function feature_image_url( $size = 'thumbnail' ) {
239
-		$attachment = wp_get_attachment_image_src( get_post_thumbnail_id( $this->ID() ), $size );
240
-		return !empty( $attachment ) ? $attachment[ 0 ] : FALSE;
238
+	public function feature_image_url($size = 'thumbnail') {
239
+		$attachment = wp_get_attachment_image_src(get_post_thumbnail_id($this->ID()), $size);
240
+		return ! empty($attachment) ? $attachment[0] : FALSE;
241 241
 	}
242 242
 
243 243
 
@@ -259,36 +259,36 @@  discard block
 block discarded – undo
259 259
 	 *                                 This array is INDEXED by RELATED OBJ NAME (so it corresponds with the obj_names sent);
260 260
 	 * @return void
261 261
 	 */
262
-	public function restore_revision( $revision_id, $related_obj_names = array(), $where_query = array() ) {
262
+	public function restore_revision($revision_id, $related_obj_names = array(), $where_query = array()) {
263 263
 		//get revision object
264
-		$revision_obj = $this->get_model()->get_one_by_ID( $revision_id );
265
-		if ( $revision_obj instanceof EE_CPT_Base ) {
264
+		$revision_obj = $this->get_model()->get_one_by_ID($revision_id);
265
+		if ($revision_obj instanceof EE_CPT_Base) {
266 266
 			//no related_obj_name so we assume we're saving a revision on this object.
267
-			if ( empty( $related_obj_names ) ) {
267
+			if (empty($related_obj_names)) {
268 268
 				$fields = $this->get_model()->get_meta_table_fields();
269
-				foreach ( $fields as $field ) {
270
-					$this->set( $field, $revision_obj->get( $field ) );
269
+				foreach ($fields as $field) {
270
+					$this->set($field, $revision_obj->get($field));
271 271
 				}
272 272
 				$this->save();
273 273
 			}
274
-			$related_obj_names = (array)$related_obj_names;
275
-			foreach ( $related_obj_names as $related_name ) {
274
+			$related_obj_names = (array) $related_obj_names;
275
+			foreach ($related_obj_names as $related_name) {
276 276
 				//related_obj_name so we're saving a revision on an object related to this object
277 277
 				//do we have $where_query params for this related object?  If we do then we include that.
278
-				$cols_n_values = isset( $where_query[ $related_name ] ) ? $where_query[ $related_name ] : array();
279
-				$where_params = !empty( $cols_n_values ) ? array( $cols_n_values ) : array();
280
-				$related_objs = $this->get_many_related( $related_name, $where_params );
281
-				$revision_related_objs = $revision_obj->get_many_related( $related_name, $where_params );
278
+				$cols_n_values = isset($where_query[$related_name]) ? $where_query[$related_name] : array();
279
+				$where_params = ! empty($cols_n_values) ? array($cols_n_values) : array();
280
+				$related_objs = $this->get_many_related($related_name, $where_params);
281
+				$revision_related_objs = $revision_obj->get_many_related($related_name, $where_params);
282 282
 				//load helper
283 283
 				//remove related objs from this object that are not in revision
284 284
 				//array_diff *should* work cause I think objects are indexed by ID?
285
-				$related_to_remove = EEH_Array::object_array_diff( $related_objs, $revision_related_objs );
286
-				foreach ( $related_to_remove as $rr ) {
287
-					$this->_remove_relation_to( $rr, $related_name, $cols_n_values );
285
+				$related_to_remove = EEH_Array::object_array_diff($related_objs, $revision_related_objs);
286
+				foreach ($related_to_remove as $rr) {
287
+					$this->_remove_relation_to($rr, $related_name, $cols_n_values);
288 288
 				}
289 289
 				//add all related objs attached to revision to this object
290
-				foreach ( $revision_related_objs as $r_obj ) {
291
-					$this->_add_relation_to( $r_obj, $related_name, $cols_n_values );
290
+				foreach ($revision_related_objs as $r_obj) {
291
+					$this->_add_relation_to($r_obj, $related_name, $cols_n_values);
292 292
 				}
293 293
 			}
294 294
 		}
@@ -304,8 +304,8 @@  discard block
 block discarded – undo
304 304
 	 * <li>If $single is set to false, or left blank, the function returns an array containing all values of the specified key.</li>
305 305
 	 * <li>If $single is set to true, the function returns the first value of the specified key (not in an array</li></ul>
306 306
 	 */
307
-	public function get_post_meta( $meta_key = NULL, $single = FALSE ) {
308
-		return get_post_meta( $this->ID(), $meta_key, $single );
307
+	public function get_post_meta($meta_key = NULL, $single = FALSE) {
308
+		return get_post_meta($this->ID(), $meta_key, $single);
309 309
 	}
310 310
 
311 311
 
@@ -317,11 +317,11 @@  discard block
 block discarded – undo
317 317
 	 * @param mixed  $prev_value
318 318
 	 * @return mixed Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure. NOTE: If the meta_value passed to this function is the same as the value that is already in the database, this function returns false.
319 319
 	 */
320
-	public function update_post_meta( $meta_key, $meta_value, $prev_value = NULL ) {
321
-		if ( ! $this->ID() ) {
320
+	public function update_post_meta($meta_key, $meta_value, $prev_value = NULL) {
321
+		if ( ! $this->ID()) {
322 322
 			$this->save();
323 323
 		}
324
-		return update_post_meta( $this->ID(), $meta_key, $meta_value, $prev_value );
324
+		return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
325 325
 	}
326 326
 
327 327
 
@@ -333,11 +333,11 @@  discard block
 block discarded – undo
333 333
 	 * @param bool  $unique . If postmeta for this $meta_key already exists, whether to add an additional item or not
334 334
 	 * @return boolean Boolean true, except if the $unique argument was set to true and a custom field with the given key already exists, in which case false is returned.
335 335
 	 */
336
-	public function add_post_meta( $meta_key, $meta_value, $unique = FALSE ) {
337
-		if ( $this->ID() ) {
336
+	public function add_post_meta($meta_key, $meta_value, $unique = FALSE) {
337
+		if ($this->ID()) {
338 338
 			$this->save();
339 339
 		}
340
-		return add_post_meta( $this->ID(), $meta_key, $meta_value, $unique );
340
+		return add_post_meta($this->ID(), $meta_key, $meta_value, $unique);
341 341
 	}
342 342
 
343 343
 
@@ -349,13 +349,13 @@  discard block
 block discarded – undo
349 349
 	 * @param mixed $meta_value
350 350
 	 * @return boolean False for failure. True for success.
351 351
 	 */
352
-	public function delete_post_meta( $meta_key, $meta_value = '' ) {
353
-		if ( ! $this->ID() ) {
352
+	public function delete_post_meta($meta_key, $meta_value = '') {
353
+		if ( ! $this->ID()) {
354 354
 			//there are obviously no postmetas for this if it's not saved
355 355
 			//so let's just report this as a success
356 356
 			return true;
357 357
 		}
358
-		return delete_post_meta( $this->ID(), $meta_key, $meta_value );
358
+		return delete_post_meta($this->ID(), $meta_key, $meta_value);
359 359
 	}
360 360
 
361 361
 
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 	 * @return string
366 366
 	 */
367 367
 	public function get_permalink() {
368
-		return get_permalink( $this->ID() );
368
+		return get_permalink($this->ID());
369 369
 	}
370 370
 
371 371
 
@@ -375,8 +375,8 @@  discard block
 block discarded – undo
375 375
 	 * @param array $query_params
376 376
 	 * @return EE_Term_Taxonomy
377 377
 	 */
378
-	public function term_taxonomies( $query_params = array() ) {
379
-		return $this->get_many_related( 'Term_Taxonomy', $query_params );
378
+	public function term_taxonomies($query_params = array()) {
379
+		return $this->get_many_related('Term_Taxonomy', $query_params);
380 380
 	}
381 381
 
382 382
 
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
     public function __sleep()
407 407
     {
408 408
         $properties_to_serialize = parent::__sleep();
409
-        $properties_to_serialize = array_diff( $properties_to_serialize, array('_wp_post'));
409
+        $properties_to_serialize = array_diff($properties_to_serialize, array('_wp_post'));
410 410
         return $properties_to_serialize;
411 411
     }
412 412
 }
Please login to merge, or discard this patch.
core/libraries/rest_api/controllers/model/Read.php 2 patches
Indentation   +1272 added lines, -1272 removed lines patch added patch discarded remove patch
@@ -9,7 +9,7 @@  discard block
 block discarded – undo
9 9
 use EE_Datetime_Field;
10 10
 
11 11
 if (! defined('EVENT_ESPRESSO_VERSION')) {
12
-    exit('No direct script access allowed');
12
+	exit('No direct script access allowed');
13 13
 }
14 14
 
15 15
 
@@ -27,1277 +27,1277 @@  discard block
 block discarded – undo
27 27
 
28 28
 
29 29
 
30
-    /**
31
-     * @var Calculated_Model_Fields
32
-     */
33
-    protected $_fields_calculator;
34
-
35
-
36
-
37
-    /**
38
-     * Read constructor.
39
-     */
40
-    public function __construct()
41
-    {
42
-        parent::__construct();
43
-        $this->_fields_calculator = new Calculated_Model_Fields();
44
-    }
45
-
46
-
47
-
48
-    /**
49
-     * Handles requests to get all (or a filtered subset) of entities for a particular model
50
-     *
51
-     * @param \WP_REST_Request $request
52
-     * @return \WP_REST_Response|\WP_Error
53
-     */
54
-    public static function handle_request_get_all(\WP_REST_Request $request)
55
-    {
56
-        $controller = new Read();
57
-        try {
58
-            $matches = $controller->parse_route(
59
-                $request->get_route(),
60
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)~',
61
-                array('version', 'model')
62
-            );
63
-            $controller->set_requested_version($matches['version']);
64
-            $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
65
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
66
-                return $controller->send_response(
67
-                    new \WP_Error(
68
-                        'endpoint_parsing_error',
69
-                        sprintf(
70
-                            __('There is no model for endpoint %s. Please contact event espresso support',
71
-                                'event_espresso'),
72
-                            $model_name_singular
73
-                        )
74
-                    )
75
-                );
76
-            }
77
-            return $controller->send_response(
78
-                $controller->get_entities_from_model(
79
-                    $controller->get_model_version_info()->load_model($model_name_singular),
80
-                    $request
81
-                )
82
-            );
83
-        } catch (\Exception $e) {
84
-            return $controller->send_response($e);
85
-        }
86
-    }
87
-
88
-
89
-
90
-    /**
91
-     * Prepares and returns schema for any OPTIONS request.
92
-     *
93
-     * @param string $model_name Something like `Event` or `Registration`
94
-     * @param string $version    The API endpoint version being used.
95
-     * @return array
96
-     */
97
-    public static function handle_schema_request($model_name, $version)
98
-    {
99
-        $controller = new Read();
100
-        try {
101
-            $controller->set_requested_version($version);
102
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name)) {
103
-                return array();
104
-            }
105
-            //get the model for this version
106
-            $model = $controller->get_model_version_info()->load_model($model_name);
107
-            $model_schema = new JsonModelSchema($model);
108
-            return $model_schema->getModelSchemaForRelations(
109
-                $controller->get_model_version_info()->relation_settings($model),
110
-                $controller->_customize_schema_for_rest_response(
111
-                    $model,
112
-                    $model_schema->getModelSchemaForFields(
113
-                        $controller->get_model_version_info()->fields_on_model_in_this_version($model),
114
-                        $model_schema->getInitialSchemaStructure()
115
-                    )
116
-                )
117
-            );
118
-        } catch (\Exception $e) {
119
-            return array();
120
-        }
121
-    }
122
-
123
-
124
-
125
-    /**
126
-     * This loops through each field in the given schema for the model and does the following:
127
-     * - add any extra fields that are REST API specific and related to existing fields.
128
-     * - transform default values into the correct format for a REST API response.
129
-     *
130
-     * @param \EEM_Base $model
131
-     * @param array     $schema
132
-     * @return array  The final schema.
133
-     */
134
-    protected function _customize_schema_for_rest_response(\EEM_Base $model, array $schema)
135
-    {
136
-        foreach ($this->get_model_version_info()->fields_on_model_in_this_version($model) as $field_name => $field) {
137
-            $schema = $this->_translate_defaults_for_rest_response(
138
-                $field_name,
139
-                $field,
140
-                $this->_maybe_add_extra_fields_to_schema($field_name, $field, $schema)
141
-            );
142
-        }
143
-        return $schema;
144
-    }
145
-
146
-
147
-
148
-    /**
149
-     * This is used to ensure that the 'default' value set in the schema response is formatted correctly for the REST
150
-     * response.
151
-     *
152
-     * @param                      $field_name
153
-     * @param \EE_Model_Field_Base $field
154
-     * @param array                $schema
155
-     * @return array
156
-     */
157
-    protected function _translate_defaults_for_rest_response($field_name, \EE_Model_Field_Base $field, array $schema)
158
-    {
159
-        if (isset($schema['properties'][$field_name]['default'])) {
160
-            if (is_array($schema['properties'][$field_name]['default'])) {
161
-                foreach ($schema['properties'][$field_name]['default'] as $default_key => $default_value) {
162
-                    if ($default_key === 'raw') {
163
-                        $schema['properties'][$field_name]['default'][$default_key] = Model_Data_Translator::prepare_field_value_for_json(
164
-                            $field,
165
-                            $default_value,
166
-                            $this->get_model_version_info()->requested_version()
167
-                        );
168
-                    }
169
-                }
170
-            } else {
171
-                $schema['properties'][$field_name]['default'] = Model_Data_Translator::prepare_field_value_for_json(
172
-                    $field,
173
-                    $schema['properties'][$field_name]['default'],
174
-                    $this->get_model_version_info()->requested_version()
175
-                );
176
-            }
177
-        }
178
-        return $schema;
179
-    }
180
-
181
-
182
-
183
-    /**
184
-     * Adds additional fields to the schema
185
-     * The REST API returns a GMT value field for each datetime field in the resource.  Thus the description about this
186
-     * needs to be added to the schema.
187
-     *
188
-     * @param                      $field_name
189
-     * @param \EE_Model_Field_Base $field
190
-     * @param array                $schema
191
-     * @return array
192
-     */
193
-    protected function _maybe_add_extra_fields_to_schema($field_name, \EE_Model_Field_Base $field, array $schema)
194
-    {
195
-        if ($field instanceof EE_Datetime_Field) {
196
-            $schema['properties'][$field_name . '_gmt'] = $field->getSchema();
197
-            //modify the description
198
-            $schema['properties'][$field_name . '_gmt']['description'] = sprintf(
199
-                esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
200
-                $field->get_nicename()
201
-            );
202
-        }
203
-        return $schema;
204
-    }
205
-
206
-
207
-
208
-    /**
209
-     * Used to figure out the route from the request when a `WP_REST_Request` object is not available
210
-     *
211
-     * @return string
212
-     */
213
-    protected function get_route_from_request()
214
-    {
215
-        if (isset($GLOBALS['wp'])
216
-            && $GLOBALS['wp'] instanceof \WP
217
-            && isset($GLOBALS['wp']->query_vars['rest_route'])
218
-        ) {
219
-            return $GLOBALS['wp']->query_vars['rest_route'];
220
-        } else {
221
-            return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
222
-        }
223
-    }
224
-
225
-
226
-
227
-    /**
228
-     * Gets a single entity related to the model indicated in the path and its id
229
-     *
230
-     * @param \WP_REST_Request $request
231
-     * @return \WP_REST_Response|\WP_Error
232
-     */
233
-    public static function handle_request_get_one(\WP_REST_Request $request)
234
-    {
235
-        $controller = new Read();
236
-        try {
237
-            $matches = $controller->parse_route(
238
-                $request->get_route(),
239
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)~',
240
-                array('version', 'model', 'id'));
241
-            $controller->set_requested_version($matches['version']);
242
-            $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
243
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
244
-                return $controller->send_response(
245
-                    new \WP_Error(
246
-                        'endpoint_parsing_error',
247
-                        sprintf(
248
-                            __('There is no model for endpoint %s. Please contact event espresso support',
249
-                                'event_espresso'),
250
-                            $model_name_singular
251
-                        )
252
-                    )
253
-                );
254
-            }
255
-            return $controller->send_response(
256
-                $controller->get_entity_from_model(
257
-                    $controller->get_model_version_info()->load_model($model_name_singular),
258
-                    $request
259
-                )
260
-            );
261
-        } catch (\Exception $e) {
262
-            return $controller->send_response($e);
263
-        }
264
-    }
265
-
266
-
267
-
268
-    /**
269
-     * Gets all the related entities (or if its a belongs-to relation just the one)
270
-     * to the item with the given id
271
-     *
272
-     * @param \WP_REST_Request $request
273
-     * @return \WP_REST_Response|\WP_Error
274
-     */
275
-    public static function handle_request_get_related(\WP_REST_Request $request)
276
-    {
277
-        $controller = new Read();
278
-        try {
279
-            $matches = $controller->parse_route(
280
-                $request->get_route(),
281
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)/(.*)~',
282
-                array('version', 'model', 'id', 'related_model')
283
-            );
284
-            $controller->set_requested_version($matches['version']);
285
-            $main_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
286
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
287
-                return $controller->send_response(
288
-                    new \WP_Error(
289
-                        'endpoint_parsing_error',
290
-                        sprintf(
291
-                            __('There is no model for endpoint %s. Please contact event espresso support',
292
-                                'event_espresso'),
293
-                            $main_model_name_singular
294
-                        )
295
-                    )
296
-                );
297
-            }
298
-            $main_model = $controller->get_model_version_info()->load_model($main_model_name_singular);
299
-            //assume the related model name is plural and try to find the model's name
300
-            $related_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['related_model']);
301
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
302
-                //so the word didn't singularize well. Maybe that's just because it's a singular word?
303
-                $related_model_name_singular = \EEH_Inflector::humanize($matches['related_model']);
304
-            }
305
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
306
-                return $controller->send_response(
307
-                    new \WP_Error(
308
-                        'endpoint_parsing_error',
309
-                        sprintf(
310
-                            __('There is no model for endpoint %s. Please contact event espresso support',
311
-                                'event_espresso'),
312
-                            $related_model_name_singular
313
-                        )
314
-                    )
315
-                );
316
-            }
317
-            return $controller->send_response(
318
-                $controller->get_entities_from_relation(
319
-                    $request->get_param('id'),
320
-                    $main_model->related_settings_for($related_model_name_singular),
321
-                    $request
322
-                )
323
-            );
324
-        } catch (\Exception $e) {
325
-            return $controller->send_response($e);
326
-        }
327
-    }
328
-
329
-
330
-
331
-    /**
332
-     * Gets a collection for the given model and filters
333
-     *
334
-     * @param \EEM_Base        $model
335
-     * @param \WP_REST_Request $request
336
-     * @return array|\WP_Error
337
-     */
338
-    public function get_entities_from_model($model, $request)
339
-    {
340
-        $query_params = $this->create_model_query_params($model, $request->get_params());
341
-        if (! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
342
-            $model_name_plural = \EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
343
-            return new \WP_Error(
344
-                sprintf('rest_%s_cannot_list', $model_name_plural),
345
-                sprintf(
346
-                    __('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
347
-                    $model_name_plural,
348
-                    Capabilities::get_missing_permissions_string($model, $query_params['caps'])
349
-                ),
350
-                array('status' => 403)
351
-            );
352
-        }
353
-        if (! $request->get_header('no_rest_headers')) {
354
-            $this->_set_headers_from_query_params($model, $query_params);
355
-        }
356
-        /** @type array $results */
357
-        $results = $model->get_all_wpdb_results($query_params);
358
-        $nice_results = array();
359
-        foreach ($results as $result) {
360
-            $nice_results[] = $this->create_entity_from_wpdb_result(
361
-                $model,
362
-                $result,
363
-                $request
364
-            );
365
-        }
366
-        return $nice_results;
367
-    }
368
-
369
-
370
-
371
-    /**
372
-     * @param array                   $primary_model_query_params query params for finding the item from which
373
-     *                                                            relations will be based
374
-     * @param \EE_Model_Relation_Base $relation
375
-     * @param \WP_REST_Request        $request
376
-     * @return \WP_Error|array
377
-     */
378
-    protected function _get_entities_from_relation($primary_model_query_params, $relation, $request)
379
-    {
380
-        $context = $this->validate_context($request->get_param('caps'));
381
-        $model = $relation->get_this_model();
382
-        $related_model = $relation->get_other_model();
383
-        if (! isset($primary_model_query_params[0])) {
384
-            $primary_model_query_params[0] = array();
385
-        }
386
-        //check if they can access the 1st model object
387
-        $primary_model_query_params = array(
388
-            0       => $primary_model_query_params[0],
389
-            'limit' => 1,
390
-        );
391
-        if ($model instanceof \EEM_Soft_Delete_Base) {
392
-            $primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($primary_model_query_params);
393
-        }
394
-        $restricted_query_params = $primary_model_query_params;
395
-        $restricted_query_params['caps'] = $context;
396
-        $this->_set_debug_info('main model query params', $restricted_query_params);
397
-        $this->_set_debug_info('missing caps', Capabilities::get_missing_permissions_string($related_model, $context));
398
-        if (
399
-        ! (
400
-            Capabilities::current_user_has_partial_access_to($related_model, $context)
401
-            && $model->exists($restricted_query_params)
402
-        )
403
-        ) {
404
-            if ($relation instanceof \EE_Belongs_To_Relation) {
405
-                $related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
406
-            } else {
407
-                $related_model_name_maybe_plural = \EEH_Inflector::pluralize_and_lower($related_model->get_this_model_name());
408
-            }
409
-            return new \WP_Error(
410
-                sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
411
-                sprintf(
412
-                    __('Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
413
-                        'event_espresso'),
414
-                    $related_model_name_maybe_plural,
415
-                    $relation->get_this_model()->get_this_model_name(),
416
-                    implode(
417
-                        ',',
418
-                        array_keys(
419
-                            Capabilities::get_missing_permissions($related_model, $context)
420
-                        )
421
-                    )
422
-                ),
423
-                array('status' => 403)
424
-            );
425
-        }
426
-        $query_params = $this->create_model_query_params($relation->get_other_model(), $request->get_params());
427
-        foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
428
-            $query_params[0][$relation->get_this_model()->get_this_model_name()
429
-                             . '.'
430
-                             . $where_condition_key] = $where_condition_value;
431
-        }
432
-        $query_params['default_where_conditions'] = 'none';
433
-        $query_params['caps'] = $context;
434
-        if (! $request->get_header('no_rest_headers')) {
435
-            $this->_set_headers_from_query_params($relation->get_other_model(), $query_params);
436
-        }
437
-        /** @type array $results */
438
-        $results = $relation->get_other_model()->get_all_wpdb_results($query_params);
439
-        $nice_results = array();
440
-        foreach ($results as $result) {
441
-            $nice_result = $this->create_entity_from_wpdb_result(
442
-                $relation->get_other_model(),
443
-                $result,
444
-                $request
445
-            );
446
-            if ($relation instanceof \EE_HABTM_Relation) {
447
-                //put the unusual stuff (properties from the HABTM relation) first, and make sure
448
-                //if there are conflicts we prefer the properties from the main model
449
-                $join_model_result = $this->create_entity_from_wpdb_result(
450
-                    $relation->get_join_model(),
451
-                    $result,
452
-                    $request
453
-                );
454
-                $joined_result = array_merge($nice_result, $join_model_result);
455
-                //but keep the meta stuff from the main model
456
-                if (isset($nice_result['meta'])) {
457
-                    $joined_result['meta'] = $nice_result['meta'];
458
-                }
459
-                $nice_result = $joined_result;
460
-            }
461
-            $nice_results[] = $nice_result;
462
-        }
463
-        if ($relation instanceof \EE_Belongs_To_Relation) {
464
-            return array_shift($nice_results);
465
-        } else {
466
-            return $nice_results;
467
-        }
468
-    }
469
-
470
-
471
-
472
-    /**
473
-     * Gets the collection for given relation object
474
-     * The same as Read::get_entities_from_model(), except if the relation
475
-     * is a HABTM relation, in which case it merges any non-foreign-key fields from
476
-     * the join-model-object into the results
477
-     *
478
-     * @param string                  $id the ID of the thing we are fetching related stuff from
479
-     * @param \EE_Model_Relation_Base $relation
480
-     * @param \WP_REST_Request        $request
481
-     * @return array|\WP_Error
482
-     * @throws \EE_Error
483
-     */
484
-    public function get_entities_from_relation($id, $relation, $request)
485
-    {
486
-        if (! $relation->get_this_model()->has_primary_key_field()) {
487
-            throw new \EE_Error(
488
-                sprintf(
489
-                    __('Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
490
-                        'event_espresso'),
491
-                    $relation->get_this_model()->get_this_model_name()
492
-                )
493
-            );
494
-        }
495
-        return $this->_get_entities_from_relation(
496
-            array(
497
-                array(
498
-                    $relation->get_this_model()->primary_key_name() => $id,
499
-                ),
500
-            ),
501
-            $relation,
502
-            $request
503
-        );
504
-    }
505
-
506
-
507
-
508
-    /**
509
-     * Sets the headers that are based on the model and query params,
510
-     * like the total records. This should only be called on the original request
511
-     * from the client, not on subsequent internal
512
-     *
513
-     * @param \EEM_Base $model
514
-     * @param array     $query_params
515
-     * @return void
516
-     */
517
-    protected function _set_headers_from_query_params($model, $query_params)
518
-    {
519
-        $this->_set_debug_info('model query params', $query_params);
520
-        $this->_set_debug_info('missing caps',
521
-            Capabilities::get_missing_permissions_string($model, $query_params['caps']));
522
-        //normally the limit to a 2-part array, where the 2nd item is the limit
523
-        if (! isset($query_params['limit'])) {
524
-            $query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
525
-        }
526
-        if (is_array($query_params['limit'])) {
527
-            $limit_parts = $query_params['limit'];
528
-        } else {
529
-            $limit_parts = explode(',', $query_params['limit']);
530
-            if (count($limit_parts) == 1) {
531
-                $limit_parts = array(0, $limit_parts[0]);
532
-            }
533
-        }
534
-        //remove the group by and having parts of the query, as those will
535
-        //make the sql query return an array of values, instead of just a single value
536
-        unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
537
-        $count = $model->count($query_params, null, true);
538
-        $pages = $count / $limit_parts[1];
539
-        $this->_set_response_header('Total', $count, false);
540
-        $this->_set_response_header('PageSize', $limit_parts[1], false);
541
-        $this->_set_response_header('TotalPages', ceil($pages), false);
542
-    }
543
-
544
-
545
-
546
-    /**
547
-     * Changes database results into REST API entities
548
-     *
549
-     * @param \EEM_Base        $model
550
-     * @param array            $db_row     like results from $wpdb->get_results()
551
-     * @param \WP_REST_Request $rest_request
552
-     * @param string           $deprecated no longer used
553
-     * @return array ready for being converted into json for sending to client
554
-     */
555
-    public function create_entity_from_wpdb_result($model, $db_row, $rest_request, $deprecated = null)
556
-    {
557
-        if (! $rest_request instanceof \WP_REST_Request) {
558
-            //ok so this was called in the old style, where the 3rd arg was
559
-            //$include, and the 4th arg was $context
560
-            //now setup the request just to avoid fatal errors, although we won't be able
561
-            //to truly make use of it because it's kinda devoid of info
562
-            $rest_request = new \WP_REST_Request();
563
-            $rest_request->set_param('include', $rest_request);
564
-            $rest_request->set_param('caps', $deprecated);
565
-        }
566
-        if ($rest_request->get_param('caps') == null) {
567
-            $rest_request->set_param('caps', \EEM_Base::caps_read);
568
-        }
569
-        $entity_array = $this->_create_bare_entity_from_wpdb_results($model, $db_row);
570
-        $entity_array = $this->_add_extra_fields($model, $db_row, $entity_array);
571
-        $entity_array['_links'] = $this->_get_entity_links($model, $db_row, $entity_array);
572
-        $entity_array['_calculated_fields'] = $this->_get_entity_calculations($model, $db_row, $rest_request);
573
-        $entity_array = apply_filters('FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models',
574
-            $entity_array, $model, $rest_request->get_param('caps'), $rest_request, $this);
575
-        $entity_array = $this->_include_requested_models($model, $rest_request, $entity_array, $db_row);
576
-        $entity_array = apply_filters(
577
-            'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
578
-            $entity_array,
579
-            $model,
580
-            $rest_request->get_param('caps'),
581
-            $rest_request,
582
-            $this
583
-        );
584
-        $result_without_inaccessible_fields = Capabilities::filter_out_inaccessible_entity_fields(
585
-            $entity_array,
586
-            $model,
587
-            $rest_request->get_param('caps'),
588
-            $this->get_model_version_info(),
589
-            $model->get_index_primary_key_string(
590
-                $model->deduce_fields_n_values_from_cols_n_values($db_row)
591
-            )
592
-        );
593
-        $this->_set_debug_info(
594
-            'inaccessible fields',
595
-            array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
596
-        );
597
-        return apply_filters(
598
-            'FHEE__Read__create_entity_from_wpdb_results__entity_return',
599
-            $result_without_inaccessible_fields,
600
-            $model,
601
-            $rest_request->get_param('caps')
602
-        );
603
-    }
604
-
605
-
606
-
607
-    /**
608
-     * Creates a REST entity array (JSON object we're going to return in the response, but
609
-     * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
610
-     * from $wpdb->get_row( $sql, ARRAY_A)
611
-     *
612
-     * @param \EEM_Base $model
613
-     * @param array     $db_row
614
-     * @return array entity mostly ready for converting to JSON and sending in the response
615
-     */
616
-    protected function _create_bare_entity_from_wpdb_results(\EEM_Base $model, $db_row)
617
-    {
618
-        $result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
619
-        $result = array_intersect_key($result,
620
-            $this->get_model_version_info()->fields_on_model_in_this_version($model));
621
-        //if this is a CPT, we need to set the global $post to it,
622
-        //otherwise shortcodes etc won't work properly while rendering it
623
-        if ($model instanceof \EEM_CPT_Base) {
624
-            $do_chevy_shuffle = true;
625
-        } else {
626
-            $do_chevy_shuffle = false;
627
-        }
628
-        if ($do_chevy_shuffle) {
629
-            global $post;
630
-            $old_post = $post;
631
-            $post = get_post($result[$model->primary_key_name()]);
632
-            if (! $post instanceof \WP_Post) {
633
-                //well that's weird, because $result is what we JUST fetched from the database
634
-                throw new Rest_Exception(
635
-                    'error_fetching_post_from_database_results',
636
-                    esc_html__(
637
-                        'An item was retrieved from the database but it\'s not a WP_Post like it should be.',
638
-                        'event_espresso'
639
-                    )
640
-                );
641
-            }
642
-            $model_object_classname = 'EE_' . $model->get_this_model_name();
643
-            $post->{$model_object_classname} = \EE_Registry::instance()->load_class(
644
-                $model_object_classname,
645
-                $result,
646
-                false,
647
-                false
648
-                );
649
-        }
650
-        foreach ($result as $field_name => $raw_field_value) {
651
-            $field_obj = $model->field_settings_for($field_name);
652
-            $field_value = $field_obj->prepare_for_set_from_db($raw_field_value);
653
-            if ($this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_ignored())) {
654
-                unset($result[$field_name]);
655
-            } elseif (
656
-            $this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_rendered_format())
657
-            ) {
658
-                $result[$field_name] = array(
659
-                    'raw'      => $field_obj->prepare_for_get($field_value),
660
-                    'rendered' => $field_obj->prepare_for_pretty_echoing($field_value),
661
-                );
662
-            } elseif (
663
-            $this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_pretty_format())
664
-            ) {
665
-                $result[$field_name] = array(
666
-                    'raw'    => $field_obj->prepare_for_get($field_value),
667
-                    'pretty' => $field_obj->prepare_for_pretty_echoing($field_value),
668
-                );
669
-            } elseif ($field_obj instanceof \EE_Datetime_Field) {
670
-                if ($field_value instanceof \DateTime) {
671
-                    $timezone = $field_value->getTimezone();
672
-                    $field_value->setTimezone(new \DateTimeZone('UTC'));
673
-                    $result[$field_name . '_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
674
-                        $field_obj,
675
-                        $field_value,
676
-                        $this->get_model_version_info()->requested_version()
677
-                    );
678
-                    $field_value->setTimezone($timezone);
679
-                    $result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
680
-                        $field_obj,
681
-                        $field_value,
682
-                        $this->get_model_version_info()->requested_version()
683
-                    );
684
-                }
685
-            } else {
686
-                $result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
687
-                    $field_obj,
688
-                    $field_obj->prepare_for_get($field_value),
689
-                    $this->get_model_version_info()->requested_version()
690
-                );
691
-            }
692
-        }
693
-        if ($do_chevy_shuffle) {
694
-            $post = $old_post;
695
-        }
696
-        return $result;
697
-    }
698
-
699
-
700
-
701
-    /**
702
-     * Adds a few extra fields to the entity response
703
-     *
704
-     * @param \EEM_Base $model
705
-     * @param array     $db_row
706
-     * @param array     $entity_array
707
-     * @return array modified entity
708
-     */
709
-    protected function _add_extra_fields(\EEM_Base $model, $db_row, $entity_array)
710
-    {
711
-        if ($model instanceof \EEM_CPT_Base) {
712
-            $entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
713
-        }
714
-        return $entity_array;
715
-    }
716
-
717
-
718
-
719
-    /**
720
-     * Gets links we want to add to the response
721
-     *
722
-     * @global \WP_REST_Server $wp_rest_server
723
-     * @param \EEM_Base        $model
724
-     * @param array            $db_row
725
-     * @param array            $entity_array
726
-     * @return array the _links item in the entity
727
-     */
728
-    protected function _get_entity_links($model, $db_row, $entity_array)
729
-    {
730
-        //add basic links
731
-        $links = array();
732
-        if ($model->has_primary_key_field()) {
733
-            $links['self'] = array(
734
-                array(
735
-                    'href' => $this->get_versioned_link_to(
736
-                        \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
737
-                        . '/'
738
-                        . $entity_array[$model->primary_key_name()]
739
-                    ),
740
-                ),
741
-            );
742
-        }
743
-        $links['collection'] = array(
744
-            array(
745
-                'href' => $this->get_versioned_link_to(
746
-                    \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
747
-                ),
748
-            ),
749
-        );
750
-        //add links to related models
751
-        if ($model->has_primary_key_field()) {
752
-            foreach ($this->get_model_version_info()->relation_settings($model) as $relation_name => $relation_obj) {
753
-                $related_model_part = Read::get_related_entity_name($relation_name, $relation_obj);
754
-                $links[\EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
755
-                    array(
756
-                        'href'   => $this->get_versioned_link_to(
757
-                            \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
758
-                            . '/'
759
-                            . $entity_array[$model->primary_key_name()]
760
-                            . '/'
761
-                            . $related_model_part
762
-                        ),
763
-                        'single' => $relation_obj instanceof \EE_Belongs_To_Relation ? true : false,
764
-                    ),
765
-                );
766
-            }
767
-        }
768
-        return $links;
769
-    }
770
-
771
-
772
-
773
-    /**
774
-     * Adds the included models indicated in the request to the entity provided
775
-     *
776
-     * @param \EEM_Base        $model
777
-     * @param \WP_REST_Request $rest_request
778
-     * @param array            $entity_array
779
-     * @param array            $db_row
780
-     * @return array the modified entity
781
-     */
782
-    protected function _include_requested_models(
783
-        \EEM_Base $model,
784
-        \WP_REST_Request $rest_request,
785
-        $entity_array,
786
-        $db_row = array()
787
-    ) {
788
-        //if $db_row not included, hope the entity array has what we need
789
-        if (! $db_row) {
790
-            $db_row = $entity_array;
791
-        }
792
-        $includes_for_this_model = $this->explode_and_get_items_prefixed_with($rest_request->get_param('include'), '');
793
-        $includes_for_this_model = $this->_remove_model_names_from_array($includes_for_this_model);
794
-        //if they passed in * or didn't specify any includes, return everything
795
-        if (! in_array('*', $includes_for_this_model)
796
-            && ! empty($includes_for_this_model)
797
-        ) {
798
-            if ($model->has_primary_key_field()) {
799
-                //always include the primary key. ya just gotta know that at least
800
-                $includes_for_this_model[] = $model->primary_key_name();
801
-            }
802
-            if ($this->explode_and_get_items_prefixed_with($rest_request->get_param('calculate'), '')) {
803
-                $includes_for_this_model[] = '_calculated_fields';
804
-            }
805
-            $entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
806
-        }
807
-        $relation_settings = $this->get_model_version_info()->relation_settings($model);
808
-        foreach ($relation_settings as $relation_name => $relation_obj) {
809
-            $related_fields_to_include = $this->explode_and_get_items_prefixed_with(
810
-                $rest_request->get_param('include'),
811
-                $relation_name
812
-            );
813
-            $related_fields_to_calculate = $this->explode_and_get_items_prefixed_with(
814
-                $rest_request->get_param('calculate'),
815
-                $relation_name
816
-            );
817
-            //did they specify they wanted to include a related model, or
818
-            //specific fields from a related model?
819
-            //or did they specify to calculate a field from a related model?
820
-            if ($related_fields_to_include || $related_fields_to_calculate) {
821
-                //if so, we should include at least some part of the related model
822
-                $pretend_related_request = new \WP_REST_Request();
823
-                $pretend_related_request->set_query_params(
824
-                    array(
825
-                        'caps'      => $rest_request->get_param('caps'),
826
-                        'include'   => $related_fields_to_include,
827
-                        'calculate' => $related_fields_to_calculate,
828
-                    )
829
-                );
830
-                $pretend_related_request->add_header('no_rest_headers', true);
831
-                $primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
832
-                    $model->get_index_primary_key_string(
833
-                        $model->deduce_fields_n_values_from_cols_n_values($db_row)
834
-                    )
835
-                );
836
-                $related_results = $this->_get_entities_from_relation(
837
-                    $primary_model_query_params,
838
-                    $relation_obj,
839
-                    $pretend_related_request
840
-                );
841
-                $entity_array[Read::get_related_entity_name($relation_name, $relation_obj)] = $related_results
842
-                                                                                              instanceof
843
-                                                                                              \WP_Error
844
-                    ? null
845
-                    : $related_results;
846
-            }
847
-        }
848
-        return $entity_array;
849
-    }
850
-
851
-
852
-
853
-    /**
854
-     * Returns a new array with all the names of models removed. Eg
855
-     * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
856
-     *
857
-     * @param array $arr
858
-     * @return array
859
-     */
860
-    private function _remove_model_names_from_array($arr)
861
-    {
862
-        return array_diff($arr, array_keys(\EE_Registry::instance()->non_abstract_db_models));
863
-    }
864
-
865
-
866
-
867
-    /**
868
-     * Gets the calculated fields for the response
869
-     *
870
-     * @param \EEM_Base        $model
871
-     * @param array            $wpdb_row
872
-     * @param \WP_REST_Request $rest_request
873
-     * @return \stdClass the _calculations item in the entity
874
-     */
875
-    protected function _get_entity_calculations($model, $wpdb_row, $rest_request)
876
-    {
877
-        $calculated_fields = $this->explode_and_get_items_prefixed_with(
878
-            $rest_request->get_param('calculate'),
879
-            ''
880
-        );
881
-        //note: setting calculate=* doesn't do anything
882
-        $calculated_fields_to_return = new \stdClass();
883
-        foreach ($calculated_fields as $field_to_calculate) {
884
-            try {
885
-                $calculated_fields_to_return->$field_to_calculate = Model_Data_Translator::prepare_field_value_for_json(
886
-                    null,
887
-                    $this->_fields_calculator->retrieve_calculated_field_value(
888
-                        $model,
889
-                        $field_to_calculate,
890
-                        $wpdb_row,
891
-                        $rest_request,
892
-                        $this
893
-                    ),
894
-                    $this->get_model_version_info()->requested_version()
895
-                );
896
-            } catch (Rest_Exception $e) {
897
-                //if we don't have permission to read it, just leave it out. but let devs know about the problem
898
-                $this->_set_response_header(
899
-                    'Notices-Field-Calculation-Errors['
900
-                    . $e->get_string_code()
901
-                    . ']['
902
-                    . $model->get_this_model_name()
903
-                    . ']['
904
-                    . $field_to_calculate
905
-                    . ']',
906
-                    $e->getMessage(),
907
-                    true
908
-                );
909
-            }
910
-        }
911
-        return $calculated_fields_to_return;
912
-    }
913
-
914
-
915
-
916
-    /**
917
-     * Gets the full URL to the resource, taking the requested version into account
918
-     *
919
-     * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
920
-     * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
921
-     */
922
-    public function get_versioned_link_to($link_part_after_version_and_slash)
923
-    {
924
-        return rest_url(
925
-            \EED_Core_Rest_Api::ee_api_namespace
926
-            . $this->get_model_version_info()->requested_version()
927
-            . '/'
928
-            . $link_part_after_version_and_slash
929
-        );
930
-    }
931
-
932
-
933
-
934
-    /**
935
-     * Gets the correct lowercase name for the relation in the API according
936
-     * to the relation's type
937
-     *
938
-     * @param string                  $relation_name
939
-     * @param \EE_Model_Relation_Base $relation_obj
940
-     * @return string
941
-     */
942
-    public static function get_related_entity_name($relation_name, $relation_obj)
943
-    {
944
-        if ($relation_obj instanceof \EE_Belongs_To_Relation) {
945
-            return strtolower($relation_name);
946
-        } else {
947
-            return \EEH_Inflector::pluralize_and_lower($relation_name);
948
-        }
949
-    }
950
-
951
-
952
-
953
-    /**
954
-     * Gets the one model object with the specified id for the specified model
955
-     *
956
-     * @param \EEM_Base        $model
957
-     * @param \WP_REST_Request $request
958
-     * @return array|\WP_Error
959
-     */
960
-    public function get_entity_from_model($model, $request)
961
-    {
962
-        $query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
963
-        if ($model instanceof \EEM_Soft_Delete_Base) {
964
-            $query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
965
-        }
966
-        $restricted_query_params = $query_params;
967
-        $restricted_query_params['caps'] = $this->validate_context($request->get_param('caps'));
968
-        $this->_set_debug_info('model query params', $restricted_query_params);
969
-        $model_rows = $model->get_all_wpdb_results($restricted_query_params);
970
-        if (! empty ($model_rows)) {
971
-            return $this->create_entity_from_wpdb_result(
972
-                $model,
973
-                array_shift($model_rows),
974
-                $request);
975
-        } else {
976
-            //ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
977
-            $lowercase_model_name = strtolower($model->get_this_model_name());
978
-            $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
979
-            if (! empty($model_rows_found_sans_restrictions)) {
980
-                //you got shafted- it existed but we didn't want to tell you!
981
-                return new \WP_Error(
982
-                    'rest_user_cannot_read',
983
-                    sprintf(
984
-                        __('Sorry, you cannot read this %1$s. Missing permissions are: %2$s', 'event_espresso'),
985
-                        strtolower($model->get_this_model_name()),
986
-                        Capabilities::get_missing_permissions_string(
987
-                            $model,
988
-                            $this->validate_context($request->get_param('caps')))
989
-                    ),
990
-                    array('status' => 403)
991
-                );
992
-            } else {
993
-                //it's not you. It just doesn't exist
994
-                return new \WP_Error(
995
-                    sprintf('rest_%s_invalid_id', $lowercase_model_name),
996
-                    sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
997
-                    array('status' => 404)
998
-                );
999
-            }
1000
-        }
1001
-    }
1002
-
1003
-
1004
-
1005
-    /**
1006
-     * If a context is provided which isn't valid, maybe it was added in a future
1007
-     * version so just treat it as a default read
1008
-     *
1009
-     * @param string $context
1010
-     * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
1011
-     */
1012
-    public function validate_context($context)
1013
-    {
1014
-        if (! $context) {
1015
-            $context = \EEM_Base::caps_read;
1016
-        }
1017
-        $valid_contexts = \EEM_Base::valid_cap_contexts();
1018
-        if (in_array($context, $valid_contexts)) {
1019
-            return $context;
1020
-        } else {
1021
-            return \EEM_Base::caps_read;
1022
-        }
1023
-    }
1024
-
1025
-
1026
-
1027
-    /**
1028
-     * Verifies the passed in value is an allowable default where conditions value.
1029
-     *
1030
-     * @param $default_query_params
1031
-     * @return string
1032
-     */
1033
-    public function validate_default_query_params($default_query_params)
1034
-    {
1035
-        $valid_default_where_conditions_for_api_calls = array(
1036
-            \EEM_Base::default_where_conditions_all,
1037
-            \EEM_Base::default_where_conditions_minimum_all,
1038
-            \EEM_Base::default_where_conditions_minimum_others,
1039
-        );
1040
-        if (! $default_query_params) {
1041
-            $default_query_params = \EEM_Base::default_where_conditions_all;
1042
-        }
1043
-        if (
1044
-        in_array(
1045
-            $default_query_params,
1046
-            $valid_default_where_conditions_for_api_calls,
1047
-            true
1048
-        )
1049
-        ) {
1050
-            return $default_query_params;
1051
-        } else {
1052
-            return \EEM_Base::default_where_conditions_all;
1053
-        }
1054
-    }
1055
-
1056
-
1057
-
1058
-    /**
1059
-     * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
1060
-     * Note: right now the query parameter keys for fields (and related fields)
1061
-     * can be left as-is, but it's quite possible this will change someday.
1062
-     * Also, this method's contents might be candidate for moving to Model_Data_Translator
1063
-     *
1064
-     * @param \EEM_Base $model
1065
-     * @param array     $query_parameters from $_GET parameter @see Read:handle_request_get_all
1066
-     * @return array like what EEM_Base::get_all() expects or FALSE to indicate
1067
-     *                                    that absolutely no results should be returned
1068
-     * @throws \EE_Error
1069
-     */
1070
-    public function create_model_query_params($model, $query_parameters)
1071
-    {
1072
-        $model_query_params = array();
1073
-        if (isset($query_parameters['where'])) {
1074
-            $model_query_params[0] = Model_Data_Translator::prepare_conditions_query_params_for_models(
1075
-                $query_parameters['where'],
1076
-                $model,
1077
-                $this->get_model_version_info()->requested_version()
1078
-            );
1079
-        }
1080
-        if (isset($query_parameters['order_by'])) {
1081
-            $order_by = $query_parameters['order_by'];
1082
-        } elseif (isset($query_parameters['orderby'])) {
1083
-            $order_by = $query_parameters['orderby'];
1084
-        } else {
1085
-            $order_by = null;
1086
-        }
1087
-        if ($order_by !== null) {
1088
-            if (is_array($order_by)) {
1089
-                $order_by = Model_Data_Translator::prepare_field_names_in_array_keys_from_json($order_by);
1090
-            } else {
1091
-                //it's a single item
1092
-                $order_by = Model_Data_Translator::prepare_field_name_from_json($order_by);
1093
-            }
1094
-            $model_query_params['order_by'] = $order_by;
1095
-        }
1096
-        if (isset($query_parameters['group_by'])) {
1097
-            $group_by = $query_parameters['group_by'];
1098
-        } elseif (isset($query_parameters['groupby'])) {
1099
-            $group_by = $query_parameters['groupby'];
1100
-        } else {
1101
-            $group_by = array_keys($model->get_combined_primary_key_fields());
1102
-        }
1103
-        //make sure they're all real names
1104
-        if (is_array($group_by)) {
1105
-            $group_by = Model_Data_Translator::prepare_field_names_from_json($group_by);
1106
-        }
1107
-        if ($group_by !== null) {
1108
-            $model_query_params['group_by'] = $group_by;
1109
-        }
1110
-        if (isset($query_parameters['having'])) {
1111
-            $model_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_models(
1112
-                $query_parameters['having'],
1113
-                $model,
1114
-                $this->get_model_version_info()->requested_version()
1115
-            );
1116
-        }
1117
-        if (isset($query_parameters['order'])) {
1118
-            $model_query_params['order'] = $query_parameters['order'];
1119
-        }
1120
-        if (isset($query_parameters['mine'])) {
1121
-            $model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
1122
-        }
1123
-        if (isset($query_parameters['limit'])) {
1124
-            //limit should be either a string like '23' or '23,43', or an array with two items in it
1125
-            if (! is_array($query_parameters['limit'])) {
1126
-                $limit_array = explode(',', (string)$query_parameters['limit']);
1127
-            } else {
1128
-                $limit_array = $query_parameters['limit'];
1129
-            }
1130
-            $sanitized_limit = array();
1131
-            foreach ($limit_array as $key => $limit_part) {
1132
-                if ($this->_debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1133
-                    throw new \EE_Error(
1134
-                        sprintf(
1135
-                            __('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.',
1136
-                                'event_espresso'),
1137
-                            wp_json_encode($query_parameters['limit'])
1138
-                        )
1139
-                    );
1140
-                }
1141
-                $sanitized_limit[] = (int)$limit_part;
1142
-            }
1143
-            $model_query_params['limit'] = implode(',', $sanitized_limit);
1144
-        } else {
1145
-            $model_query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
1146
-        }
1147
-        if (isset($query_parameters['caps'])) {
1148
-            $model_query_params['caps'] = $this->validate_context($query_parameters['caps']);
1149
-        } else {
1150
-            $model_query_params['caps'] = \EEM_Base::caps_read;
1151
-        }
1152
-        if (isset($query_parameters['default_where_conditions'])) {
1153
-            $model_query_params['default_where_conditions'] = $this->validate_default_query_params($query_parameters['default_where_conditions']);
1154
-        }
1155
-        return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
1156
-    }
1157
-
1158
-
1159
-
1160
-    /**
1161
-     * Changes the REST-style query params for use in the models
1162
-     *
1163
-     * @deprecated
1164
-     * @param \EEM_Base $model
1165
-     * @param array     $query_params sub-array from @see EEM_Base::get_all()
1166
-     * @return array
1167
-     */
1168
-    public function prepare_rest_query_params_key_for_models($model, $query_params)
1169
-    {
1170
-        $model_ready_query_params = array();
1171
-        foreach ($query_params as $key => $value) {
1172
-            if (is_array($value)) {
1173
-                $model_ready_query_params[$key] = $this->prepare_rest_query_params_key_for_models($model, $value);
1174
-            } else {
1175
-                $model_ready_query_params[$key] = $value;
1176
-            }
1177
-        }
1178
-        return $model_ready_query_params;
1179
-    }
1180
-
1181
-
1182
-
1183
-    /**
1184
-     * @deprecated
1185
-     * @param $model
1186
-     * @param $query_params
1187
-     * @return array
1188
-     */
1189
-    public function prepare_rest_query_params_values_for_models($model, $query_params)
1190
-    {
1191
-        $model_ready_query_params = array();
1192
-        foreach ($query_params as $key => $value) {
1193
-            if (is_array($value)) {
1194
-                $model_ready_query_params[$key] = $this->prepare_rest_query_params_values_for_models($model, $value);
1195
-            } else {
1196
-                $model_ready_query_params[$key] = $value;
1197
-            }
1198
-        }
1199
-        return $model_ready_query_params;
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * Explodes the string on commas, and only returns items with $prefix followed by a period.
1206
-     * If no prefix is specified, returns items with no period.
1207
-     *
1208
-     * @param string|array $string_to_explode eg "jibba,jabba, blah, blaabla" or array('jibba', 'jabba' )
1209
-     * @param string       $prefix            "Event" or "foobar"
1210
-     * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1211
-     *                                        we only return strings starting with that and a period; if no prefix was
1212
-     *                                        specified we return all items containing NO periods
1213
-     */
1214
-    public function explode_and_get_items_prefixed_with($string_to_explode, $prefix)
1215
-    {
1216
-        if (is_string($string_to_explode)) {
1217
-            $exploded_contents = explode(',', $string_to_explode);
1218
-        } else if (is_array($string_to_explode)) {
1219
-            $exploded_contents = $string_to_explode;
1220
-        } else {
1221
-            $exploded_contents = array();
1222
-        }
1223
-        //if the string was empty, we want an empty array
1224
-        $exploded_contents = array_filter($exploded_contents);
1225
-        $contents_with_prefix = array();
1226
-        foreach ($exploded_contents as $item) {
1227
-            $item = trim($item);
1228
-            //if no prefix was provided, so we look for items with no "." in them
1229
-            if (! $prefix) {
1230
-                //does this item have a period?
1231
-                if (strpos($item, '.') === false) {
1232
-                    //if not, then its what we're looking for
1233
-                    $contents_with_prefix[] = $item;
1234
-                }
1235
-            } else if (strpos($item, $prefix . '.') === 0) {
1236
-                //this item has the prefix and a period, grab it
1237
-                $contents_with_prefix[] = substr(
1238
-                    $item,
1239
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1240
-                );
1241
-            } else if ($item === $prefix) {
1242
-                //this item is JUST the prefix
1243
-                //so let's grab everything after, which is a blank string
1244
-                $contents_with_prefix[] = '';
1245
-            }
1246
-        }
1247
-        return $contents_with_prefix;
1248
-    }
1249
-
1250
-
1251
-
1252
-    /**
1253
-     * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1254
-     * Deprecated because its return values were really quite confusing- sometimes it returned
1255
-     * an empty array (when the include string was blank or '*') or sometimes it returned
1256
-     * array('*') (when you provided a model and a model of that kind was found).
1257
-     * Parses the $include_string so we fetch all the field names relating to THIS model
1258
-     * (ie have NO period in them), or for the provided model (ie start with the model
1259
-     * name and then a period).
1260
-     * @param string $include_string @see Read:handle_request_get_all
1261
-     * @param string $model_name
1262
-     * @return array of fields for this model. If $model_name is provided, then
1263
-     *                               the fields for that model, with the model's name removed from each.
1264
-     *                               If $include_string was blank or '*' returns an empty array
1265
-     */
1266
-    public function extract_includes_for_this_model($include_string, $model_name = null)
1267
-    {
1268
-        if (is_array($include_string)) {
1269
-            $include_string = implode(',', $include_string);
1270
-        }
1271
-        if ($include_string === '*' || $include_string === '') {
1272
-            return array();
1273
-        }
1274
-        $includes = explode(',', $include_string);
1275
-        $extracted_fields_to_include = array();
1276
-        if ($model_name) {
1277
-            foreach ($includes as $field_to_include) {
1278
-                $field_to_include = trim($field_to_include);
1279
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1280
-                    //found the model name at the exact start
1281
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1282
-                    $extracted_fields_to_include[] = $field_sans_model_name;
1283
-                } elseif ($field_to_include == $model_name) {
1284
-                    $extracted_fields_to_include[] = '*';
1285
-                }
1286
-            }
1287
-        } else {
1288
-            //look for ones with no period
1289
-            foreach ($includes as $field_to_include) {
1290
-                $field_to_include = trim($field_to_include);
1291
-                if (
1292
-                    strpos($field_to_include, '.') === false
1293
-                    && ! $this->get_model_version_info()->is_model_name_in_this_version($field_to_include)
1294
-                ) {
1295
-                    $extracted_fields_to_include[] = $field_to_include;
1296
-                }
1297
-            }
1298
-        }
1299
-        return $extracted_fields_to_include;
1300
-    }
30
+	/**
31
+	 * @var Calculated_Model_Fields
32
+	 */
33
+	protected $_fields_calculator;
34
+
35
+
36
+
37
+	/**
38
+	 * Read constructor.
39
+	 */
40
+	public function __construct()
41
+	{
42
+		parent::__construct();
43
+		$this->_fields_calculator = new Calculated_Model_Fields();
44
+	}
45
+
46
+
47
+
48
+	/**
49
+	 * Handles requests to get all (or a filtered subset) of entities for a particular model
50
+	 *
51
+	 * @param \WP_REST_Request $request
52
+	 * @return \WP_REST_Response|\WP_Error
53
+	 */
54
+	public static function handle_request_get_all(\WP_REST_Request $request)
55
+	{
56
+		$controller = new Read();
57
+		try {
58
+			$matches = $controller->parse_route(
59
+				$request->get_route(),
60
+				'~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)~',
61
+				array('version', 'model')
62
+			);
63
+			$controller->set_requested_version($matches['version']);
64
+			$model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
65
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
66
+				return $controller->send_response(
67
+					new \WP_Error(
68
+						'endpoint_parsing_error',
69
+						sprintf(
70
+							__('There is no model for endpoint %s. Please contact event espresso support',
71
+								'event_espresso'),
72
+							$model_name_singular
73
+						)
74
+					)
75
+				);
76
+			}
77
+			return $controller->send_response(
78
+				$controller->get_entities_from_model(
79
+					$controller->get_model_version_info()->load_model($model_name_singular),
80
+					$request
81
+				)
82
+			);
83
+		} catch (\Exception $e) {
84
+			return $controller->send_response($e);
85
+		}
86
+	}
87
+
88
+
89
+
90
+	/**
91
+	 * Prepares and returns schema for any OPTIONS request.
92
+	 *
93
+	 * @param string $model_name Something like `Event` or `Registration`
94
+	 * @param string $version    The API endpoint version being used.
95
+	 * @return array
96
+	 */
97
+	public static function handle_schema_request($model_name, $version)
98
+	{
99
+		$controller = new Read();
100
+		try {
101
+			$controller->set_requested_version($version);
102
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name)) {
103
+				return array();
104
+			}
105
+			//get the model for this version
106
+			$model = $controller->get_model_version_info()->load_model($model_name);
107
+			$model_schema = new JsonModelSchema($model);
108
+			return $model_schema->getModelSchemaForRelations(
109
+				$controller->get_model_version_info()->relation_settings($model),
110
+				$controller->_customize_schema_for_rest_response(
111
+					$model,
112
+					$model_schema->getModelSchemaForFields(
113
+						$controller->get_model_version_info()->fields_on_model_in_this_version($model),
114
+						$model_schema->getInitialSchemaStructure()
115
+					)
116
+				)
117
+			);
118
+		} catch (\Exception $e) {
119
+			return array();
120
+		}
121
+	}
122
+
123
+
124
+
125
+	/**
126
+	 * This loops through each field in the given schema for the model and does the following:
127
+	 * - add any extra fields that are REST API specific and related to existing fields.
128
+	 * - transform default values into the correct format for a REST API response.
129
+	 *
130
+	 * @param \EEM_Base $model
131
+	 * @param array     $schema
132
+	 * @return array  The final schema.
133
+	 */
134
+	protected function _customize_schema_for_rest_response(\EEM_Base $model, array $schema)
135
+	{
136
+		foreach ($this->get_model_version_info()->fields_on_model_in_this_version($model) as $field_name => $field) {
137
+			$schema = $this->_translate_defaults_for_rest_response(
138
+				$field_name,
139
+				$field,
140
+				$this->_maybe_add_extra_fields_to_schema($field_name, $field, $schema)
141
+			);
142
+		}
143
+		return $schema;
144
+	}
145
+
146
+
147
+
148
+	/**
149
+	 * This is used to ensure that the 'default' value set in the schema response is formatted correctly for the REST
150
+	 * response.
151
+	 *
152
+	 * @param                      $field_name
153
+	 * @param \EE_Model_Field_Base $field
154
+	 * @param array                $schema
155
+	 * @return array
156
+	 */
157
+	protected function _translate_defaults_for_rest_response($field_name, \EE_Model_Field_Base $field, array $schema)
158
+	{
159
+		if (isset($schema['properties'][$field_name]['default'])) {
160
+			if (is_array($schema['properties'][$field_name]['default'])) {
161
+				foreach ($schema['properties'][$field_name]['default'] as $default_key => $default_value) {
162
+					if ($default_key === 'raw') {
163
+						$schema['properties'][$field_name]['default'][$default_key] = Model_Data_Translator::prepare_field_value_for_json(
164
+							$field,
165
+							$default_value,
166
+							$this->get_model_version_info()->requested_version()
167
+						);
168
+					}
169
+				}
170
+			} else {
171
+				$schema['properties'][$field_name]['default'] = Model_Data_Translator::prepare_field_value_for_json(
172
+					$field,
173
+					$schema['properties'][$field_name]['default'],
174
+					$this->get_model_version_info()->requested_version()
175
+				);
176
+			}
177
+		}
178
+		return $schema;
179
+	}
180
+
181
+
182
+
183
+	/**
184
+	 * Adds additional fields to the schema
185
+	 * The REST API returns a GMT value field for each datetime field in the resource.  Thus the description about this
186
+	 * needs to be added to the schema.
187
+	 *
188
+	 * @param                      $field_name
189
+	 * @param \EE_Model_Field_Base $field
190
+	 * @param array                $schema
191
+	 * @return array
192
+	 */
193
+	protected function _maybe_add_extra_fields_to_schema($field_name, \EE_Model_Field_Base $field, array $schema)
194
+	{
195
+		if ($field instanceof EE_Datetime_Field) {
196
+			$schema['properties'][$field_name . '_gmt'] = $field->getSchema();
197
+			//modify the description
198
+			$schema['properties'][$field_name . '_gmt']['description'] = sprintf(
199
+				esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
200
+				$field->get_nicename()
201
+			);
202
+		}
203
+		return $schema;
204
+	}
205
+
206
+
207
+
208
+	/**
209
+	 * Used to figure out the route from the request when a `WP_REST_Request` object is not available
210
+	 *
211
+	 * @return string
212
+	 */
213
+	protected function get_route_from_request()
214
+	{
215
+		if (isset($GLOBALS['wp'])
216
+			&& $GLOBALS['wp'] instanceof \WP
217
+			&& isset($GLOBALS['wp']->query_vars['rest_route'])
218
+		) {
219
+			return $GLOBALS['wp']->query_vars['rest_route'];
220
+		} else {
221
+			return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
222
+		}
223
+	}
224
+
225
+
226
+
227
+	/**
228
+	 * Gets a single entity related to the model indicated in the path and its id
229
+	 *
230
+	 * @param \WP_REST_Request $request
231
+	 * @return \WP_REST_Response|\WP_Error
232
+	 */
233
+	public static function handle_request_get_one(\WP_REST_Request $request)
234
+	{
235
+		$controller = new Read();
236
+		try {
237
+			$matches = $controller->parse_route(
238
+				$request->get_route(),
239
+				'~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)~',
240
+				array('version', 'model', 'id'));
241
+			$controller->set_requested_version($matches['version']);
242
+			$model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
243
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
244
+				return $controller->send_response(
245
+					new \WP_Error(
246
+						'endpoint_parsing_error',
247
+						sprintf(
248
+							__('There is no model for endpoint %s. Please contact event espresso support',
249
+								'event_espresso'),
250
+							$model_name_singular
251
+						)
252
+					)
253
+				);
254
+			}
255
+			return $controller->send_response(
256
+				$controller->get_entity_from_model(
257
+					$controller->get_model_version_info()->load_model($model_name_singular),
258
+					$request
259
+				)
260
+			);
261
+		} catch (\Exception $e) {
262
+			return $controller->send_response($e);
263
+		}
264
+	}
265
+
266
+
267
+
268
+	/**
269
+	 * Gets all the related entities (or if its a belongs-to relation just the one)
270
+	 * to the item with the given id
271
+	 *
272
+	 * @param \WP_REST_Request $request
273
+	 * @return \WP_REST_Response|\WP_Error
274
+	 */
275
+	public static function handle_request_get_related(\WP_REST_Request $request)
276
+	{
277
+		$controller = new Read();
278
+		try {
279
+			$matches = $controller->parse_route(
280
+				$request->get_route(),
281
+				'~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)/(.*)~',
282
+				array('version', 'model', 'id', 'related_model')
283
+			);
284
+			$controller->set_requested_version($matches['version']);
285
+			$main_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
286
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
287
+				return $controller->send_response(
288
+					new \WP_Error(
289
+						'endpoint_parsing_error',
290
+						sprintf(
291
+							__('There is no model for endpoint %s. Please contact event espresso support',
292
+								'event_espresso'),
293
+							$main_model_name_singular
294
+						)
295
+					)
296
+				);
297
+			}
298
+			$main_model = $controller->get_model_version_info()->load_model($main_model_name_singular);
299
+			//assume the related model name is plural and try to find the model's name
300
+			$related_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['related_model']);
301
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
302
+				//so the word didn't singularize well. Maybe that's just because it's a singular word?
303
+				$related_model_name_singular = \EEH_Inflector::humanize($matches['related_model']);
304
+			}
305
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
306
+				return $controller->send_response(
307
+					new \WP_Error(
308
+						'endpoint_parsing_error',
309
+						sprintf(
310
+							__('There is no model for endpoint %s. Please contact event espresso support',
311
+								'event_espresso'),
312
+							$related_model_name_singular
313
+						)
314
+					)
315
+				);
316
+			}
317
+			return $controller->send_response(
318
+				$controller->get_entities_from_relation(
319
+					$request->get_param('id'),
320
+					$main_model->related_settings_for($related_model_name_singular),
321
+					$request
322
+				)
323
+			);
324
+		} catch (\Exception $e) {
325
+			return $controller->send_response($e);
326
+		}
327
+	}
328
+
329
+
330
+
331
+	/**
332
+	 * Gets a collection for the given model and filters
333
+	 *
334
+	 * @param \EEM_Base        $model
335
+	 * @param \WP_REST_Request $request
336
+	 * @return array|\WP_Error
337
+	 */
338
+	public function get_entities_from_model($model, $request)
339
+	{
340
+		$query_params = $this->create_model_query_params($model, $request->get_params());
341
+		if (! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
342
+			$model_name_plural = \EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
343
+			return new \WP_Error(
344
+				sprintf('rest_%s_cannot_list', $model_name_plural),
345
+				sprintf(
346
+					__('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
347
+					$model_name_plural,
348
+					Capabilities::get_missing_permissions_string($model, $query_params['caps'])
349
+				),
350
+				array('status' => 403)
351
+			);
352
+		}
353
+		if (! $request->get_header('no_rest_headers')) {
354
+			$this->_set_headers_from_query_params($model, $query_params);
355
+		}
356
+		/** @type array $results */
357
+		$results = $model->get_all_wpdb_results($query_params);
358
+		$nice_results = array();
359
+		foreach ($results as $result) {
360
+			$nice_results[] = $this->create_entity_from_wpdb_result(
361
+				$model,
362
+				$result,
363
+				$request
364
+			);
365
+		}
366
+		return $nice_results;
367
+	}
368
+
369
+
370
+
371
+	/**
372
+	 * @param array                   $primary_model_query_params query params for finding the item from which
373
+	 *                                                            relations will be based
374
+	 * @param \EE_Model_Relation_Base $relation
375
+	 * @param \WP_REST_Request        $request
376
+	 * @return \WP_Error|array
377
+	 */
378
+	protected function _get_entities_from_relation($primary_model_query_params, $relation, $request)
379
+	{
380
+		$context = $this->validate_context($request->get_param('caps'));
381
+		$model = $relation->get_this_model();
382
+		$related_model = $relation->get_other_model();
383
+		if (! isset($primary_model_query_params[0])) {
384
+			$primary_model_query_params[0] = array();
385
+		}
386
+		//check if they can access the 1st model object
387
+		$primary_model_query_params = array(
388
+			0       => $primary_model_query_params[0],
389
+			'limit' => 1,
390
+		);
391
+		if ($model instanceof \EEM_Soft_Delete_Base) {
392
+			$primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($primary_model_query_params);
393
+		}
394
+		$restricted_query_params = $primary_model_query_params;
395
+		$restricted_query_params['caps'] = $context;
396
+		$this->_set_debug_info('main model query params', $restricted_query_params);
397
+		$this->_set_debug_info('missing caps', Capabilities::get_missing_permissions_string($related_model, $context));
398
+		if (
399
+		! (
400
+			Capabilities::current_user_has_partial_access_to($related_model, $context)
401
+			&& $model->exists($restricted_query_params)
402
+		)
403
+		) {
404
+			if ($relation instanceof \EE_Belongs_To_Relation) {
405
+				$related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
406
+			} else {
407
+				$related_model_name_maybe_plural = \EEH_Inflector::pluralize_and_lower($related_model->get_this_model_name());
408
+			}
409
+			return new \WP_Error(
410
+				sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
411
+				sprintf(
412
+					__('Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
413
+						'event_espresso'),
414
+					$related_model_name_maybe_plural,
415
+					$relation->get_this_model()->get_this_model_name(),
416
+					implode(
417
+						',',
418
+						array_keys(
419
+							Capabilities::get_missing_permissions($related_model, $context)
420
+						)
421
+					)
422
+				),
423
+				array('status' => 403)
424
+			);
425
+		}
426
+		$query_params = $this->create_model_query_params($relation->get_other_model(), $request->get_params());
427
+		foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
428
+			$query_params[0][$relation->get_this_model()->get_this_model_name()
429
+							 . '.'
430
+							 . $where_condition_key] = $where_condition_value;
431
+		}
432
+		$query_params['default_where_conditions'] = 'none';
433
+		$query_params['caps'] = $context;
434
+		if (! $request->get_header('no_rest_headers')) {
435
+			$this->_set_headers_from_query_params($relation->get_other_model(), $query_params);
436
+		}
437
+		/** @type array $results */
438
+		$results = $relation->get_other_model()->get_all_wpdb_results($query_params);
439
+		$nice_results = array();
440
+		foreach ($results as $result) {
441
+			$nice_result = $this->create_entity_from_wpdb_result(
442
+				$relation->get_other_model(),
443
+				$result,
444
+				$request
445
+			);
446
+			if ($relation instanceof \EE_HABTM_Relation) {
447
+				//put the unusual stuff (properties from the HABTM relation) first, and make sure
448
+				//if there are conflicts we prefer the properties from the main model
449
+				$join_model_result = $this->create_entity_from_wpdb_result(
450
+					$relation->get_join_model(),
451
+					$result,
452
+					$request
453
+				);
454
+				$joined_result = array_merge($nice_result, $join_model_result);
455
+				//but keep the meta stuff from the main model
456
+				if (isset($nice_result['meta'])) {
457
+					$joined_result['meta'] = $nice_result['meta'];
458
+				}
459
+				$nice_result = $joined_result;
460
+			}
461
+			$nice_results[] = $nice_result;
462
+		}
463
+		if ($relation instanceof \EE_Belongs_To_Relation) {
464
+			return array_shift($nice_results);
465
+		} else {
466
+			return $nice_results;
467
+		}
468
+	}
469
+
470
+
471
+
472
+	/**
473
+	 * Gets the collection for given relation object
474
+	 * The same as Read::get_entities_from_model(), except if the relation
475
+	 * is a HABTM relation, in which case it merges any non-foreign-key fields from
476
+	 * the join-model-object into the results
477
+	 *
478
+	 * @param string                  $id the ID of the thing we are fetching related stuff from
479
+	 * @param \EE_Model_Relation_Base $relation
480
+	 * @param \WP_REST_Request        $request
481
+	 * @return array|\WP_Error
482
+	 * @throws \EE_Error
483
+	 */
484
+	public function get_entities_from_relation($id, $relation, $request)
485
+	{
486
+		if (! $relation->get_this_model()->has_primary_key_field()) {
487
+			throw new \EE_Error(
488
+				sprintf(
489
+					__('Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
490
+						'event_espresso'),
491
+					$relation->get_this_model()->get_this_model_name()
492
+				)
493
+			);
494
+		}
495
+		return $this->_get_entities_from_relation(
496
+			array(
497
+				array(
498
+					$relation->get_this_model()->primary_key_name() => $id,
499
+				),
500
+			),
501
+			$relation,
502
+			$request
503
+		);
504
+	}
505
+
506
+
507
+
508
+	/**
509
+	 * Sets the headers that are based on the model and query params,
510
+	 * like the total records. This should only be called on the original request
511
+	 * from the client, not on subsequent internal
512
+	 *
513
+	 * @param \EEM_Base $model
514
+	 * @param array     $query_params
515
+	 * @return void
516
+	 */
517
+	protected function _set_headers_from_query_params($model, $query_params)
518
+	{
519
+		$this->_set_debug_info('model query params', $query_params);
520
+		$this->_set_debug_info('missing caps',
521
+			Capabilities::get_missing_permissions_string($model, $query_params['caps']));
522
+		//normally the limit to a 2-part array, where the 2nd item is the limit
523
+		if (! isset($query_params['limit'])) {
524
+			$query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
525
+		}
526
+		if (is_array($query_params['limit'])) {
527
+			$limit_parts = $query_params['limit'];
528
+		} else {
529
+			$limit_parts = explode(',', $query_params['limit']);
530
+			if (count($limit_parts) == 1) {
531
+				$limit_parts = array(0, $limit_parts[0]);
532
+			}
533
+		}
534
+		//remove the group by and having parts of the query, as those will
535
+		//make the sql query return an array of values, instead of just a single value
536
+		unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
537
+		$count = $model->count($query_params, null, true);
538
+		$pages = $count / $limit_parts[1];
539
+		$this->_set_response_header('Total', $count, false);
540
+		$this->_set_response_header('PageSize', $limit_parts[1], false);
541
+		$this->_set_response_header('TotalPages', ceil($pages), false);
542
+	}
543
+
544
+
545
+
546
+	/**
547
+	 * Changes database results into REST API entities
548
+	 *
549
+	 * @param \EEM_Base        $model
550
+	 * @param array            $db_row     like results from $wpdb->get_results()
551
+	 * @param \WP_REST_Request $rest_request
552
+	 * @param string           $deprecated no longer used
553
+	 * @return array ready for being converted into json for sending to client
554
+	 */
555
+	public function create_entity_from_wpdb_result($model, $db_row, $rest_request, $deprecated = null)
556
+	{
557
+		if (! $rest_request instanceof \WP_REST_Request) {
558
+			//ok so this was called in the old style, where the 3rd arg was
559
+			//$include, and the 4th arg was $context
560
+			//now setup the request just to avoid fatal errors, although we won't be able
561
+			//to truly make use of it because it's kinda devoid of info
562
+			$rest_request = new \WP_REST_Request();
563
+			$rest_request->set_param('include', $rest_request);
564
+			$rest_request->set_param('caps', $deprecated);
565
+		}
566
+		if ($rest_request->get_param('caps') == null) {
567
+			$rest_request->set_param('caps', \EEM_Base::caps_read);
568
+		}
569
+		$entity_array = $this->_create_bare_entity_from_wpdb_results($model, $db_row);
570
+		$entity_array = $this->_add_extra_fields($model, $db_row, $entity_array);
571
+		$entity_array['_links'] = $this->_get_entity_links($model, $db_row, $entity_array);
572
+		$entity_array['_calculated_fields'] = $this->_get_entity_calculations($model, $db_row, $rest_request);
573
+		$entity_array = apply_filters('FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models',
574
+			$entity_array, $model, $rest_request->get_param('caps'), $rest_request, $this);
575
+		$entity_array = $this->_include_requested_models($model, $rest_request, $entity_array, $db_row);
576
+		$entity_array = apply_filters(
577
+			'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
578
+			$entity_array,
579
+			$model,
580
+			$rest_request->get_param('caps'),
581
+			$rest_request,
582
+			$this
583
+		);
584
+		$result_without_inaccessible_fields = Capabilities::filter_out_inaccessible_entity_fields(
585
+			$entity_array,
586
+			$model,
587
+			$rest_request->get_param('caps'),
588
+			$this->get_model_version_info(),
589
+			$model->get_index_primary_key_string(
590
+				$model->deduce_fields_n_values_from_cols_n_values($db_row)
591
+			)
592
+		);
593
+		$this->_set_debug_info(
594
+			'inaccessible fields',
595
+			array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
596
+		);
597
+		return apply_filters(
598
+			'FHEE__Read__create_entity_from_wpdb_results__entity_return',
599
+			$result_without_inaccessible_fields,
600
+			$model,
601
+			$rest_request->get_param('caps')
602
+		);
603
+	}
604
+
605
+
606
+
607
+	/**
608
+	 * Creates a REST entity array (JSON object we're going to return in the response, but
609
+	 * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
610
+	 * from $wpdb->get_row( $sql, ARRAY_A)
611
+	 *
612
+	 * @param \EEM_Base $model
613
+	 * @param array     $db_row
614
+	 * @return array entity mostly ready for converting to JSON and sending in the response
615
+	 */
616
+	protected function _create_bare_entity_from_wpdb_results(\EEM_Base $model, $db_row)
617
+	{
618
+		$result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
619
+		$result = array_intersect_key($result,
620
+			$this->get_model_version_info()->fields_on_model_in_this_version($model));
621
+		//if this is a CPT, we need to set the global $post to it,
622
+		//otherwise shortcodes etc won't work properly while rendering it
623
+		if ($model instanceof \EEM_CPT_Base) {
624
+			$do_chevy_shuffle = true;
625
+		} else {
626
+			$do_chevy_shuffle = false;
627
+		}
628
+		if ($do_chevy_shuffle) {
629
+			global $post;
630
+			$old_post = $post;
631
+			$post = get_post($result[$model->primary_key_name()]);
632
+			if (! $post instanceof \WP_Post) {
633
+				//well that's weird, because $result is what we JUST fetched from the database
634
+				throw new Rest_Exception(
635
+					'error_fetching_post_from_database_results',
636
+					esc_html__(
637
+						'An item was retrieved from the database but it\'s not a WP_Post like it should be.',
638
+						'event_espresso'
639
+					)
640
+				);
641
+			}
642
+			$model_object_classname = 'EE_' . $model->get_this_model_name();
643
+			$post->{$model_object_classname} = \EE_Registry::instance()->load_class(
644
+				$model_object_classname,
645
+				$result,
646
+				false,
647
+				false
648
+				);
649
+		}
650
+		foreach ($result as $field_name => $raw_field_value) {
651
+			$field_obj = $model->field_settings_for($field_name);
652
+			$field_value = $field_obj->prepare_for_set_from_db($raw_field_value);
653
+			if ($this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_ignored())) {
654
+				unset($result[$field_name]);
655
+			} elseif (
656
+			$this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_rendered_format())
657
+			) {
658
+				$result[$field_name] = array(
659
+					'raw'      => $field_obj->prepare_for_get($field_value),
660
+					'rendered' => $field_obj->prepare_for_pretty_echoing($field_value),
661
+				);
662
+			} elseif (
663
+			$this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_pretty_format())
664
+			) {
665
+				$result[$field_name] = array(
666
+					'raw'    => $field_obj->prepare_for_get($field_value),
667
+					'pretty' => $field_obj->prepare_for_pretty_echoing($field_value),
668
+				);
669
+			} elseif ($field_obj instanceof \EE_Datetime_Field) {
670
+				if ($field_value instanceof \DateTime) {
671
+					$timezone = $field_value->getTimezone();
672
+					$field_value->setTimezone(new \DateTimeZone('UTC'));
673
+					$result[$field_name . '_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
674
+						$field_obj,
675
+						$field_value,
676
+						$this->get_model_version_info()->requested_version()
677
+					);
678
+					$field_value->setTimezone($timezone);
679
+					$result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
680
+						$field_obj,
681
+						$field_value,
682
+						$this->get_model_version_info()->requested_version()
683
+					);
684
+				}
685
+			} else {
686
+				$result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
687
+					$field_obj,
688
+					$field_obj->prepare_for_get($field_value),
689
+					$this->get_model_version_info()->requested_version()
690
+				);
691
+			}
692
+		}
693
+		if ($do_chevy_shuffle) {
694
+			$post = $old_post;
695
+		}
696
+		return $result;
697
+	}
698
+
699
+
700
+
701
+	/**
702
+	 * Adds a few extra fields to the entity response
703
+	 *
704
+	 * @param \EEM_Base $model
705
+	 * @param array     $db_row
706
+	 * @param array     $entity_array
707
+	 * @return array modified entity
708
+	 */
709
+	protected function _add_extra_fields(\EEM_Base $model, $db_row, $entity_array)
710
+	{
711
+		if ($model instanceof \EEM_CPT_Base) {
712
+			$entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
713
+		}
714
+		return $entity_array;
715
+	}
716
+
717
+
718
+
719
+	/**
720
+	 * Gets links we want to add to the response
721
+	 *
722
+	 * @global \WP_REST_Server $wp_rest_server
723
+	 * @param \EEM_Base        $model
724
+	 * @param array            $db_row
725
+	 * @param array            $entity_array
726
+	 * @return array the _links item in the entity
727
+	 */
728
+	protected function _get_entity_links($model, $db_row, $entity_array)
729
+	{
730
+		//add basic links
731
+		$links = array();
732
+		if ($model->has_primary_key_field()) {
733
+			$links['self'] = array(
734
+				array(
735
+					'href' => $this->get_versioned_link_to(
736
+						\EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
737
+						. '/'
738
+						. $entity_array[$model->primary_key_name()]
739
+					),
740
+				),
741
+			);
742
+		}
743
+		$links['collection'] = array(
744
+			array(
745
+				'href' => $this->get_versioned_link_to(
746
+					\EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
747
+				),
748
+			),
749
+		);
750
+		//add links to related models
751
+		if ($model->has_primary_key_field()) {
752
+			foreach ($this->get_model_version_info()->relation_settings($model) as $relation_name => $relation_obj) {
753
+				$related_model_part = Read::get_related_entity_name($relation_name, $relation_obj);
754
+				$links[\EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
755
+					array(
756
+						'href'   => $this->get_versioned_link_to(
757
+							\EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
758
+							. '/'
759
+							. $entity_array[$model->primary_key_name()]
760
+							. '/'
761
+							. $related_model_part
762
+						),
763
+						'single' => $relation_obj instanceof \EE_Belongs_To_Relation ? true : false,
764
+					),
765
+				);
766
+			}
767
+		}
768
+		return $links;
769
+	}
770
+
771
+
772
+
773
+	/**
774
+	 * Adds the included models indicated in the request to the entity provided
775
+	 *
776
+	 * @param \EEM_Base        $model
777
+	 * @param \WP_REST_Request $rest_request
778
+	 * @param array            $entity_array
779
+	 * @param array            $db_row
780
+	 * @return array the modified entity
781
+	 */
782
+	protected function _include_requested_models(
783
+		\EEM_Base $model,
784
+		\WP_REST_Request $rest_request,
785
+		$entity_array,
786
+		$db_row = array()
787
+	) {
788
+		//if $db_row not included, hope the entity array has what we need
789
+		if (! $db_row) {
790
+			$db_row = $entity_array;
791
+		}
792
+		$includes_for_this_model = $this->explode_and_get_items_prefixed_with($rest_request->get_param('include'), '');
793
+		$includes_for_this_model = $this->_remove_model_names_from_array($includes_for_this_model);
794
+		//if they passed in * or didn't specify any includes, return everything
795
+		if (! in_array('*', $includes_for_this_model)
796
+			&& ! empty($includes_for_this_model)
797
+		) {
798
+			if ($model->has_primary_key_field()) {
799
+				//always include the primary key. ya just gotta know that at least
800
+				$includes_for_this_model[] = $model->primary_key_name();
801
+			}
802
+			if ($this->explode_and_get_items_prefixed_with($rest_request->get_param('calculate'), '')) {
803
+				$includes_for_this_model[] = '_calculated_fields';
804
+			}
805
+			$entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
806
+		}
807
+		$relation_settings = $this->get_model_version_info()->relation_settings($model);
808
+		foreach ($relation_settings as $relation_name => $relation_obj) {
809
+			$related_fields_to_include = $this->explode_and_get_items_prefixed_with(
810
+				$rest_request->get_param('include'),
811
+				$relation_name
812
+			);
813
+			$related_fields_to_calculate = $this->explode_and_get_items_prefixed_with(
814
+				$rest_request->get_param('calculate'),
815
+				$relation_name
816
+			);
817
+			//did they specify they wanted to include a related model, or
818
+			//specific fields from a related model?
819
+			//or did they specify to calculate a field from a related model?
820
+			if ($related_fields_to_include || $related_fields_to_calculate) {
821
+				//if so, we should include at least some part of the related model
822
+				$pretend_related_request = new \WP_REST_Request();
823
+				$pretend_related_request->set_query_params(
824
+					array(
825
+						'caps'      => $rest_request->get_param('caps'),
826
+						'include'   => $related_fields_to_include,
827
+						'calculate' => $related_fields_to_calculate,
828
+					)
829
+				);
830
+				$pretend_related_request->add_header('no_rest_headers', true);
831
+				$primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
832
+					$model->get_index_primary_key_string(
833
+						$model->deduce_fields_n_values_from_cols_n_values($db_row)
834
+					)
835
+				);
836
+				$related_results = $this->_get_entities_from_relation(
837
+					$primary_model_query_params,
838
+					$relation_obj,
839
+					$pretend_related_request
840
+				);
841
+				$entity_array[Read::get_related_entity_name($relation_name, $relation_obj)] = $related_results
842
+																							  instanceof
843
+																							  \WP_Error
844
+					? null
845
+					: $related_results;
846
+			}
847
+		}
848
+		return $entity_array;
849
+	}
850
+
851
+
852
+
853
+	/**
854
+	 * Returns a new array with all the names of models removed. Eg
855
+	 * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
856
+	 *
857
+	 * @param array $arr
858
+	 * @return array
859
+	 */
860
+	private function _remove_model_names_from_array($arr)
861
+	{
862
+		return array_diff($arr, array_keys(\EE_Registry::instance()->non_abstract_db_models));
863
+	}
864
+
865
+
866
+
867
+	/**
868
+	 * Gets the calculated fields for the response
869
+	 *
870
+	 * @param \EEM_Base        $model
871
+	 * @param array            $wpdb_row
872
+	 * @param \WP_REST_Request $rest_request
873
+	 * @return \stdClass the _calculations item in the entity
874
+	 */
875
+	protected function _get_entity_calculations($model, $wpdb_row, $rest_request)
876
+	{
877
+		$calculated_fields = $this->explode_and_get_items_prefixed_with(
878
+			$rest_request->get_param('calculate'),
879
+			''
880
+		);
881
+		//note: setting calculate=* doesn't do anything
882
+		$calculated_fields_to_return = new \stdClass();
883
+		foreach ($calculated_fields as $field_to_calculate) {
884
+			try {
885
+				$calculated_fields_to_return->$field_to_calculate = Model_Data_Translator::prepare_field_value_for_json(
886
+					null,
887
+					$this->_fields_calculator->retrieve_calculated_field_value(
888
+						$model,
889
+						$field_to_calculate,
890
+						$wpdb_row,
891
+						$rest_request,
892
+						$this
893
+					),
894
+					$this->get_model_version_info()->requested_version()
895
+				);
896
+			} catch (Rest_Exception $e) {
897
+				//if we don't have permission to read it, just leave it out. but let devs know about the problem
898
+				$this->_set_response_header(
899
+					'Notices-Field-Calculation-Errors['
900
+					. $e->get_string_code()
901
+					. ']['
902
+					. $model->get_this_model_name()
903
+					. ']['
904
+					. $field_to_calculate
905
+					. ']',
906
+					$e->getMessage(),
907
+					true
908
+				);
909
+			}
910
+		}
911
+		return $calculated_fields_to_return;
912
+	}
913
+
914
+
915
+
916
+	/**
917
+	 * Gets the full URL to the resource, taking the requested version into account
918
+	 *
919
+	 * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
920
+	 * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
921
+	 */
922
+	public function get_versioned_link_to($link_part_after_version_and_slash)
923
+	{
924
+		return rest_url(
925
+			\EED_Core_Rest_Api::ee_api_namespace
926
+			. $this->get_model_version_info()->requested_version()
927
+			. '/'
928
+			. $link_part_after_version_and_slash
929
+		);
930
+	}
931
+
932
+
933
+
934
+	/**
935
+	 * Gets the correct lowercase name for the relation in the API according
936
+	 * to the relation's type
937
+	 *
938
+	 * @param string                  $relation_name
939
+	 * @param \EE_Model_Relation_Base $relation_obj
940
+	 * @return string
941
+	 */
942
+	public static function get_related_entity_name($relation_name, $relation_obj)
943
+	{
944
+		if ($relation_obj instanceof \EE_Belongs_To_Relation) {
945
+			return strtolower($relation_name);
946
+		} else {
947
+			return \EEH_Inflector::pluralize_and_lower($relation_name);
948
+		}
949
+	}
950
+
951
+
952
+
953
+	/**
954
+	 * Gets the one model object with the specified id for the specified model
955
+	 *
956
+	 * @param \EEM_Base        $model
957
+	 * @param \WP_REST_Request $request
958
+	 * @return array|\WP_Error
959
+	 */
960
+	public function get_entity_from_model($model, $request)
961
+	{
962
+		$query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
963
+		if ($model instanceof \EEM_Soft_Delete_Base) {
964
+			$query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
965
+		}
966
+		$restricted_query_params = $query_params;
967
+		$restricted_query_params['caps'] = $this->validate_context($request->get_param('caps'));
968
+		$this->_set_debug_info('model query params', $restricted_query_params);
969
+		$model_rows = $model->get_all_wpdb_results($restricted_query_params);
970
+		if (! empty ($model_rows)) {
971
+			return $this->create_entity_from_wpdb_result(
972
+				$model,
973
+				array_shift($model_rows),
974
+				$request);
975
+		} else {
976
+			//ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
977
+			$lowercase_model_name = strtolower($model->get_this_model_name());
978
+			$model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
979
+			if (! empty($model_rows_found_sans_restrictions)) {
980
+				//you got shafted- it existed but we didn't want to tell you!
981
+				return new \WP_Error(
982
+					'rest_user_cannot_read',
983
+					sprintf(
984
+						__('Sorry, you cannot read this %1$s. Missing permissions are: %2$s', 'event_espresso'),
985
+						strtolower($model->get_this_model_name()),
986
+						Capabilities::get_missing_permissions_string(
987
+							$model,
988
+							$this->validate_context($request->get_param('caps')))
989
+					),
990
+					array('status' => 403)
991
+				);
992
+			} else {
993
+				//it's not you. It just doesn't exist
994
+				return new \WP_Error(
995
+					sprintf('rest_%s_invalid_id', $lowercase_model_name),
996
+					sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
997
+					array('status' => 404)
998
+				);
999
+			}
1000
+		}
1001
+	}
1002
+
1003
+
1004
+
1005
+	/**
1006
+	 * If a context is provided which isn't valid, maybe it was added in a future
1007
+	 * version so just treat it as a default read
1008
+	 *
1009
+	 * @param string $context
1010
+	 * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
1011
+	 */
1012
+	public function validate_context($context)
1013
+	{
1014
+		if (! $context) {
1015
+			$context = \EEM_Base::caps_read;
1016
+		}
1017
+		$valid_contexts = \EEM_Base::valid_cap_contexts();
1018
+		if (in_array($context, $valid_contexts)) {
1019
+			return $context;
1020
+		} else {
1021
+			return \EEM_Base::caps_read;
1022
+		}
1023
+	}
1024
+
1025
+
1026
+
1027
+	/**
1028
+	 * Verifies the passed in value is an allowable default where conditions value.
1029
+	 *
1030
+	 * @param $default_query_params
1031
+	 * @return string
1032
+	 */
1033
+	public function validate_default_query_params($default_query_params)
1034
+	{
1035
+		$valid_default_where_conditions_for_api_calls = array(
1036
+			\EEM_Base::default_where_conditions_all,
1037
+			\EEM_Base::default_where_conditions_minimum_all,
1038
+			\EEM_Base::default_where_conditions_minimum_others,
1039
+		);
1040
+		if (! $default_query_params) {
1041
+			$default_query_params = \EEM_Base::default_where_conditions_all;
1042
+		}
1043
+		if (
1044
+		in_array(
1045
+			$default_query_params,
1046
+			$valid_default_where_conditions_for_api_calls,
1047
+			true
1048
+		)
1049
+		) {
1050
+			return $default_query_params;
1051
+		} else {
1052
+			return \EEM_Base::default_where_conditions_all;
1053
+		}
1054
+	}
1055
+
1056
+
1057
+
1058
+	/**
1059
+	 * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
1060
+	 * Note: right now the query parameter keys for fields (and related fields)
1061
+	 * can be left as-is, but it's quite possible this will change someday.
1062
+	 * Also, this method's contents might be candidate for moving to Model_Data_Translator
1063
+	 *
1064
+	 * @param \EEM_Base $model
1065
+	 * @param array     $query_parameters from $_GET parameter @see Read:handle_request_get_all
1066
+	 * @return array like what EEM_Base::get_all() expects or FALSE to indicate
1067
+	 *                                    that absolutely no results should be returned
1068
+	 * @throws \EE_Error
1069
+	 */
1070
+	public function create_model_query_params($model, $query_parameters)
1071
+	{
1072
+		$model_query_params = array();
1073
+		if (isset($query_parameters['where'])) {
1074
+			$model_query_params[0] = Model_Data_Translator::prepare_conditions_query_params_for_models(
1075
+				$query_parameters['where'],
1076
+				$model,
1077
+				$this->get_model_version_info()->requested_version()
1078
+			);
1079
+		}
1080
+		if (isset($query_parameters['order_by'])) {
1081
+			$order_by = $query_parameters['order_by'];
1082
+		} elseif (isset($query_parameters['orderby'])) {
1083
+			$order_by = $query_parameters['orderby'];
1084
+		} else {
1085
+			$order_by = null;
1086
+		}
1087
+		if ($order_by !== null) {
1088
+			if (is_array($order_by)) {
1089
+				$order_by = Model_Data_Translator::prepare_field_names_in_array_keys_from_json($order_by);
1090
+			} else {
1091
+				//it's a single item
1092
+				$order_by = Model_Data_Translator::prepare_field_name_from_json($order_by);
1093
+			}
1094
+			$model_query_params['order_by'] = $order_by;
1095
+		}
1096
+		if (isset($query_parameters['group_by'])) {
1097
+			$group_by = $query_parameters['group_by'];
1098
+		} elseif (isset($query_parameters['groupby'])) {
1099
+			$group_by = $query_parameters['groupby'];
1100
+		} else {
1101
+			$group_by = array_keys($model->get_combined_primary_key_fields());
1102
+		}
1103
+		//make sure they're all real names
1104
+		if (is_array($group_by)) {
1105
+			$group_by = Model_Data_Translator::prepare_field_names_from_json($group_by);
1106
+		}
1107
+		if ($group_by !== null) {
1108
+			$model_query_params['group_by'] = $group_by;
1109
+		}
1110
+		if (isset($query_parameters['having'])) {
1111
+			$model_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_models(
1112
+				$query_parameters['having'],
1113
+				$model,
1114
+				$this->get_model_version_info()->requested_version()
1115
+			);
1116
+		}
1117
+		if (isset($query_parameters['order'])) {
1118
+			$model_query_params['order'] = $query_parameters['order'];
1119
+		}
1120
+		if (isset($query_parameters['mine'])) {
1121
+			$model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
1122
+		}
1123
+		if (isset($query_parameters['limit'])) {
1124
+			//limit should be either a string like '23' or '23,43', or an array with two items in it
1125
+			if (! is_array($query_parameters['limit'])) {
1126
+				$limit_array = explode(',', (string)$query_parameters['limit']);
1127
+			} else {
1128
+				$limit_array = $query_parameters['limit'];
1129
+			}
1130
+			$sanitized_limit = array();
1131
+			foreach ($limit_array as $key => $limit_part) {
1132
+				if ($this->_debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1133
+					throw new \EE_Error(
1134
+						sprintf(
1135
+							__('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.',
1136
+								'event_espresso'),
1137
+							wp_json_encode($query_parameters['limit'])
1138
+						)
1139
+					);
1140
+				}
1141
+				$sanitized_limit[] = (int)$limit_part;
1142
+			}
1143
+			$model_query_params['limit'] = implode(',', $sanitized_limit);
1144
+		} else {
1145
+			$model_query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
1146
+		}
1147
+		if (isset($query_parameters['caps'])) {
1148
+			$model_query_params['caps'] = $this->validate_context($query_parameters['caps']);
1149
+		} else {
1150
+			$model_query_params['caps'] = \EEM_Base::caps_read;
1151
+		}
1152
+		if (isset($query_parameters['default_where_conditions'])) {
1153
+			$model_query_params['default_where_conditions'] = $this->validate_default_query_params($query_parameters['default_where_conditions']);
1154
+		}
1155
+		return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
1156
+	}
1157
+
1158
+
1159
+
1160
+	/**
1161
+	 * Changes the REST-style query params for use in the models
1162
+	 *
1163
+	 * @deprecated
1164
+	 * @param \EEM_Base $model
1165
+	 * @param array     $query_params sub-array from @see EEM_Base::get_all()
1166
+	 * @return array
1167
+	 */
1168
+	public function prepare_rest_query_params_key_for_models($model, $query_params)
1169
+	{
1170
+		$model_ready_query_params = array();
1171
+		foreach ($query_params as $key => $value) {
1172
+			if (is_array($value)) {
1173
+				$model_ready_query_params[$key] = $this->prepare_rest_query_params_key_for_models($model, $value);
1174
+			} else {
1175
+				$model_ready_query_params[$key] = $value;
1176
+			}
1177
+		}
1178
+		return $model_ready_query_params;
1179
+	}
1180
+
1181
+
1182
+
1183
+	/**
1184
+	 * @deprecated
1185
+	 * @param $model
1186
+	 * @param $query_params
1187
+	 * @return array
1188
+	 */
1189
+	public function prepare_rest_query_params_values_for_models($model, $query_params)
1190
+	{
1191
+		$model_ready_query_params = array();
1192
+		foreach ($query_params as $key => $value) {
1193
+			if (is_array($value)) {
1194
+				$model_ready_query_params[$key] = $this->prepare_rest_query_params_values_for_models($model, $value);
1195
+			} else {
1196
+				$model_ready_query_params[$key] = $value;
1197
+			}
1198
+		}
1199
+		return $model_ready_query_params;
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * Explodes the string on commas, and only returns items with $prefix followed by a period.
1206
+	 * If no prefix is specified, returns items with no period.
1207
+	 *
1208
+	 * @param string|array $string_to_explode eg "jibba,jabba, blah, blaabla" or array('jibba', 'jabba' )
1209
+	 * @param string       $prefix            "Event" or "foobar"
1210
+	 * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1211
+	 *                                        we only return strings starting with that and a period; if no prefix was
1212
+	 *                                        specified we return all items containing NO periods
1213
+	 */
1214
+	public function explode_and_get_items_prefixed_with($string_to_explode, $prefix)
1215
+	{
1216
+		if (is_string($string_to_explode)) {
1217
+			$exploded_contents = explode(',', $string_to_explode);
1218
+		} else if (is_array($string_to_explode)) {
1219
+			$exploded_contents = $string_to_explode;
1220
+		} else {
1221
+			$exploded_contents = array();
1222
+		}
1223
+		//if the string was empty, we want an empty array
1224
+		$exploded_contents = array_filter($exploded_contents);
1225
+		$contents_with_prefix = array();
1226
+		foreach ($exploded_contents as $item) {
1227
+			$item = trim($item);
1228
+			//if no prefix was provided, so we look for items with no "." in them
1229
+			if (! $prefix) {
1230
+				//does this item have a period?
1231
+				if (strpos($item, '.') === false) {
1232
+					//if not, then its what we're looking for
1233
+					$contents_with_prefix[] = $item;
1234
+				}
1235
+			} else if (strpos($item, $prefix . '.') === 0) {
1236
+				//this item has the prefix and a period, grab it
1237
+				$contents_with_prefix[] = substr(
1238
+					$item,
1239
+					strpos($item, $prefix . '.') + strlen($prefix . '.')
1240
+				);
1241
+			} else if ($item === $prefix) {
1242
+				//this item is JUST the prefix
1243
+				//so let's grab everything after, which is a blank string
1244
+				$contents_with_prefix[] = '';
1245
+			}
1246
+		}
1247
+		return $contents_with_prefix;
1248
+	}
1249
+
1250
+
1251
+
1252
+	/**
1253
+	 * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1254
+	 * Deprecated because its return values were really quite confusing- sometimes it returned
1255
+	 * an empty array (when the include string was blank or '*') or sometimes it returned
1256
+	 * array('*') (when you provided a model and a model of that kind was found).
1257
+	 * Parses the $include_string so we fetch all the field names relating to THIS model
1258
+	 * (ie have NO period in them), or for the provided model (ie start with the model
1259
+	 * name and then a period).
1260
+	 * @param string $include_string @see Read:handle_request_get_all
1261
+	 * @param string $model_name
1262
+	 * @return array of fields for this model. If $model_name is provided, then
1263
+	 *                               the fields for that model, with the model's name removed from each.
1264
+	 *                               If $include_string was blank or '*' returns an empty array
1265
+	 */
1266
+	public function extract_includes_for_this_model($include_string, $model_name = null)
1267
+	{
1268
+		if (is_array($include_string)) {
1269
+			$include_string = implode(',', $include_string);
1270
+		}
1271
+		if ($include_string === '*' || $include_string === '') {
1272
+			return array();
1273
+		}
1274
+		$includes = explode(',', $include_string);
1275
+		$extracted_fields_to_include = array();
1276
+		if ($model_name) {
1277
+			foreach ($includes as $field_to_include) {
1278
+				$field_to_include = trim($field_to_include);
1279
+				if (strpos($field_to_include, $model_name . '.') === 0) {
1280
+					//found the model name at the exact start
1281
+					$field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1282
+					$extracted_fields_to_include[] = $field_sans_model_name;
1283
+				} elseif ($field_to_include == $model_name) {
1284
+					$extracted_fields_to_include[] = '*';
1285
+				}
1286
+			}
1287
+		} else {
1288
+			//look for ones with no period
1289
+			foreach ($includes as $field_to_include) {
1290
+				$field_to_include = trim($field_to_include);
1291
+				if (
1292
+					strpos($field_to_include, '.') === false
1293
+					&& ! $this->get_model_version_info()->is_model_name_in_this_version($field_to_include)
1294
+				) {
1295
+					$extracted_fields_to_include[] = $field_to_include;
1296
+				}
1297
+			}
1298
+		}
1299
+		return $extracted_fields_to_include;
1300
+	}
1301 1301
 }
1302 1302
 
1303 1303
 
Please login to merge, or discard this patch.
Spacing   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@  discard block
 block discarded – undo
8 8
 use EventEspresso\core\entities\models\JsonModelSchema;
9 9
 use EE_Datetime_Field;
10 10
 
11
-if (! defined('EVENT_ESPRESSO_VERSION')) {
11
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
12 12
     exit('No direct script access allowed');
13 13
 }
14 14
 
@@ -57,12 +57,12 @@  discard block
 block discarded – undo
57 57
         try {
58 58
             $matches = $controller->parse_route(
59 59
                 $request->get_route(),
60
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)~',
60
+                '~'.\EED_Core_Rest_Api::ee_api_namespace_for_regex.'(.*)~',
61 61
                 array('version', 'model')
62 62
             );
63 63
             $controller->set_requested_version($matches['version']);
64 64
             $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
65
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
65
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
66 66
                 return $controller->send_response(
67 67
                     new \WP_Error(
68 68
                         'endpoint_parsing_error',
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
         $controller = new Read();
100 100
         try {
101 101
             $controller->set_requested_version($version);
102
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name)) {
102
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($model_name)) {
103 103
                 return array();
104 104
             }
105 105
             //get the model for this version
@@ -193,9 +193,9 @@  discard block
 block discarded – undo
193 193
     protected function _maybe_add_extra_fields_to_schema($field_name, \EE_Model_Field_Base $field, array $schema)
194 194
     {
195 195
         if ($field instanceof EE_Datetime_Field) {
196
-            $schema['properties'][$field_name . '_gmt'] = $field->getSchema();
196
+            $schema['properties'][$field_name.'_gmt'] = $field->getSchema();
197 197
             //modify the description
198
-            $schema['properties'][$field_name . '_gmt']['description'] = sprintf(
198
+            $schema['properties'][$field_name.'_gmt']['description'] = sprintf(
199 199
                 esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
200 200
                 $field->get_nicename()
201 201
             );
@@ -236,11 +236,11 @@  discard block
 block discarded – undo
236 236
         try {
237 237
             $matches = $controller->parse_route(
238 238
                 $request->get_route(),
239
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)~',
239
+                '~'.\EED_Core_Rest_Api::ee_api_namespace_for_regex.'(.*)/(.*)~',
240 240
                 array('version', 'model', 'id'));
241 241
             $controller->set_requested_version($matches['version']);
242 242
             $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
243
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
243
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
244 244
                 return $controller->send_response(
245 245
                     new \WP_Error(
246 246
                         'endpoint_parsing_error',
@@ -278,12 +278,12 @@  discard block
 block discarded – undo
278 278
         try {
279 279
             $matches = $controller->parse_route(
280 280
                 $request->get_route(),
281
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)/(.*)~',
281
+                '~'.\EED_Core_Rest_Api::ee_api_namespace_for_regex.'(.*)/(.*)/(.*)~',
282 282
                 array('version', 'model', 'id', 'related_model')
283 283
             );
284 284
             $controller->set_requested_version($matches['version']);
285 285
             $main_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
286
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
286
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
287 287
                 return $controller->send_response(
288 288
                     new \WP_Error(
289 289
                         'endpoint_parsing_error',
@@ -298,11 +298,11 @@  discard block
 block discarded – undo
298 298
             $main_model = $controller->get_model_version_info()->load_model($main_model_name_singular);
299 299
             //assume the related model name is plural and try to find the model's name
300 300
             $related_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['related_model']);
301
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
301
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
302 302
                 //so the word didn't singularize well. Maybe that's just because it's a singular word?
303 303
                 $related_model_name_singular = \EEH_Inflector::humanize($matches['related_model']);
304 304
             }
305
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
305
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
306 306
                 return $controller->send_response(
307 307
                     new \WP_Error(
308 308
                         'endpoint_parsing_error',
@@ -338,7 +338,7 @@  discard block
 block discarded – undo
338 338
     public function get_entities_from_model($model, $request)
339 339
     {
340 340
         $query_params = $this->create_model_query_params($model, $request->get_params());
341
-        if (! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
341
+        if ( ! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
342 342
             $model_name_plural = \EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
343 343
             return new \WP_Error(
344 344
                 sprintf('rest_%s_cannot_list', $model_name_plural),
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
                 array('status' => 403)
351 351
             );
352 352
         }
353
-        if (! $request->get_header('no_rest_headers')) {
353
+        if ( ! $request->get_header('no_rest_headers')) {
354 354
             $this->_set_headers_from_query_params($model, $query_params);
355 355
         }
356 356
         /** @type array $results */
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
         $context = $this->validate_context($request->get_param('caps'));
381 381
         $model = $relation->get_this_model();
382 382
         $related_model = $relation->get_other_model();
383
-        if (! isset($primary_model_query_params[0])) {
383
+        if ( ! isset($primary_model_query_params[0])) {
384 384
             $primary_model_query_params[0] = array();
385 385
         }
386 386
         //check if they can access the 1st model object
@@ -431,7 +431,7 @@  discard block
 block discarded – undo
431 431
         }
432 432
         $query_params['default_where_conditions'] = 'none';
433 433
         $query_params['caps'] = $context;
434
-        if (! $request->get_header('no_rest_headers')) {
434
+        if ( ! $request->get_header('no_rest_headers')) {
435 435
             $this->_set_headers_from_query_params($relation->get_other_model(), $query_params);
436 436
         }
437 437
         /** @type array $results */
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
      */
484 484
     public function get_entities_from_relation($id, $relation, $request)
485 485
     {
486
-        if (! $relation->get_this_model()->has_primary_key_field()) {
486
+        if ( ! $relation->get_this_model()->has_primary_key_field()) {
487 487
             throw new \EE_Error(
488 488
                 sprintf(
489 489
                     __('Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
@@ -520,7 +520,7 @@  discard block
 block discarded – undo
520 520
         $this->_set_debug_info('missing caps',
521 521
             Capabilities::get_missing_permissions_string($model, $query_params['caps']));
522 522
         //normally the limit to a 2-part array, where the 2nd item is the limit
523
-        if (! isset($query_params['limit'])) {
523
+        if ( ! isset($query_params['limit'])) {
524 524
             $query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
525 525
         }
526 526
         if (is_array($query_params['limit'])) {
@@ -554,7 +554,7 @@  discard block
 block discarded – undo
554 554
      */
555 555
     public function create_entity_from_wpdb_result($model, $db_row, $rest_request, $deprecated = null)
556 556
     {
557
-        if (! $rest_request instanceof \WP_REST_Request) {
557
+        if ( ! $rest_request instanceof \WP_REST_Request) {
558 558
             //ok so this was called in the old style, where the 3rd arg was
559 559
             //$include, and the 4th arg was $context
560 560
             //now setup the request just to avoid fatal errors, although we won't be able
@@ -629,7 +629,7 @@  discard block
 block discarded – undo
629 629
             global $post;
630 630
             $old_post = $post;
631 631
             $post = get_post($result[$model->primary_key_name()]);
632
-            if (! $post instanceof \WP_Post) {
632
+            if ( ! $post instanceof \WP_Post) {
633 633
                 //well that's weird, because $result is what we JUST fetched from the database
634 634
                 throw new Rest_Exception(
635 635
                     'error_fetching_post_from_database_results',
@@ -639,7 +639,7 @@  discard block
 block discarded – undo
639 639
                     )
640 640
                 );
641 641
             }
642
-            $model_object_classname = 'EE_' . $model->get_this_model_name();
642
+            $model_object_classname = 'EE_'.$model->get_this_model_name();
643 643
             $post->{$model_object_classname} = \EE_Registry::instance()->load_class(
644 644
                 $model_object_classname,
645 645
                 $result,
@@ -670,7 +670,7 @@  discard block
 block discarded – undo
670 670
                 if ($field_value instanceof \DateTime) {
671 671
                     $timezone = $field_value->getTimezone();
672 672
                     $field_value->setTimezone(new \DateTimeZone('UTC'));
673
-                    $result[$field_name . '_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
673
+                    $result[$field_name.'_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
674 674
                         $field_obj,
675 675
                         $field_value,
676 676
                         $this->get_model_version_info()->requested_version()
@@ -751,7 +751,7 @@  discard block
 block discarded – undo
751 751
         if ($model->has_primary_key_field()) {
752 752
             foreach ($this->get_model_version_info()->relation_settings($model) as $relation_name => $relation_obj) {
753 753
                 $related_model_part = Read::get_related_entity_name($relation_name, $relation_obj);
754
-                $links[\EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
754
+                $links[\EED_Core_Rest_Api::ee_api_link_namespace.$related_model_part] = array(
755 755
                     array(
756 756
                         'href'   => $this->get_versioned_link_to(
757 757
                             \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
@@ -786,13 +786,13 @@  discard block
 block discarded – undo
786 786
         $db_row = array()
787 787
     ) {
788 788
         //if $db_row not included, hope the entity array has what we need
789
-        if (! $db_row) {
789
+        if ( ! $db_row) {
790 790
             $db_row = $entity_array;
791 791
         }
792 792
         $includes_for_this_model = $this->explode_and_get_items_prefixed_with($rest_request->get_param('include'), '');
793 793
         $includes_for_this_model = $this->_remove_model_names_from_array($includes_for_this_model);
794 794
         //if they passed in * or didn't specify any includes, return everything
795
-        if (! in_array('*', $includes_for_this_model)
795
+        if ( ! in_array('*', $includes_for_this_model)
796 796
             && ! empty($includes_for_this_model)
797 797
         ) {
798 798
             if ($model->has_primary_key_field()) {
@@ -967,7 +967,7 @@  discard block
 block discarded – undo
967 967
         $restricted_query_params['caps'] = $this->validate_context($request->get_param('caps'));
968 968
         $this->_set_debug_info('model query params', $restricted_query_params);
969 969
         $model_rows = $model->get_all_wpdb_results($restricted_query_params);
970
-        if (! empty ($model_rows)) {
970
+        if ( ! empty ($model_rows)) {
971 971
             return $this->create_entity_from_wpdb_result(
972 972
                 $model,
973 973
                 array_shift($model_rows),
@@ -976,7 +976,7 @@  discard block
 block discarded – undo
976 976
             //ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
977 977
             $lowercase_model_name = strtolower($model->get_this_model_name());
978 978
             $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
979
-            if (! empty($model_rows_found_sans_restrictions)) {
979
+            if ( ! empty($model_rows_found_sans_restrictions)) {
980 980
                 //you got shafted- it existed but we didn't want to tell you!
981 981
                 return new \WP_Error(
982 982
                     'rest_user_cannot_read',
@@ -1011,7 +1011,7 @@  discard block
 block discarded – undo
1011 1011
      */
1012 1012
     public function validate_context($context)
1013 1013
     {
1014
-        if (! $context) {
1014
+        if ( ! $context) {
1015 1015
             $context = \EEM_Base::caps_read;
1016 1016
         }
1017 1017
         $valid_contexts = \EEM_Base::valid_cap_contexts();
@@ -1037,7 +1037,7 @@  discard block
 block discarded – undo
1037 1037
             \EEM_Base::default_where_conditions_minimum_all,
1038 1038
             \EEM_Base::default_where_conditions_minimum_others,
1039 1039
         );
1040
-        if (! $default_query_params) {
1040
+        if ( ! $default_query_params) {
1041 1041
             $default_query_params = \EEM_Base::default_where_conditions_all;
1042 1042
         }
1043 1043
         if (
@@ -1122,14 +1122,14 @@  discard block
 block discarded – undo
1122 1122
         }
1123 1123
         if (isset($query_parameters['limit'])) {
1124 1124
             //limit should be either a string like '23' or '23,43', or an array with two items in it
1125
-            if (! is_array($query_parameters['limit'])) {
1126
-                $limit_array = explode(',', (string)$query_parameters['limit']);
1125
+            if ( ! is_array($query_parameters['limit'])) {
1126
+                $limit_array = explode(',', (string) $query_parameters['limit']);
1127 1127
             } else {
1128 1128
                 $limit_array = $query_parameters['limit'];
1129 1129
             }
1130 1130
             $sanitized_limit = array();
1131 1131
             foreach ($limit_array as $key => $limit_part) {
1132
-                if ($this->_debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1132
+                if ($this->_debug_mode && ( ! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1133 1133
                     throw new \EE_Error(
1134 1134
                         sprintf(
1135 1135
                             __('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.',
@@ -1138,7 +1138,7 @@  discard block
 block discarded – undo
1138 1138
                         )
1139 1139
                     );
1140 1140
                 }
1141
-                $sanitized_limit[] = (int)$limit_part;
1141
+                $sanitized_limit[] = (int) $limit_part;
1142 1142
             }
1143 1143
             $model_query_params['limit'] = implode(',', $sanitized_limit);
1144 1144
         } else {
@@ -1226,17 +1226,17 @@  discard block
 block discarded – undo
1226 1226
         foreach ($exploded_contents as $item) {
1227 1227
             $item = trim($item);
1228 1228
             //if no prefix was provided, so we look for items with no "." in them
1229
-            if (! $prefix) {
1229
+            if ( ! $prefix) {
1230 1230
                 //does this item have a period?
1231 1231
                 if (strpos($item, '.') === false) {
1232 1232
                     //if not, then its what we're looking for
1233 1233
                     $contents_with_prefix[] = $item;
1234 1234
                 }
1235
-            } else if (strpos($item, $prefix . '.') === 0) {
1235
+            } else if (strpos($item, $prefix.'.') === 0) {
1236 1236
                 //this item has the prefix and a period, grab it
1237 1237
                 $contents_with_prefix[] = substr(
1238 1238
                     $item,
1239
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1239
+                    strpos($item, $prefix.'.') + strlen($prefix.'.')
1240 1240
                 );
1241 1241
             } else if ($item === $prefix) {
1242 1242
                 //this item is JUST the prefix
@@ -1276,9 +1276,9 @@  discard block
 block discarded – undo
1276 1276
         if ($model_name) {
1277 1277
             foreach ($includes as $field_to_include) {
1278 1278
                 $field_to_include = trim($field_to_include);
1279
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1279
+                if (strpos($field_to_include, $model_name.'.') === 0) {
1280 1280
                     //found the model name at the exact start
1281
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1281
+                    $field_sans_model_name = str_replace($model_name.'.', '', $field_to_include);
1282 1282
                     $extracted_fields_to_include[] = $field_sans_model_name;
1283 1283
                 } elseif ($field_to_include == $model_name) {
1284 1284
                     $extracted_fields_to_include[] = '*';
Please login to merge, or discard this patch.
core/services/shortcodes/EspressoShortcode.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
             }
85 85
         }
86 86
         return $this->shortcodeContent(
87
-            $this->sanitizeAttributes((array)$attributes)
87
+            $this->sanitizeAttributes((array) $attributes)
88 88
         );
89 89
     }
90 90
 
@@ -112,8 +112,8 @@  discard block
 block discarded – undo
112 112
             // serialized attributes
113 113
             wp_json_encode($attributes),
114 114
             // Closure for generating content if cache is expired
115
-            function () use ($shortcode, $attributes) {
116
-                if($shortcode->initialized() === false){
115
+            function() use ($shortcode, $attributes) {
116
+                if ($shortcode->initialized() === false) {
117 117
                     $shortcode->initializeShortcode();
118 118
                 }
119 119
                 return $shortcode->processShortcode($attributes);
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
      * Returns whether or not this shortcode has been initialized
248 248
      * @return boolean
249 249
      */
250
-    public function initialized(){
250
+    public function initialized() {
251 251
         return $this->initialized;
252 252
     }
253 253
 
Please login to merge, or discard this patch.
Indentation   +224 added lines, -224 removed lines patch added patch discarded remove patch
@@ -23,230 +23,230 @@
 block discarded – undo
23 23
 abstract class EspressoShortcode implements ShortcodeInterface
24 24
 {
25 25
 
26
-    /**
27
-     * transient prefix
28
-     *
29
-     * @type string
30
-     */
31
-    const CACHE_TRANSIENT_PREFIX = 'ee_sc_';
32
-
33
-    /**
34
-     * @var PostRelatedCacheManager $cache_manager
35
-     */
36
-    private $cache_manager;
37
-
38
-    /**
39
-     * true if ShortcodeInterface::initializeShortcode() has been called
40
-     * if false, then that will get called before processing
41
-     *
42
-     * @var boolean $initialized
43
-     */
44
-    private $initialized = false;
45
-
46
-
47
-
48
-    /**
49
-     * EspressoShortcode constructor
50
-     *
51
-     * @param PostRelatedCacheManager $cache_manager
52
-     */
53
-    public function __construct(PostRelatedCacheManager $cache_manager)
54
-    {
55
-        $this->cache_manager = $cache_manager;
56
-    }
57
-
58
-
59
-
60
-    /**
61
-     * @return void
62
-     */
63
-    public function shortcodeHasBeenInitialized()
64
-    {
65
-        $this->initialized = true;
66
-    }
67
-
68
-
69
-
70
-    /**
71
-     * enqueues scripts then processes the shortcode
72
-     *
73
-     * @param array $attributes
74
-     * @return string
75
-     * @throws EE_Error
76
-     */
77
-    final public function processShortcodeCallback($attributes = array())
78
-    {
79
-        if ($this instanceof EnqueueAssetsInterface) {
80
-            if (is_admin()) {
81
-                $this->enqueueAdminScripts();
82
-            } else {
83
-                $this->enqueueScripts();
84
-            }
85
-        }
86
-        return $this->shortcodeContent(
87
-            $this->sanitizeAttributes((array)$attributes)
88
-        );
89
-    }
90
-
91
-
92
-
93
-    /**
94
-     * If shortcode caching is enabled for the shortcode,
95
-     * and cached results exist, then that will be returned
96
-     * else new content will be generated.
97
-     * If caching is enabled, then the new content will be cached for later.
98
-     *
99
-     * @param array $attributes
100
-     * @return mixed|string
101
-     * @throws EE_Error
102
-     */
103
-    private function shortcodeContent(array $attributes)
104
-    {
105
-        $shortcode = $this;
106
-        $post_ID = $this->currentPostID();
107
-        // something like "SC_EVENTS-123"
108
-        $cache_ID = $this->shortcodeCacheID($post_ID);
109
-        $this->cache_manager->clearPostRelatedCacheOnUpdate($post_ID, $cache_ID);
110
-        return $this->cache_manager->get(
111
-            $cache_ID,
112
-            // serialized attributes
113
-            wp_json_encode($attributes),
114
-            // Closure for generating content if cache is expired
115
-            function () use ($shortcode, $attributes) {
116
-                if($shortcode->initialized() === false){
117
-                    $shortcode->initializeShortcode();
118
-                }
119
-                return $shortcode->processShortcode($attributes);
120
-            },
121
-            // filterable cache expiration set by each shortcode
122
-            apply_filters(
123
-                'FHEE__EventEspresso_core_services_shortcodes_EspressoShortcode__shortcodeContent__cache_expiration',
124
-                $this->cacheExpiration(),
125
-                $this->getTag(),
126
-                $this
127
-            )
128
-        );
129
-    }
130
-
131
-
132
-
133
-    /**
134
-     * @return int
135
-     * @throws EE_Error
136
-     */
137
-    private function currentPostID()
138
-    {
139
-        // try to get EE_Event any way we can
140
-        $event = EEH_Event_View::get_event();
141
-        // then get some kind of ID
142
-        if ($event instanceof EE_Event) {
143
-            return $event->ID();
144
-        }
145
-        global $post;
146
-        if ($post instanceof WP_Post) {
147
-            return $post->ID;
148
-        }
149
-        return 0;
150
-    }
151
-
152
-
153
-
154
-    /**
155
-     * @param int $post_ID
156
-     * @return string
157
-     * @throws EE_Error
158
-     */
159
-    private function shortcodeCacheID($post_ID)
160
-    {
161
-        $tag = str_replace('ESPRESSO_', '', $this->getTag());
162
-        return "SC_{$tag}-{$post_ID}";
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * array for defining custom attribute sanitization callbacks,
169
-     * where keys match keys in your attributes array,
170
-     * and values represent the sanitization function you wish to be applied to that attribute.
171
-     * So for example, if you had an integer attribute named "event_id"
172
-     * that you wanted to be sanitized using absint(),
173
-     * then you would return the following:
174
-     *      array('event_id' => 'absint')
175
-     * Entering 'skip_sanitization' for the callback value
176
-     * means that no sanitization will be applied
177
-     * on the assumption that the attribute
178
-     * will be sanitized at some point... right?
179
-     * You wouldn't pass around unsanitized attributes would you?
180
-     * That would be very Tom Foolery of you!!!
181
-     *
182
-     * @return array
183
-     */
184
-    protected function customAttributeSanitizationMap()
185
-    {
186
-        return array();
187
-    }
188
-
189
-
190
-
191
-    /**
192
-     * Performs basic sanitization on shortcode attributes
193
-     * Since incoming attributes from the shortcode usage in the WP editor will all be strings,
194
-     * most attributes will by default be sanitized using the sanitize_text_field() function.
195
-     * This can be overridden using the customAttributeSanitizationMap() method (see above),
196
-     * all other attributes would be sanitized using the defaults in the switch statement below
197
-     *
198
-     * @param array $attributes
199
-     * @return array
200
-     */
201
-    private function sanitizeAttributes(array $attributes)
202
-    {
203
-        $custom_sanitization = $this->customAttributeSanitizationMap();
204
-        foreach ($attributes as $key => $value) {
205
-            // is a custom sanitization callback specified ?
206
-            if (isset($custom_sanitization[$key])) {
207
-                $callback = $custom_sanitization[$key];
208
-                if ($callback === 'skip_sanitization') {
209
-                    $attributes[$key] = $value;
210
-                    continue;
211
-                }
212
-                if (function_exists($callback)) {
213
-                    $attributes[$key] = $callback($value);
214
-                    continue;
215
-                }
216
-            }
217
-            switch (true) {
218
-                case $value === null :
219
-                case is_int($value) :
220
-                case is_float($value) :
221
-                    // typical booleans
222
-                case in_array($value, array(true, 'true', '1', 'on', 'yes', false, 'false', '0', 'off', 'no'), true) :
223
-                    $attributes[$key] = $value;
224
-                    break;
225
-                case is_string($value) :
226
-                    $attributes[$key] = sanitize_text_field($value);
227
-                    break;
228
-                case is_array($value) :
229
-                    $attributes[$key] = $this->sanitizeAttributes($value);
230
-                    break;
231
-                default :
232
-                    // only remaining data types are Object and Resource
233
-                    // which are not allowed as shortcode attributes
234
-                    $attributes[$key] = null;
235
-                    break;
236
-            }
237
-        }
238
-        return $attributes;
239
-    }
240
-
241
-
242
-
243
-    /**
244
-     * Returns whether or not this shortcode has been initialized
245
-     * @return boolean
246
-     */
247
-    public function initialized(){
248
-        return $this->initialized;
249
-    }
26
+	/**
27
+	 * transient prefix
28
+	 *
29
+	 * @type string
30
+	 */
31
+	const CACHE_TRANSIENT_PREFIX = 'ee_sc_';
32
+
33
+	/**
34
+	 * @var PostRelatedCacheManager $cache_manager
35
+	 */
36
+	private $cache_manager;
37
+
38
+	/**
39
+	 * true if ShortcodeInterface::initializeShortcode() has been called
40
+	 * if false, then that will get called before processing
41
+	 *
42
+	 * @var boolean $initialized
43
+	 */
44
+	private $initialized = false;
45
+
46
+
47
+
48
+	/**
49
+	 * EspressoShortcode constructor
50
+	 *
51
+	 * @param PostRelatedCacheManager $cache_manager
52
+	 */
53
+	public function __construct(PostRelatedCacheManager $cache_manager)
54
+	{
55
+		$this->cache_manager = $cache_manager;
56
+	}
57
+
58
+
59
+
60
+	/**
61
+	 * @return void
62
+	 */
63
+	public function shortcodeHasBeenInitialized()
64
+	{
65
+		$this->initialized = true;
66
+	}
67
+
68
+
69
+
70
+	/**
71
+	 * enqueues scripts then processes the shortcode
72
+	 *
73
+	 * @param array $attributes
74
+	 * @return string
75
+	 * @throws EE_Error
76
+	 */
77
+	final public function processShortcodeCallback($attributes = array())
78
+	{
79
+		if ($this instanceof EnqueueAssetsInterface) {
80
+			if (is_admin()) {
81
+				$this->enqueueAdminScripts();
82
+			} else {
83
+				$this->enqueueScripts();
84
+			}
85
+		}
86
+		return $this->shortcodeContent(
87
+			$this->sanitizeAttributes((array)$attributes)
88
+		);
89
+	}
90
+
91
+
92
+
93
+	/**
94
+	 * If shortcode caching is enabled for the shortcode,
95
+	 * and cached results exist, then that will be returned
96
+	 * else new content will be generated.
97
+	 * If caching is enabled, then the new content will be cached for later.
98
+	 *
99
+	 * @param array $attributes
100
+	 * @return mixed|string
101
+	 * @throws EE_Error
102
+	 */
103
+	private function shortcodeContent(array $attributes)
104
+	{
105
+		$shortcode = $this;
106
+		$post_ID = $this->currentPostID();
107
+		// something like "SC_EVENTS-123"
108
+		$cache_ID = $this->shortcodeCacheID($post_ID);
109
+		$this->cache_manager->clearPostRelatedCacheOnUpdate($post_ID, $cache_ID);
110
+		return $this->cache_manager->get(
111
+			$cache_ID,
112
+			// serialized attributes
113
+			wp_json_encode($attributes),
114
+			// Closure for generating content if cache is expired
115
+			function () use ($shortcode, $attributes) {
116
+				if($shortcode->initialized() === false){
117
+					$shortcode->initializeShortcode();
118
+				}
119
+				return $shortcode->processShortcode($attributes);
120
+			},
121
+			// filterable cache expiration set by each shortcode
122
+			apply_filters(
123
+				'FHEE__EventEspresso_core_services_shortcodes_EspressoShortcode__shortcodeContent__cache_expiration',
124
+				$this->cacheExpiration(),
125
+				$this->getTag(),
126
+				$this
127
+			)
128
+		);
129
+	}
130
+
131
+
132
+
133
+	/**
134
+	 * @return int
135
+	 * @throws EE_Error
136
+	 */
137
+	private function currentPostID()
138
+	{
139
+		// try to get EE_Event any way we can
140
+		$event = EEH_Event_View::get_event();
141
+		// then get some kind of ID
142
+		if ($event instanceof EE_Event) {
143
+			return $event->ID();
144
+		}
145
+		global $post;
146
+		if ($post instanceof WP_Post) {
147
+			return $post->ID;
148
+		}
149
+		return 0;
150
+	}
151
+
152
+
153
+
154
+	/**
155
+	 * @param int $post_ID
156
+	 * @return string
157
+	 * @throws EE_Error
158
+	 */
159
+	private function shortcodeCacheID($post_ID)
160
+	{
161
+		$tag = str_replace('ESPRESSO_', '', $this->getTag());
162
+		return "SC_{$tag}-{$post_ID}";
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * array for defining custom attribute sanitization callbacks,
169
+	 * where keys match keys in your attributes array,
170
+	 * and values represent the sanitization function you wish to be applied to that attribute.
171
+	 * So for example, if you had an integer attribute named "event_id"
172
+	 * that you wanted to be sanitized using absint(),
173
+	 * then you would return the following:
174
+	 *      array('event_id' => 'absint')
175
+	 * Entering 'skip_sanitization' for the callback value
176
+	 * means that no sanitization will be applied
177
+	 * on the assumption that the attribute
178
+	 * will be sanitized at some point... right?
179
+	 * You wouldn't pass around unsanitized attributes would you?
180
+	 * That would be very Tom Foolery of you!!!
181
+	 *
182
+	 * @return array
183
+	 */
184
+	protected function customAttributeSanitizationMap()
185
+	{
186
+		return array();
187
+	}
188
+
189
+
190
+
191
+	/**
192
+	 * Performs basic sanitization on shortcode attributes
193
+	 * Since incoming attributes from the shortcode usage in the WP editor will all be strings,
194
+	 * most attributes will by default be sanitized using the sanitize_text_field() function.
195
+	 * This can be overridden using the customAttributeSanitizationMap() method (see above),
196
+	 * all other attributes would be sanitized using the defaults in the switch statement below
197
+	 *
198
+	 * @param array $attributes
199
+	 * @return array
200
+	 */
201
+	private function sanitizeAttributes(array $attributes)
202
+	{
203
+		$custom_sanitization = $this->customAttributeSanitizationMap();
204
+		foreach ($attributes as $key => $value) {
205
+			// is a custom sanitization callback specified ?
206
+			if (isset($custom_sanitization[$key])) {
207
+				$callback = $custom_sanitization[$key];
208
+				if ($callback === 'skip_sanitization') {
209
+					$attributes[$key] = $value;
210
+					continue;
211
+				}
212
+				if (function_exists($callback)) {
213
+					$attributes[$key] = $callback($value);
214
+					continue;
215
+				}
216
+			}
217
+			switch (true) {
218
+				case $value === null :
219
+				case is_int($value) :
220
+				case is_float($value) :
221
+					// typical booleans
222
+				case in_array($value, array(true, 'true', '1', 'on', 'yes', false, 'false', '0', 'off', 'no'), true) :
223
+					$attributes[$key] = $value;
224
+					break;
225
+				case is_string($value) :
226
+					$attributes[$key] = sanitize_text_field($value);
227
+					break;
228
+				case is_array($value) :
229
+					$attributes[$key] = $this->sanitizeAttributes($value);
230
+					break;
231
+				default :
232
+					// only remaining data types are Object and Resource
233
+					// which are not allowed as shortcode attributes
234
+					$attributes[$key] = null;
235
+					break;
236
+			}
237
+		}
238
+		return $attributes;
239
+	}
240
+
241
+
242
+
243
+	/**
244
+	 * Returns whether or not this shortcode has been initialized
245
+	 * @return boolean
246
+	 */
247
+	public function initialized(){
248
+		return $this->initialized;
249
+	}
250 250
 
251 251
 
252 252
 
Please login to merge, or discard this patch.
core/services/shortcodes/ShortcodeInterface.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -8,52 +8,52 @@
 block discarded – undo
8 8
 interface ShortcodeInterface
9 9
 {
10 10
 
11
-    /**
12
-     * the actual shortcode tag that gets registered with WordPress
13
-     *
14
-     * @return string
15
-     */
16
-    public function getTag();
17
-
18
-    /**
19
-     * the length of time in seconds to cache the results of the processShortcode() method
20
-     * 0 means the processShortcode() results will NOT be cached at all
21
-     *
22
-     * @return int
23
-     */
24
-    public function cacheExpiration();
25
-
26
-    /**
27
-     * a place for adding any initialization code that needs to run prior to wp_header().
28
-     * this may be required for shortcodes that utilize a corresponding module,
29
-     * and need to enqueue assets for that module
30
-     *
31
-     * !!! IMPORTANT !!!
32
-     * After performing any logic within this method required for initialization
33
-     *         $this->shortcodeHasBeenInitialized();
34
-     * should be called to ensure that the shortcode is setup correctly.
35
-     *
36
-     * @return void
37
-     */
38
-    public function initializeShortcode();
39
-
40
-    /**
41
-     * callback that runs when the shortcode is encountered in post content.
42
-     * IMPORTANT !!!
43
-     * remember that shortcode content should be RETURNED and NOT echoed out
44
-     *
45
-     * @param array $attributes
46
-     * @return string
47
-     */
48
-    public function processShortcode($attributes = array());
49
-
50
-
51
-
52
-    /**
53
-     * Returns whether or not this shortcode class has already been initialized
54
-     * @return boolean
55
-     */
56
-    public function initialized();
11
+	/**
12
+	 * the actual shortcode tag that gets registered with WordPress
13
+	 *
14
+	 * @return string
15
+	 */
16
+	public function getTag();
17
+
18
+	/**
19
+	 * the length of time in seconds to cache the results of the processShortcode() method
20
+	 * 0 means the processShortcode() results will NOT be cached at all
21
+	 *
22
+	 * @return int
23
+	 */
24
+	public function cacheExpiration();
25
+
26
+	/**
27
+	 * a place for adding any initialization code that needs to run prior to wp_header().
28
+	 * this may be required for shortcodes that utilize a corresponding module,
29
+	 * and need to enqueue assets for that module
30
+	 *
31
+	 * !!! IMPORTANT !!!
32
+	 * After performing any logic within this method required for initialization
33
+	 *         $this->shortcodeHasBeenInitialized();
34
+	 * should be called to ensure that the shortcode is setup correctly.
35
+	 *
36
+	 * @return void
37
+	 */
38
+	public function initializeShortcode();
39
+
40
+	/**
41
+	 * callback that runs when the shortcode is encountered in post content.
42
+	 * IMPORTANT !!!
43
+	 * remember that shortcode content should be RETURNED and NOT echoed out
44
+	 *
45
+	 * @param array $attributes
46
+	 * @return string
47
+	 */
48
+	public function processShortcode($attributes = array());
49
+
50
+
51
+
52
+	/**
53
+	 * Returns whether or not this shortcode class has already been initialized
54
+	 * @return boolean
55
+	 */
56
+	public function initialized();
57 57
 
58 58
 }
59 59
 // End of file ShortcodeInterface.php
Please login to merge, or discard this patch.
caffeinated/admin/extend/events/Extend_Events_Admin_Page.core.php 1 patch
Indentation   +1260 added lines, -1260 removed lines patch added patch discarded remove patch
@@ -14,1264 +14,1264 @@
 block discarded – undo
14 14
 {
15 15
 
16 16
 
17
-    /**
18
-     * Extend_Events_Admin_Page constructor.
19
-     *
20
-     * @param bool $routing
21
-     */
22
-    public function __construct($routing = true)
23
-    {
24
-        parent::__construct($routing);
25
-        if (! defined('EVENTS_CAF_TEMPLATE_PATH')) {
26
-            define('EVENTS_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'events/templates/');
27
-            define('EVENTS_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'events/assets/');
28
-            define('EVENTS_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'events/assets/');
29
-        }
30
-    }
31
-
32
-
33
-    /**
34
-     * Sets routes.
35
-     */
36
-    protected function _extend_page_config()
37
-    {
38
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'events';
39
-        //is there a evt_id in the request?
40
-        $evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
41
-            ? $this->_req_data['EVT_ID']
42
-            : 0;
43
-        $evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
44
-        //tkt_id?
45
-        $tkt_id             = ! empty($this->_req_data['TKT_ID']) && ! is_array($this->_req_data['TKT_ID'])
46
-            ? $this->_req_data['TKT_ID']
47
-            : 0;
48
-        $new_page_routes    = array(
49
-            'duplicate_event'          => array(
50
-                'func'       => '_duplicate_event',
51
-                'capability' => 'ee_edit_event',
52
-                'obj_id'     => $evt_id,
53
-                'noheader'   => true,
54
-            ),
55
-            'ticket_list_table'        => array(
56
-                'func'       => '_tickets_overview_list_table',
57
-                'capability' => 'ee_read_default_tickets',
58
-            ),
59
-            'trash_ticket'             => array(
60
-                'func'       => '_trash_or_restore_ticket',
61
-                'capability' => 'ee_delete_default_ticket',
62
-                'obj_id'     => $tkt_id,
63
-                'noheader'   => true,
64
-                'args'       => array('trash' => true),
65
-            ),
66
-            'trash_tickets'            => array(
67
-                'func'       => '_trash_or_restore_ticket',
68
-                'capability' => 'ee_delete_default_tickets',
69
-                'noheader'   => true,
70
-                'args'       => array('trash' => true),
71
-            ),
72
-            'restore_ticket'           => array(
73
-                'func'       => '_trash_or_restore_ticket',
74
-                'capability' => 'ee_delete_default_ticket',
75
-                'obj_id'     => $tkt_id,
76
-                'noheader'   => true,
77
-            ),
78
-            'restore_tickets'          => array(
79
-                'func'       => '_trash_or_restore_ticket',
80
-                'capability' => 'ee_delete_default_tickets',
81
-                'noheader'   => true,
82
-            ),
83
-            'delete_ticket'            => array(
84
-                'func'       => '_delete_ticket',
85
-                'capability' => 'ee_delete_default_ticket',
86
-                'obj_id'     => $tkt_id,
87
-                'noheader'   => true,
88
-            ),
89
-            'delete_tickets'           => array(
90
-                'func'       => '_delete_ticket',
91
-                'capability' => 'ee_delete_default_tickets',
92
-                'noheader'   => true,
93
-            ),
94
-            'import_page'              => array(
95
-                'func'       => '_import_page',
96
-                'capability' => 'import',
97
-            ),
98
-            'import'                   => array(
99
-                'func'       => '_import_events',
100
-                'capability' => 'import',
101
-                'noheader'   => true,
102
-            ),
103
-            'import_events'            => array(
104
-                'func'       => '_import_events',
105
-                'capability' => 'import',
106
-                'noheader'   => true,
107
-            ),
108
-            'export_events'            => array(
109
-                'func'       => '_events_export',
110
-                'capability' => 'export',
111
-                'noheader'   => true,
112
-            ),
113
-            'export_categories'        => array(
114
-                'func'       => '_categories_export',
115
-                'capability' => 'export',
116
-                'noheader'   => true,
117
-            ),
118
-            'sample_export_file'       => array(
119
-                'func'       => '_sample_export_file',
120
-                'capability' => 'export',
121
-                'noheader'   => true,
122
-            ),
123
-            'update_template_settings' => array(
124
-                'func'       => '_update_template_settings',
125
-                'capability' => 'manage_options',
126
-                'noheader'   => true,
127
-            ),
128
-        );
129
-        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
130
-        //partial route/config override
131
-        $this->_page_config['import_events']['metaboxes'] = $this->_default_espresso_metaboxes;
132
-        $this->_page_config['create_new']['metaboxes'][]  = '_premium_event_editor_meta_boxes';
133
-        $this->_page_config['create_new']['qtips'][]      = 'EE_Event_Editor_Tips';
134
-        $this->_page_config['edit']['qtips'][]            = 'EE_Event_Editor_Tips';
135
-        $this->_page_config['edit']['metaboxes'][]        = '_premium_event_editor_meta_boxes';
136
-        $this->_page_config['default']['list_table']      = 'Extend_Events_Admin_List_Table';
137
-        //add tickets tab but only if there are more than one default ticket!
138
-        $tkt_count = EEM_Ticket::instance()->count_deleted_and_undeleted(
139
-            array(array('TKT_is_default' => 1)),
140
-            'TKT_ID',
141
-            true
142
-        );
143
-        if ($tkt_count > 1) {
144
-            $new_page_config = array(
145
-                'ticket_list_table' => array(
146
-                    'nav'           => array(
147
-                        'label' => esc_html__('Default Tickets', 'event_espresso'),
148
-                        'order' => 60,
149
-                    ),
150
-                    'list_table'    => 'Tickets_List_Table',
151
-                    'require_nonce' => false,
152
-                ),
153
-            );
154
-        }
155
-        //template settings
156
-        $new_page_config['template_settings'] = array(
157
-            'nav'           => array(
158
-                'label' => esc_html__('Templates', 'event_espresso'),
159
-                'order' => 30,
160
-            ),
161
-            'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
162
-            'help_tabs'     => array(
163
-                'general_settings_templates_help_tab' => array(
164
-                    'title'    => esc_html__('Templates', 'event_espresso'),
165
-                    'filename' => 'general_settings_templates',
166
-                ),
167
-            ),
168
-            'help_tour'     => array('Templates_Help_Tour'),
169
-            'require_nonce' => false,
170
-        );
171
-        $this->_page_config                   = array_merge($this->_page_config, $new_page_config);
172
-        //add filters and actions
173
-        //modifying _views
174
-        add_filter(
175
-            'FHEE_event_datetime_metabox_add_additional_date_time_template',
176
-            array($this, 'add_additional_datetime_button'),
177
-            10,
178
-            2
179
-        );
180
-        add_filter(
181
-            'FHEE_event_datetime_metabox_clone_button_template',
182
-            array($this, 'add_datetime_clone_button'),
183
-            10,
184
-            2
185
-        );
186
-        add_filter(
187
-            'FHEE_event_datetime_metabox_timezones_template',
188
-            array($this, 'datetime_timezones_template'),
189
-            10,
190
-            2
191
-        );
192
-        //filters for event list table
193
-        add_filter('FHEE__Extend_Events_Admin_List_Table__filters', array($this, 'list_table_filters'), 10, 2);
194
-        add_filter(
195
-            'FHEE__Events_Admin_List_Table__column_actions__action_links',
196
-            array($this, 'extra_list_table_actions'),
197
-            10,
198
-            2
199
-        );
200
-        //legend item
201
-        add_filter('FHEE__Events_Admin_Page___event_legend_items__items', array($this, 'additional_legend_items'));
202
-        add_action('admin_init', array($this, 'admin_init'));
203
-        //heartbeat stuff
204
-        add_filter('heartbeat_received', array($this, 'heartbeat_response'), 10, 2);
205
-    }
206
-
207
-
208
-    /**
209
-     * admin_init
210
-     */
211
-    public function admin_init()
212
-    {
213
-        EE_Registry::$i18n_js_strings = array_merge(
214
-            EE_Registry::$i18n_js_strings,
215
-            array(
216
-                'image_confirm'          => esc_html__(
217
-                    'Do you really want to delete this image? Please remember to update your event to complete the removal.',
218
-                    'event_espresso'
219
-                ),
220
-                'event_starts_on'        => esc_html__('Event Starts on', 'event_espresso'),
221
-                'event_ends_on'          => esc_html__('Event Ends on', 'event_espresso'),
222
-                'event_datetime_actions' => esc_html__('Actions', 'event_espresso'),
223
-                'event_clone_dt_msg'     => esc_html__('Clone this Event Date and Time', 'event_espresso'),
224
-                'remove_event_dt_msg'    => esc_html__('Remove this Event Time', 'event_espresso'),
225
-            )
226
-        );
227
-    }
228
-
229
-
230
-    /**
231
-     * This will be used to listen for any heartbeat data packages coming via the WordPress heartbeat API and handle
232
-     * accordingly.
233
-     *
234
-     * @param array $response The existing heartbeat response array.
235
-     * @param array $data     The incoming data package.
236
-     * @return array  possibly appended response.
237
-     */
238
-    public function heartbeat_response($response, $data)
239
-    {
240
-        /**
241
-         * check whether count of tickets is approaching the potential
242
-         * limits for the server.
243
-         */
244
-        if (! empty($data['input_count'])) {
245
-            $response['max_input_vars_check'] = EE_Registry::instance()->CFG->environment->max_input_vars_limit_check(
246
-                $data['input_count']
247
-            );
248
-        }
249
-        return $response;
250
-    }
251
-
252
-
253
-    /**
254
-     * Add per page screen options to the default ticket list table view.
255
-     */
256
-    protected function _add_screen_options_ticket_list_table()
257
-    {
258
-        $this->_per_page_screen_option();
259
-    }
260
-
261
-
262
-    /**
263
-     * @param string $return
264
-     * @param int    $id
265
-     * @param string $new_title
266
-     * @param string $new_slug
267
-     * @return string
268
-     */
269
-    public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
270
-    {
271
-        $return = parent::extra_permalink_field_buttons($return, $id, $new_title, $new_slug);
272
-        //make sure this is only when editing
273
-        if (! empty($id)) {
274
-            $href   = EE_Admin_Page::add_query_args_and_nonce(
275
-                array('action' => 'duplicate_event', 'EVT_ID' => $id),
276
-                $this->_admin_base_url
277
-            );
278
-            $title  = esc_attr__('Duplicate Event', 'event_espresso');
279
-            $return .= '<a href="'
280
-                       . $href
281
-                       . '" title="'
282
-                       . $title
283
-                       . '" id="ee-duplicate-event-button" class="button button-small"  value="duplicate_event">'
284
-                       . $title
285
-                       . '</button>';
286
-        }
287
-        return $return;
288
-    }
289
-
290
-
291
-    /**
292
-     * Set the list table views for the default ticket list table view.
293
-     */
294
-    public function _set_list_table_views_ticket_list_table()
295
-    {
296
-        $this->_views = array(
297
-            'all'     => array(
298
-                'slug'        => 'all',
299
-                'label'       => esc_html__('All', 'event_espresso'),
300
-                'count'       => 0,
301
-                'bulk_action' => array(
302
-                    'trash_tickets' => esc_html__('Move to Trash', 'event_espresso'),
303
-                ),
304
-            ),
305
-            'trashed' => array(
306
-                'slug'        => 'trashed',
307
-                'label'       => esc_html__('Trash', 'event_espresso'),
308
-                'count'       => 0,
309
-                'bulk_action' => array(
310
-                    'restore_tickets' => esc_html__('Restore from Trash', 'event_espresso'),
311
-                    'delete_tickets'  => esc_html__('Delete Permanently', 'event_espresso'),
312
-                ),
313
-            ),
314
-        );
315
-    }
316
-
317
-
318
-    /**
319
-     * Enqueue scripts and styles for the event editor.
320
-     */
321
-    public function load_scripts_styles_edit()
322
-    {
323
-        wp_register_script(
324
-            'ee-event-editor-heartbeat',
325
-            EVENTS_CAF_ASSETS_URL . 'event-editor-heartbeat.js',
326
-            array('ee_admin_js', 'heartbeat'),
327
-            EVENT_ESPRESSO_VERSION,
328
-            true
329
-        );
330
-        wp_enqueue_script('ee-accounting');
331
-        //styles
332
-        wp_enqueue_style('espresso-ui-theme');
333
-        wp_enqueue_script('event_editor_js');
334
-        wp_enqueue_script('ee-event-editor-heartbeat');
335
-    }
336
-
337
-
338
-    /**
339
-     * Returns template for the additional datetime.
340
-     * @param $template
341
-     * @param $template_args
342
-     * @return mixed
343
-     * @throws DomainException
344
-     */
345
-    public function add_additional_datetime_button($template, $template_args)
346
-    {
347
-        return EEH_Template::display_template(
348
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_add_additional_time.template.php',
349
-            $template_args,
350
-            true
351
-        );
352
-    }
353
-
354
-
355
-    /**
356
-     * Returns the template for cloning a datetime.
357
-     * @param $template
358
-     * @param $template_args
359
-     * @return mixed
360
-     * @throws DomainException
361
-     */
362
-    public function add_datetime_clone_button($template, $template_args)
363
-    {
364
-        return EEH_Template::display_template(
365
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_metabox_clone_button.template.php',
366
-            $template_args,
367
-            true
368
-        );
369
-    }
370
-
371
-
372
-    /**
373
-     * Returns the template for datetime timezones.
374
-     * @param $template
375
-     * @param $template_args
376
-     * @return mixed
377
-     * @throws DomainException
378
-     */
379
-    public function datetime_timezones_template($template, $template_args)
380
-    {
381
-        return EEH_Template::display_template(
382
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_timezones.template.php',
383
-            $template_args,
384
-            true
385
-        );
386
-    }
387
-
388
-
389
-    /**
390
-     * Sets the views for the default list table view.
391
-     */
392
-    protected function _set_list_table_views_default()
393
-    {
394
-        parent::_set_list_table_views_default();
395
-        $new_views    = array(
396
-            'today' => array(
397
-                'slug'        => 'today',
398
-                'label'       => esc_html__('Today', 'event_espresso'),
399
-                'count'       => $this->total_events_today(),
400
-                'bulk_action' => array(
401
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
402
-                ),
403
-            ),
404
-            'month' => array(
405
-                'slug'        => 'month',
406
-                'label'       => esc_html__('This Month', 'event_espresso'),
407
-                'count'       => $this->total_events_this_month(),
408
-                'bulk_action' => array(
409
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
410
-                ),
411
-            ),
412
-        );
413
-        $this->_views = array_merge($this->_views, $new_views);
414
-    }
415
-
416
-
417
-    /**
418
-     * Returns the extra action links for the default list table view.
419
-     * @param array     $action_links
420
-     * @param \EE_Event $event
421
-     * @return array
422
-     * @throws EE_Error
423
-     */
424
-    public function extra_list_table_actions(array $action_links, \EE_Event $event)
425
-    {
426
-        if (EE_Registry::instance()->CAP->current_user_can(
427
-            'ee_read_registrations',
428
-            'espresso_registrations_reports',
429
-            $event->ID()
430
-        )
431
-        ) {
432
-            $reports_query_args = array(
433
-                'action' => 'reports',
434
-                'EVT_ID' => $event->ID(),
435
-            );
436
-            $reports_link       = EE_Admin_Page::add_query_args_and_nonce($reports_query_args, REG_ADMIN_URL);
437
-            $action_links[]     = '<a href="'
438
-                                  . $reports_link
439
-                                  . '" title="'
440
-                                  . esc_attr__('View Report', 'event_espresso')
441
-                                  . '"><div class="dashicons dashicons-chart-bar"></div></a>'
442
-                                  . "\n\t";
443
-        }
444
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
445
-            EE_Registry::instance()->load_helper('MSG_Template');
446
-            $action_links[] = EEH_MSG_Template::get_message_action_link(
447
-                'see_notifications_for',
448
-                null,
449
-                array('EVT_ID' => $event->ID())
450
-            );
451
-        }
452
-        return $action_links;
453
-    }
454
-
455
-
456
-    /**
457
-     * @param $items
458
-     * @return mixed
459
-     */
460
-    public function additional_legend_items($items)
461
-    {
462
-        if (EE_Registry::instance()->CAP->current_user_can(
463
-            'ee_read_registrations',
464
-            'espresso_registrations_reports'
465
-        )
466
-        ) {
467
-            $items['reports'] = array(
468
-                'class' => 'dashicons dashicons-chart-bar',
469
-                'desc'  => esc_html__('Event Reports', 'event_espresso'),
470
-            );
471
-        }
472
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
473
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
474
-            if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
475
-                $items['view_related_messages'] = array(
476
-                    'class' => $related_for_icon['css_class'],
477
-                    'desc'  => $related_for_icon['label'],
478
-                );
479
-            }
480
-        }
481
-        return $items;
482
-    }
483
-
484
-
485
-    /**
486
-     * This is the callback method for the duplicate event route
487
-     * Method looks for 'EVT_ID' in the request and retrieves that event and its details and duplicates them
488
-     * into a new event.  We add a hook so that any plugins that add extra event details can hook into this
489
-     * action.  Note that the dupe will have **DUPLICATE** as its title and slug.
490
-     * After duplication the redirect is to the new event edit page.
491
-     *
492
-     * @return void
493
-     * @access protected
494
-     * @throws EE_Error If EE_Event is not available with given ID
495
-     */
496
-    protected function _duplicate_event()
497
-    {
498
-        // first make sure the ID for the event is in the request.
499
-        //  If it isn't then we need to bail and redirect back to overview list table (cause how did we get here?)
500
-        if (! isset($this->_req_data['EVT_ID'])) {
501
-            EE_Error::add_error(
502
-                esc_html__(
503
-                    'In order to duplicate an event an Event ID is required.  None was given.',
504
-                    'event_espresso'
505
-                ),
506
-                __FILE__,
507
-                __FUNCTION__,
508
-                __LINE__
509
-            );
510
-            $this->_redirect_after_action(false, '', '', array(), true);
511
-            return;
512
-        }
513
-        //k we've got EVT_ID so let's use that to get the event we'll duplicate
514
-        $orig_event = EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']);
515
-        if (! $orig_event instanceof EE_Event) {
516
-            throw new EE_Error(
517
-                sprintf(
518
-                    esc_html__('An EE_Event object could not be retrieved for the given ID (%s)', 'event_espresso'),
519
-                    $this->_req_data['EVT_ID']
520
-                )
521
-            );
522
-        }
523
-        //k now let's clone the $orig_event before getting relations
524
-        $new_event = clone $orig_event;
525
-        //original datetimes
526
-        $orig_datetimes = $orig_event->get_many_related('Datetime');
527
-        //other original relations
528
-        $orig_ven = $orig_event->get_many_related('Venue');
529
-        //reset the ID and modify other details to make it clear this is a dupe
530
-        $new_event->set('EVT_ID', 0);
531
-        $new_name = $new_event->name() . ' ' . esc_html__('**DUPLICATE**', 'event_espresso');
532
-        $new_event->set('EVT_name', $new_name);
533
-        $new_event->set(
534
-            'EVT_slug',
535
-            wp_unique_post_slug(
536
-                sanitize_title($orig_event->name()),
537
-                0,
538
-                'publish',
539
-                'espresso_events',
540
-                0
541
-            )
542
-        );
543
-        $new_event->set('status', 'draft');
544
-        //duplicate discussion settings
545
-        $new_event->set('comment_status', $orig_event->get('comment_status'));
546
-        $new_event->set('ping_status', $orig_event->get('ping_status'));
547
-        //save the new event
548
-        $new_event->save();
549
-        //venues
550
-        foreach ($orig_ven as $ven) {
551
-            $new_event->_add_relation_to($ven, 'Venue');
552
-        }
553
-        $new_event->save();
554
-        //now we need to get the question group relations and handle that
555
-        //first primary question groups
556
-        $orig_primary_qgs = $orig_event->get_many_related(
557
-            'Question_Group',
558
-            array(array('Event_Question_Group.EQG_primary' => 1))
559
-        );
560
-        if (! empty($orig_primary_qgs)) {
561
-            foreach ($orig_primary_qgs as $id => $obj) {
562
-                if ($obj instanceof EE_Question_Group) {
563
-                    $new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 1));
564
-                }
565
-            }
566
-        }
567
-        //next additional attendee question groups
568
-        $orig_additional_qgs = $orig_event->get_many_related(
569
-            'Question_Group',
570
-            array(array('Event_Question_Group.EQG_primary' => 0))
571
-        );
572
-        if (! empty($orig_additional_qgs)) {
573
-            foreach ($orig_additional_qgs as $id => $obj) {
574
-                if ($obj instanceof EE_Question_Group) {
575
-                    $new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 0));
576
-                }
577
-            }
578
-        }
579
-
580
-        $new_event->save();
581
-
582
-        //k now that we have the new event saved we can loop through the datetimes and start adding relations.
583
-        $cloned_tickets = array();
584
-        foreach ($orig_datetimes as $orig_dtt) {
585
-            if (! $orig_dtt instanceof EE_Datetime) {
586
-                continue;
587
-            }
588
-            $new_dtt   = clone $orig_dtt;
589
-            $orig_tkts = $orig_dtt->tickets();
590
-            //save new dtt then add to event
591
-            $new_dtt->set('DTT_ID', 0);
592
-            $new_dtt->set('DTT_sold', 0);
593
-            $new_dtt->set_reserved(0);
594
-            $new_dtt->save();
595
-            $new_event->_add_relation_to($new_dtt, 'Datetime');
596
-            $new_event->save();
597
-            //now let's get the ticket relations setup.
598
-            foreach ((array)$orig_tkts as $orig_tkt) {
599
-                //it's possible a datetime will have no tickets so let's verify we HAVE a ticket first.
600
-                if (! $orig_tkt instanceof EE_Ticket) {
601
-                    continue;
602
-                }
603
-                //is this ticket archived?  If it is then let's skip
604
-                if ($orig_tkt->get('TKT_deleted')) {
605
-                    continue;
606
-                }
607
-                // does this original ticket already exist in the clone_tickets cache?
608
-                //  If so we'll just use the new ticket from it.
609
-                if (isset($cloned_tickets[$orig_tkt->ID()])) {
610
-                    $new_tkt = $cloned_tickets[$orig_tkt->ID()];
611
-                } else {
612
-                    $new_tkt = clone $orig_tkt;
613
-                    //get relations on the $orig_tkt that we need to setup.
614
-                    $orig_prices = $orig_tkt->prices();
615
-                    $new_tkt->set('TKT_ID', 0);
616
-                    $new_tkt->set('TKT_sold', 0);
617
-                    $new_tkt->set('TKT_reserved', 0);
618
-                    $new_tkt->save(); //make sure new ticket has ID.
619
-                    //price relations on new ticket need to be setup.
620
-                    foreach ($orig_prices as $orig_price) {
621
-                        $new_price = clone $orig_price;
622
-                        $new_price->set('PRC_ID', 0);
623
-                        $new_price->save();
624
-                        $new_tkt->_add_relation_to($new_price, 'Price');
625
-                        $new_tkt->save();
626
-                    }
627
-
628
-                    do_action(
629
-                        'AHEE__Extend_Events_Admin_Page___duplicate_event__duplicate_ticket__after',
630
-                        $orig_tkt,
631
-                        $new_tkt,
632
-                        $orig_prices,
633
-                        $orig_event,
634
-                        $orig_dtt,
635
-                        $new_dtt
636
-                    );
637
-                }
638
-                // k now we can add the new ticket as a relation to the new datetime
639
-                // and make sure its added to our cached $cloned_tickets array
640
-                // for use with later datetimes that have the same ticket.
641
-                $new_dtt->_add_relation_to($new_tkt, 'Ticket');
642
-                $new_dtt->save();
643
-                $cloned_tickets[$orig_tkt->ID()] = $new_tkt;
644
-            }
645
-        }
646
-        //clone taxonomy information
647
-        $taxonomies_to_clone_with = apply_filters(
648
-            'FHEE__Extend_Events_Admin_Page___duplicate_event__taxonomies_to_clone',
649
-            array('espresso_event_categories', 'espresso_event_type', 'post_tag')
650
-        );
651
-        //get terms for original event (notice)
652
-        $orig_terms = wp_get_object_terms($orig_event->ID(), $taxonomies_to_clone_with);
653
-        //loop through terms and add them to new event.
654
-        foreach ($orig_terms as $term) {
655
-            wp_set_object_terms($new_event->ID(), $term->term_id, $term->taxonomy, true);
656
-        }
657
-
658
-        //duplicate other core WP_Post items for this event.
659
-        //post thumbnail (feature image).
660
-        $feature_image_id = get_post_thumbnail_id($orig_event->ID());
661
-        if ($feature_image_id) {
662
-            update_post_meta($new_event->ID(), '_thumbnail_id', $feature_image_id);
663
-        }
664
-
665
-        //duplicate page_template setting
666
-        $page_template = get_post_meta($orig_event->ID(), '_wp_page_template', true);
667
-        if ($page_template) {
668
-            update_post_meta($new_event->ID(), '_wp_page_template', $page_template);
669
-        }
670
-
671
-        do_action('AHEE__Extend_Events_Admin_Page___duplicate_event__after', $new_event, $orig_event);
672
-        //now let's redirect to the edit page for this duplicated event if we have a new event id.
673
-        if ($new_event->ID()) {
674
-            $redirect_args = array(
675
-                'post'   => $new_event->ID(),
676
-                'action' => 'edit',
677
-            );
678
-            EE_Error::add_success(
679
-                esc_html__(
680
-                    'Event successfully duplicated.  Please review the details below and make any necessary edits',
681
-                    'event_espresso'
682
-                )
683
-            );
684
-        } else {
685
-            $redirect_args = array(
686
-                'action' => 'default',
687
-            );
688
-            EE_Error::add_error(
689
-                esc_html__('Not able to duplicate event.  Something went wrong.', 'event_espresso'),
690
-                __FILE__,
691
-                __FUNCTION__,
692
-                __LINE__
693
-            );
694
-        }
695
-        $this->_redirect_after_action(false, '', '', $redirect_args, true);
696
-    }
697
-
698
-
699
-    /**
700
-     * Generates output for the import page.
701
-     * @throws DomainException
702
-     */
703
-    protected function _import_page()
704
-    {
705
-        $title                                      = esc_html__('Import', 'event_espresso');
706
-        $intro                                      = esc_html__(
707
-            'If you have a previously exported Event Espresso 4 information in a Comma Separated Value (CSV) file format, you can upload the file here: ',
708
-            'event_espresso'
709
-        );
710
-        $form_url                                   = EVENTS_ADMIN_URL;
711
-        $action                                     = 'import_events';
712
-        $type                                       = 'csv';
713
-        $this->_template_args['form']               = EE_Import::instance()->upload_form(
714
-            $title, $intro, $form_url, $action, $type
715
-        );
716
-        $this->_template_args['sample_file_link']   = EE_Admin_Page::add_query_args_and_nonce(
717
-            array('action' => 'sample_export_file'),
718
-            $this->_admin_base_url
719
-        );
720
-        $content                                    = EEH_Template::display_template(
721
-            EVENTS_CAF_TEMPLATE_PATH . 'import_page.template.php',
722
-            $this->_template_args,
723
-            true
724
-        );
725
-        $this->_template_args['admin_page_content'] = $content;
726
-        $this->display_admin_page_with_sidebar();
727
-    }
728
-
729
-
730
-    /**
731
-     * _import_events
732
-     * This handles displaying the screen and running imports for importing events.
733
-     *
734
-     * @return void
735
-     */
736
-    protected function _import_events()
737
-    {
738
-        require_once(EE_CLASSES . 'EE_Import.class.php');
739
-        $success = EE_Import::instance()->import();
740
-        $this->_redirect_after_action($success, 'Import File', 'ran', array('action' => 'import_page'), true);
741
-    }
742
-
743
-
744
-    /**
745
-     * _events_export
746
-     * Will export all (or just the given event) to a Excel compatible file.
747
-     *
748
-     * @access protected
749
-     * @return void
750
-     */
751
-    protected function _events_export()
752
-    {
753
-        if (isset($this->_req_data['EVT_ID'])) {
754
-            $event_ids = $this->_req_data['EVT_ID'];
755
-        } elseif (isset($this->_req_data['EVT_IDs'])) {
756
-            $event_ids = $this->_req_data['EVT_IDs'];
757
-        } else {
758
-            $event_ids = null;
759
-        }
760
-        //todo: I don't like doing this but it'll do until we modify EE_Export Class.
761
-        $new_request_args = array(
762
-            'export' => 'report',
763
-            'action' => 'all_event_data',
764
-            'EVT_ID' => $event_ids,
765
-        );
766
-        $this->_req_data  = array_merge($this->_req_data, $new_request_args);
767
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
768
-            require_once(EE_CLASSES . 'EE_Export.class.php');
769
-            $EE_Export = EE_Export::instance($this->_req_data);
770
-            $EE_Export->export();
771
-        }
772
-    }
773
-
774
-
775
-    /**
776
-     * handle category exports()
777
-     *
778
-     * @return void
779
-     */
780
-    protected function _categories_export()
781
-    {
782
-        //todo: I don't like doing this but it'll do until we modify EE_Export Class.
783
-        $new_request_args = array(
784
-            'export'       => 'report',
785
-            'action'       => 'categories',
786
-            'category_ids' => $this->_req_data['EVT_CAT_ID'],
787
-        );
788
-        $this->_req_data  = array_merge($this->_req_data, $new_request_args);
789
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
790
-            require_once(EE_CLASSES . 'EE_Export.class.php');
791
-            $EE_Export = EE_Export::instance($this->_req_data);
792
-            $EE_Export->export();
793
-        }
794
-    }
795
-
796
-
797
-    /**
798
-     * Creates a sample CSV file for importing
799
-     */
800
-    protected function _sample_export_file()
801
-    {
802
-        //		require_once(EE_CLASSES . 'EE_Export.class.php');
803
-        EE_Export::instance()->export_sample();
804
-    }
805
-
806
-
807
-    /*************        Template Settings        *************/
808
-    /**
809
-     * Generates template settings page output
810
-     * @throws DomainException
811
-     * @throws EE_Error
812
-     */
813
-    protected function _template_settings()
814
-    {
815
-        $this->_template_args['values'] = $this->_yes_no_values;
816
-        /**
817
-         * Note leaving this filter in for backward compatibility this was moved in 4.6.x
818
-         * from General_Settings_Admin_Page to here.
819
-         */
820
-        $this->_template_args = apply_filters(
821
-            'FHEE__General_Settings_Admin_Page__template_settings__template_args',
822
-            $this->_template_args
823
-        );
824
-        $this->_set_add_edit_form_tags('update_template_settings');
825
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
826
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
827
-            EVENTS_CAF_TEMPLATE_PATH . 'template_settings.template.php',
828
-            $this->_template_args,
829
-            true
830
-        );
831
-        $this->display_admin_page_with_sidebar();
832
-    }
833
-
834
-
835
-    /**
836
-     * Handler for updating template settings.
837
-     */
838
-    protected function _update_template_settings()
839
-    {
840
-        /**
841
-         * Note leaving this filter in for backward compatibility this was moved in 4.6.x
842
-         * from General_Settings_Admin_Page to here.
843
-         */
844
-        EE_Registry::instance()->CFG->template_settings = apply_filters(
845
-            'FHEE__General_Settings_Admin_Page__update_template_settings__data',
846
-            EE_Registry::instance()->CFG->template_settings,
847
-            $this->_req_data
848
-        );
849
-        //update custom post type slugs and detect if we need to flush rewrite rules
850
-        $old_slug                                          = EE_Registry::instance()->CFG->core->event_cpt_slug;
851
-        EE_Registry::instance()->CFG->core->event_cpt_slug = empty($this->_req_data['event_cpt_slug'])
852
-            ? EE_Registry::instance()->CFG->core->event_cpt_slug
853
-            : sanitize_title_with_dashes($this->_req_data['event_cpt_slug']);
854
-        $what                                              = 'Template Settings';
855
-        $success                                           = $this->_update_espresso_configuration(
856
-            $what,
857
-            EE_Registry::instance()->CFG->template_settings,
858
-            __FILE__,
859
-            __FUNCTION__,
860
-            __LINE__
861
-        );
862
-        if (EE_Registry::instance()->CFG->core->event_cpt_slug != $old_slug) {
863
-            update_option('ee_flush_rewrite_rules', true);
864
-        }
865
-        $this->_redirect_after_action($success, $what, 'updated', array('action' => 'template_settings'));
866
-    }
867
-
868
-
869
-    /**
870
-     * _premium_event_editor_meta_boxes
871
-     * add all metaboxes related to the event_editor
872
-     *
873
-     * @access protected
874
-     * @return void
875
-     * @throws EE_Error
876
-     */
877
-    protected function _premium_event_editor_meta_boxes()
878
-    {
879
-        $this->verify_cpt_object();
880
-        add_meta_box(
881
-            'espresso_event_editor_event_options',
882
-            esc_html__('Event Registration Options', 'event_espresso'),
883
-            array($this, 'registration_options_meta_box'),
884
-            $this->page_slug,
885
-            'side',
886
-            'core'
887
-        );
888
-    }
889
-
890
-
891
-    /**
892
-     * override caf metabox
893
-     *
894
-     * @return void
895
-     * @throws DomainException
896
-     */
897
-    public function registration_options_meta_box()
898
-    {
899
-        $yes_no_values                                    = array(
900
-            array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
901
-            array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
902
-        );
903
-        $default_reg_status_values                        = EEM_Registration::reg_status_array(
904
-            array(
905
-                EEM_Registration::status_id_cancelled,
906
-                EEM_Registration::status_id_declined,
907
-                EEM_Registration::status_id_incomplete,
908
-                EEM_Registration::status_id_wait_list,
909
-            ),
910
-            true
911
-        );
912
-        $template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
913
-        $template_args['_event']                          = $this->_cpt_model_obj;
914
-        $template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
915
-        $template_args['default_registration_status']     = EEH_Form_Fields::select_input(
916
-            'default_reg_status',
917
-            $default_reg_status_values,
918
-            $this->_cpt_model_obj->default_registration_status()
919
-        );
920
-        $template_args['display_description']             = EEH_Form_Fields::select_input(
921
-            'display_desc',
922
-            $yes_no_values,
923
-            $this->_cpt_model_obj->display_description()
924
-        );
925
-        $template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
926
-            'display_ticket_selector',
927
-            $yes_no_values,
928
-            $this->_cpt_model_obj->display_ticket_selector(),
929
-            '',
930
-            '',
931
-            false
932
-        );
933
-        $template_args['EVT_default_registration_status'] = EEH_Form_Fields::select_input(
934
-            'EVT_default_registration_status',
935
-            $default_reg_status_values,
936
-            $this->_cpt_model_obj->default_registration_status()
937
-        );
938
-        $template_args['additional_registration_options'] = apply_filters(
939
-            'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
940
-            '',
941
-            $template_args,
942
-            $yes_no_values,
943
-            $default_reg_status_values
944
-        );
945
-        EEH_Template::display_template(
946
-            EVENTS_CAF_TEMPLATE_PATH . 'event_registration_options.template.php',
947
-            $template_args
948
-        );
949
-    }
950
-
951
-
952
-
953
-    /**
954
-     * wp_list_table_mods for caf
955
-     * ============================
956
-     */
957
-    /**
958
-     * hook into list table filters and provide filters for caffeinated list table
959
-     *
960
-     * @param  array $old_filters    any existing filters present
961
-     * @param  array $list_table_obj the list table object
962
-     * @return array                  new filters
963
-     */
964
-    public function list_table_filters($old_filters, $list_table_obj)
965
-    {
966
-        $filters = array();
967
-        //first month/year filters
968
-        $filters[] = $this->espresso_event_months_dropdown();
969
-        $status    = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
970
-        //active status dropdown
971
-        if ($status !== 'draft') {
972
-            $filters[] = $this->active_status_dropdown(
973
-                isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : ''
974
-            );
975
-        }
976
-        //category filter
977
-        $filters[] = $this->category_dropdown();
978
-        return array_merge($old_filters, $filters);
979
-    }
980
-
981
-
982
-    /**
983
-     * espresso_event_months_dropdown
984
-     *
985
-     * @access public
986
-     * @return string                dropdown listing month/year selections for events.
987
-     */
988
-    public function espresso_event_months_dropdown()
989
-    {
990
-        // what we need to do is get all PRIMARY datetimes for all events to filter on.
991
-        // Note we need to include any other filters that are set!
992
-        $status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
993
-        //categories?
994
-        $category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
995
-            ? $this->_req_data['EVT_CAT']
996
-            : null;
997
-        //active status?
998
-        $active_status = isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : null;
999
-        $cur_date      = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
1000
-        return EEH_Form_Fields::generate_event_months_dropdown($cur_date, $status, $category, $active_status);
1001
-    }
1002
-
1003
-
1004
-    /**
1005
-     * returns a list of "active" statuses on the event
1006
-     *
1007
-     * @param  string $current_value whatever the current active status is
1008
-     * @return string
1009
-     */
1010
-    public function active_status_dropdown($current_value = '')
1011
-    {
1012
-        $select_name = 'active_status';
1013
-        $values      = array(
1014
-            'none'     => esc_html__('Show Active/Inactive', 'event_espresso'),
1015
-            'active'   => esc_html__('Active', 'event_espresso'),
1016
-            'upcoming' => esc_html__('Upcoming', 'event_espresso'),
1017
-            'expired'  => esc_html__('Expired', 'event_espresso'),
1018
-            'inactive' => esc_html__('Inactive', 'event_espresso'),
1019
-        );
1020
-        $id          = 'id="espresso-active-status-dropdown-filter"';
1021
-        $class       = 'wide';
1022
-        return EEH_Form_Fields::select_input($select_name, $values, $current_value, $id, $class);
1023
-    }
1024
-
1025
-
1026
-    /**
1027
-     * output a dropdown of the categories for the category filter on the event admin list table
1028
-     *
1029
-     * @access  public
1030
-     * @return string html
1031
-     */
1032
-    public function category_dropdown()
1033
-    {
1034
-        $cur_cat = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
1035
-        return EEH_Form_Fields::generate_event_category_dropdown($cur_cat);
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * get total number of events today
1041
-     *
1042
-     * @access public
1043
-     * @return int
1044
-     * @throws EE_Error
1045
-     */
1046
-    public function total_events_today()
1047
-    {
1048
-        $start = EEM_Datetime::instance()->convert_datetime_for_query(
1049
-            'DTT_EVT_start',
1050
-            date('Y-m-d') . ' 00:00:00',
1051
-            'Y-m-d H:i:s',
1052
-            'UTC'
1053
-        );
1054
-        $end   = EEM_Datetime::instance()->convert_datetime_for_query(
1055
-            'DTT_EVT_start',
1056
-            date('Y-m-d') . ' 23:59:59',
1057
-            'Y-m-d H:i:s',
1058
-            'UTC'
1059
-        );
1060
-        $where = array(
1061
-            'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1062
-        );
1063
-        $count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1064
-        return $count;
1065
-    }
1066
-
1067
-
1068
-    /**
1069
-     * get total number of events this month
1070
-     *
1071
-     * @access public
1072
-     * @return int
1073
-     * @throws EE_Error
1074
-     */
1075
-    public function total_events_this_month()
1076
-    {
1077
-        //Dates
1078
-        $this_year_r     = date('Y');
1079
-        $this_month_r    = date('m');
1080
-        $days_this_month = date('t');
1081
-        $start           = EEM_Datetime::instance()->convert_datetime_for_query(
1082
-            'DTT_EVT_start',
1083
-            $this_year_r . '-' . $this_month_r . '-01 00:00:00',
1084
-            'Y-m-d H:i:s',
1085
-            'UTC'
1086
-        );
1087
-        $end             = EEM_Datetime::instance()->convert_datetime_for_query(
1088
-            'DTT_EVT_start',
1089
-            $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' 23:59:59',
1090
-            'Y-m-d H:i:s',
1091
-            'UTC'
1092
-        );
1093
-        $where           = array(
1094
-            'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1095
-        );
1096
-        $count           = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1097
-        return $count;
1098
-    }
1099
-
1100
-
1101
-    /** DEFAULT TICKETS STUFF **/
1102
-
1103
-    /**
1104
-     * Output default tickets list table view.
1105
-     */
1106
-    public function _tickets_overview_list_table()
1107
-    {
1108
-        $this->_search_btn_label = esc_html__('Tickets', 'event_espresso');
1109
-        $this->display_admin_list_table_page_with_no_sidebar();
1110
-    }
1111
-
1112
-
1113
-    /**
1114
-     * @param int  $per_page
1115
-     * @param bool $count
1116
-     * @param bool $trashed
1117
-     * @return \EE_Soft_Delete_Base_Class[]|int
1118
-     */
1119
-    public function get_default_tickets($per_page = 10, $count = false, $trashed = false)
1120
-    {
1121
-        $orderby = empty($this->_req_data['orderby']) ? 'TKT_name' : $this->_req_data['orderby'];
1122
-        $order   = empty($this->_req_data['order']) ? 'ASC' : $this->_req_data['order'];
1123
-        switch ($orderby) {
1124
-            case 'TKT_name':
1125
-                $orderby = array('TKT_name' => $order);
1126
-                break;
1127
-            case 'TKT_price':
1128
-                $orderby = array('TKT_price' => $order);
1129
-                break;
1130
-            case 'TKT_uses':
1131
-                $orderby = array('TKT_uses' => $order);
1132
-                break;
1133
-            case 'TKT_min':
1134
-                $orderby = array('TKT_min' => $order);
1135
-                break;
1136
-            case 'TKT_max':
1137
-                $orderby = array('TKT_max' => $order);
1138
-                break;
1139
-            case 'TKT_qty':
1140
-                $orderby = array('TKT_qty' => $order);
1141
-                break;
1142
-        }
1143
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1144
-            ? $this->_req_data['paged']
1145
-            : 1;
1146
-        $per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1147
-            ? $this->_req_data['perpage']
1148
-            : $per_page;
1149
-        $_where       = array(
1150
-            'TKT_is_default' => 1,
1151
-            'TKT_deleted'    => $trashed,
1152
-        );
1153
-        $offset       = ($current_page - 1) * $per_page;
1154
-        $limit        = array($offset, $per_page);
1155
-        if (isset($this->_req_data['s'])) {
1156
-            $sstr         = '%' . $this->_req_data['s'] . '%';
1157
-            $_where['OR'] = array(
1158
-                'TKT_name'        => array('LIKE', $sstr),
1159
-                'TKT_description' => array('LIKE', $sstr),
1160
-            );
1161
-        }
1162
-        $query_params = array(
1163
-            $_where,
1164
-            'order_by' => $orderby,
1165
-            'limit'    => $limit,
1166
-            'group_by' => 'TKT_ID',
1167
-        );
1168
-        if ($count) {
1169
-            return EEM_Ticket::instance()->count_deleted_and_undeleted(array($_where));
1170
-        } else {
1171
-            return EEM_Ticket::instance()->get_all_deleted_and_undeleted($query_params);
1172
-        }
1173
-    }
1174
-
1175
-
1176
-    /**
1177
-     * @param bool $trash
1178
-     * @throws EE_Error
1179
-     */
1180
-    protected function _trash_or_restore_ticket($trash = false)
1181
-    {
1182
-        $success = 1;
1183
-        $TKT     = EEM_Ticket::instance();
1184
-        //checkboxes?
1185
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1186
-            //if array has more than one element then success message should be plural
1187
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1188
-            //cycle thru the boxes
1189
-            while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1190
-                if ($trash) {
1191
-                    if (! $TKT->delete_by_ID($TKT_ID)) {
1192
-                        $success = 0;
1193
-                    }
1194
-                } else {
1195
-                    if (! $TKT->restore_by_ID($TKT_ID)) {
1196
-                        $success = 0;
1197
-                    }
1198
-                }
1199
-            }
1200
-        } else {
1201
-            //grab single id and trash
1202
-            $TKT_ID = absint($this->_req_data['TKT_ID']);
1203
-            if ($trash) {
1204
-                if (! $TKT->delete_by_ID($TKT_ID)) {
1205
-                    $success = 0;
1206
-                }
1207
-            } else {
1208
-                if (! $TKT->restore_by_ID($TKT_ID)) {
1209
-                    $success = 0;
1210
-                }
1211
-            }
1212
-        }
1213
-        $action_desc = $trash ? 'moved to the trash' : 'restored';
1214
-        $query_args  = array(
1215
-            'action' => 'ticket_list_table',
1216
-            'status' => $trash ? '' : 'trashed',
1217
-        );
1218
-        $this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1219
-    }
1220
-
1221
-
1222
-    /**
1223
-     * Handles trashing default ticket.
1224
-     */
1225
-    protected function _delete_ticket()
1226
-    {
1227
-        $success = 1;
1228
-        //checkboxes?
1229
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1230
-            //if array has more than one element then success message should be plural
1231
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1232
-            //cycle thru the boxes
1233
-            while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1234
-                //delete
1235
-                if (! $this->_delete_the_ticket($TKT_ID)) {
1236
-                    $success = 0;
1237
-                }
1238
-            }
1239
-        } else {
1240
-            //grab single id and trash
1241
-            $TKT_ID = absint($this->_req_data['TKT_ID']);
1242
-            if (! $this->_delete_the_ticket($TKT_ID)) {
1243
-                $success = 0;
1244
-            }
1245
-        }
1246
-        $action_desc = 'deleted';
1247
-        $query_args  = array(
1248
-            'action' => 'ticket_list_table',
1249
-            'status' => 'trashed',
1250
-        );
1251
-        //fail safe.  If the default ticket count === 1 then we need to redirect to event overview.
1252
-        if (EEM_Ticket::instance()->count_deleted_and_undeleted(
1253
-            array(array('TKT_is_default' => 1)),
1254
-            'TKT_ID',
1255
-            true
1256
-        )
1257
-        ) {
1258
-            $query_args = array();
1259
-        }
1260
-        $this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1261
-    }
1262
-
1263
-
1264
-    /**
1265
-     * @param int $TKT_ID
1266
-     * @return bool|int
1267
-     * @throws EE_Error
1268
-     */
1269
-    protected function _delete_the_ticket($TKT_ID)
1270
-    {
1271
-        $tkt = EEM_Ticket::instance()->get_one_by_ID($TKT_ID);
1272
-        $tkt->_remove_relations('Datetime');
1273
-        //delete all related prices first
1274
-        $tkt->delete_related_permanently('Price');
1275
-        return $tkt->delete_permanently();
1276
-    }
17
+	/**
18
+	 * Extend_Events_Admin_Page constructor.
19
+	 *
20
+	 * @param bool $routing
21
+	 */
22
+	public function __construct($routing = true)
23
+	{
24
+		parent::__construct($routing);
25
+		if (! defined('EVENTS_CAF_TEMPLATE_PATH')) {
26
+			define('EVENTS_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'events/templates/');
27
+			define('EVENTS_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'events/assets/');
28
+			define('EVENTS_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'events/assets/');
29
+		}
30
+	}
31
+
32
+
33
+	/**
34
+	 * Sets routes.
35
+	 */
36
+	protected function _extend_page_config()
37
+	{
38
+		$this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'events';
39
+		//is there a evt_id in the request?
40
+		$evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
41
+			? $this->_req_data['EVT_ID']
42
+			: 0;
43
+		$evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
44
+		//tkt_id?
45
+		$tkt_id             = ! empty($this->_req_data['TKT_ID']) && ! is_array($this->_req_data['TKT_ID'])
46
+			? $this->_req_data['TKT_ID']
47
+			: 0;
48
+		$new_page_routes    = array(
49
+			'duplicate_event'          => array(
50
+				'func'       => '_duplicate_event',
51
+				'capability' => 'ee_edit_event',
52
+				'obj_id'     => $evt_id,
53
+				'noheader'   => true,
54
+			),
55
+			'ticket_list_table'        => array(
56
+				'func'       => '_tickets_overview_list_table',
57
+				'capability' => 'ee_read_default_tickets',
58
+			),
59
+			'trash_ticket'             => array(
60
+				'func'       => '_trash_or_restore_ticket',
61
+				'capability' => 'ee_delete_default_ticket',
62
+				'obj_id'     => $tkt_id,
63
+				'noheader'   => true,
64
+				'args'       => array('trash' => true),
65
+			),
66
+			'trash_tickets'            => array(
67
+				'func'       => '_trash_or_restore_ticket',
68
+				'capability' => 'ee_delete_default_tickets',
69
+				'noheader'   => true,
70
+				'args'       => array('trash' => true),
71
+			),
72
+			'restore_ticket'           => array(
73
+				'func'       => '_trash_or_restore_ticket',
74
+				'capability' => 'ee_delete_default_ticket',
75
+				'obj_id'     => $tkt_id,
76
+				'noheader'   => true,
77
+			),
78
+			'restore_tickets'          => array(
79
+				'func'       => '_trash_or_restore_ticket',
80
+				'capability' => 'ee_delete_default_tickets',
81
+				'noheader'   => true,
82
+			),
83
+			'delete_ticket'            => array(
84
+				'func'       => '_delete_ticket',
85
+				'capability' => 'ee_delete_default_ticket',
86
+				'obj_id'     => $tkt_id,
87
+				'noheader'   => true,
88
+			),
89
+			'delete_tickets'           => array(
90
+				'func'       => '_delete_ticket',
91
+				'capability' => 'ee_delete_default_tickets',
92
+				'noheader'   => true,
93
+			),
94
+			'import_page'              => array(
95
+				'func'       => '_import_page',
96
+				'capability' => 'import',
97
+			),
98
+			'import'                   => array(
99
+				'func'       => '_import_events',
100
+				'capability' => 'import',
101
+				'noheader'   => true,
102
+			),
103
+			'import_events'            => array(
104
+				'func'       => '_import_events',
105
+				'capability' => 'import',
106
+				'noheader'   => true,
107
+			),
108
+			'export_events'            => array(
109
+				'func'       => '_events_export',
110
+				'capability' => 'export',
111
+				'noheader'   => true,
112
+			),
113
+			'export_categories'        => array(
114
+				'func'       => '_categories_export',
115
+				'capability' => 'export',
116
+				'noheader'   => true,
117
+			),
118
+			'sample_export_file'       => array(
119
+				'func'       => '_sample_export_file',
120
+				'capability' => 'export',
121
+				'noheader'   => true,
122
+			),
123
+			'update_template_settings' => array(
124
+				'func'       => '_update_template_settings',
125
+				'capability' => 'manage_options',
126
+				'noheader'   => true,
127
+			),
128
+		);
129
+		$this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
130
+		//partial route/config override
131
+		$this->_page_config['import_events']['metaboxes'] = $this->_default_espresso_metaboxes;
132
+		$this->_page_config['create_new']['metaboxes'][]  = '_premium_event_editor_meta_boxes';
133
+		$this->_page_config['create_new']['qtips'][]      = 'EE_Event_Editor_Tips';
134
+		$this->_page_config['edit']['qtips'][]            = 'EE_Event_Editor_Tips';
135
+		$this->_page_config['edit']['metaboxes'][]        = '_premium_event_editor_meta_boxes';
136
+		$this->_page_config['default']['list_table']      = 'Extend_Events_Admin_List_Table';
137
+		//add tickets tab but only if there are more than one default ticket!
138
+		$tkt_count = EEM_Ticket::instance()->count_deleted_and_undeleted(
139
+			array(array('TKT_is_default' => 1)),
140
+			'TKT_ID',
141
+			true
142
+		);
143
+		if ($tkt_count > 1) {
144
+			$new_page_config = array(
145
+				'ticket_list_table' => array(
146
+					'nav'           => array(
147
+						'label' => esc_html__('Default Tickets', 'event_espresso'),
148
+						'order' => 60,
149
+					),
150
+					'list_table'    => 'Tickets_List_Table',
151
+					'require_nonce' => false,
152
+				),
153
+			);
154
+		}
155
+		//template settings
156
+		$new_page_config['template_settings'] = array(
157
+			'nav'           => array(
158
+				'label' => esc_html__('Templates', 'event_espresso'),
159
+				'order' => 30,
160
+			),
161
+			'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
162
+			'help_tabs'     => array(
163
+				'general_settings_templates_help_tab' => array(
164
+					'title'    => esc_html__('Templates', 'event_espresso'),
165
+					'filename' => 'general_settings_templates',
166
+				),
167
+			),
168
+			'help_tour'     => array('Templates_Help_Tour'),
169
+			'require_nonce' => false,
170
+		);
171
+		$this->_page_config                   = array_merge($this->_page_config, $new_page_config);
172
+		//add filters and actions
173
+		//modifying _views
174
+		add_filter(
175
+			'FHEE_event_datetime_metabox_add_additional_date_time_template',
176
+			array($this, 'add_additional_datetime_button'),
177
+			10,
178
+			2
179
+		);
180
+		add_filter(
181
+			'FHEE_event_datetime_metabox_clone_button_template',
182
+			array($this, 'add_datetime_clone_button'),
183
+			10,
184
+			2
185
+		);
186
+		add_filter(
187
+			'FHEE_event_datetime_metabox_timezones_template',
188
+			array($this, 'datetime_timezones_template'),
189
+			10,
190
+			2
191
+		);
192
+		//filters for event list table
193
+		add_filter('FHEE__Extend_Events_Admin_List_Table__filters', array($this, 'list_table_filters'), 10, 2);
194
+		add_filter(
195
+			'FHEE__Events_Admin_List_Table__column_actions__action_links',
196
+			array($this, 'extra_list_table_actions'),
197
+			10,
198
+			2
199
+		);
200
+		//legend item
201
+		add_filter('FHEE__Events_Admin_Page___event_legend_items__items', array($this, 'additional_legend_items'));
202
+		add_action('admin_init', array($this, 'admin_init'));
203
+		//heartbeat stuff
204
+		add_filter('heartbeat_received', array($this, 'heartbeat_response'), 10, 2);
205
+	}
206
+
207
+
208
+	/**
209
+	 * admin_init
210
+	 */
211
+	public function admin_init()
212
+	{
213
+		EE_Registry::$i18n_js_strings = array_merge(
214
+			EE_Registry::$i18n_js_strings,
215
+			array(
216
+				'image_confirm'          => esc_html__(
217
+					'Do you really want to delete this image? Please remember to update your event to complete the removal.',
218
+					'event_espresso'
219
+				),
220
+				'event_starts_on'        => esc_html__('Event Starts on', 'event_espresso'),
221
+				'event_ends_on'          => esc_html__('Event Ends on', 'event_espresso'),
222
+				'event_datetime_actions' => esc_html__('Actions', 'event_espresso'),
223
+				'event_clone_dt_msg'     => esc_html__('Clone this Event Date and Time', 'event_espresso'),
224
+				'remove_event_dt_msg'    => esc_html__('Remove this Event Time', 'event_espresso'),
225
+			)
226
+		);
227
+	}
228
+
229
+
230
+	/**
231
+	 * This will be used to listen for any heartbeat data packages coming via the WordPress heartbeat API and handle
232
+	 * accordingly.
233
+	 *
234
+	 * @param array $response The existing heartbeat response array.
235
+	 * @param array $data     The incoming data package.
236
+	 * @return array  possibly appended response.
237
+	 */
238
+	public function heartbeat_response($response, $data)
239
+	{
240
+		/**
241
+		 * check whether count of tickets is approaching the potential
242
+		 * limits for the server.
243
+		 */
244
+		if (! empty($data['input_count'])) {
245
+			$response['max_input_vars_check'] = EE_Registry::instance()->CFG->environment->max_input_vars_limit_check(
246
+				$data['input_count']
247
+			);
248
+		}
249
+		return $response;
250
+	}
251
+
252
+
253
+	/**
254
+	 * Add per page screen options to the default ticket list table view.
255
+	 */
256
+	protected function _add_screen_options_ticket_list_table()
257
+	{
258
+		$this->_per_page_screen_option();
259
+	}
260
+
261
+
262
+	/**
263
+	 * @param string $return
264
+	 * @param int    $id
265
+	 * @param string $new_title
266
+	 * @param string $new_slug
267
+	 * @return string
268
+	 */
269
+	public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
270
+	{
271
+		$return = parent::extra_permalink_field_buttons($return, $id, $new_title, $new_slug);
272
+		//make sure this is only when editing
273
+		if (! empty($id)) {
274
+			$href   = EE_Admin_Page::add_query_args_and_nonce(
275
+				array('action' => 'duplicate_event', 'EVT_ID' => $id),
276
+				$this->_admin_base_url
277
+			);
278
+			$title  = esc_attr__('Duplicate Event', 'event_espresso');
279
+			$return .= '<a href="'
280
+					   . $href
281
+					   . '" title="'
282
+					   . $title
283
+					   . '" id="ee-duplicate-event-button" class="button button-small"  value="duplicate_event">'
284
+					   . $title
285
+					   . '</button>';
286
+		}
287
+		return $return;
288
+	}
289
+
290
+
291
+	/**
292
+	 * Set the list table views for the default ticket list table view.
293
+	 */
294
+	public function _set_list_table_views_ticket_list_table()
295
+	{
296
+		$this->_views = array(
297
+			'all'     => array(
298
+				'slug'        => 'all',
299
+				'label'       => esc_html__('All', 'event_espresso'),
300
+				'count'       => 0,
301
+				'bulk_action' => array(
302
+					'trash_tickets' => esc_html__('Move to Trash', 'event_espresso'),
303
+				),
304
+			),
305
+			'trashed' => array(
306
+				'slug'        => 'trashed',
307
+				'label'       => esc_html__('Trash', 'event_espresso'),
308
+				'count'       => 0,
309
+				'bulk_action' => array(
310
+					'restore_tickets' => esc_html__('Restore from Trash', 'event_espresso'),
311
+					'delete_tickets'  => esc_html__('Delete Permanently', 'event_espresso'),
312
+				),
313
+			),
314
+		);
315
+	}
316
+
317
+
318
+	/**
319
+	 * Enqueue scripts and styles for the event editor.
320
+	 */
321
+	public function load_scripts_styles_edit()
322
+	{
323
+		wp_register_script(
324
+			'ee-event-editor-heartbeat',
325
+			EVENTS_CAF_ASSETS_URL . 'event-editor-heartbeat.js',
326
+			array('ee_admin_js', 'heartbeat'),
327
+			EVENT_ESPRESSO_VERSION,
328
+			true
329
+		);
330
+		wp_enqueue_script('ee-accounting');
331
+		//styles
332
+		wp_enqueue_style('espresso-ui-theme');
333
+		wp_enqueue_script('event_editor_js');
334
+		wp_enqueue_script('ee-event-editor-heartbeat');
335
+	}
336
+
337
+
338
+	/**
339
+	 * Returns template for the additional datetime.
340
+	 * @param $template
341
+	 * @param $template_args
342
+	 * @return mixed
343
+	 * @throws DomainException
344
+	 */
345
+	public function add_additional_datetime_button($template, $template_args)
346
+	{
347
+		return EEH_Template::display_template(
348
+			EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_add_additional_time.template.php',
349
+			$template_args,
350
+			true
351
+		);
352
+	}
353
+
354
+
355
+	/**
356
+	 * Returns the template for cloning a datetime.
357
+	 * @param $template
358
+	 * @param $template_args
359
+	 * @return mixed
360
+	 * @throws DomainException
361
+	 */
362
+	public function add_datetime_clone_button($template, $template_args)
363
+	{
364
+		return EEH_Template::display_template(
365
+			EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_metabox_clone_button.template.php',
366
+			$template_args,
367
+			true
368
+		);
369
+	}
370
+
371
+
372
+	/**
373
+	 * Returns the template for datetime timezones.
374
+	 * @param $template
375
+	 * @param $template_args
376
+	 * @return mixed
377
+	 * @throws DomainException
378
+	 */
379
+	public function datetime_timezones_template($template, $template_args)
380
+	{
381
+		return EEH_Template::display_template(
382
+			EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_timezones.template.php',
383
+			$template_args,
384
+			true
385
+		);
386
+	}
387
+
388
+
389
+	/**
390
+	 * Sets the views for the default list table view.
391
+	 */
392
+	protected function _set_list_table_views_default()
393
+	{
394
+		parent::_set_list_table_views_default();
395
+		$new_views    = array(
396
+			'today' => array(
397
+				'slug'        => 'today',
398
+				'label'       => esc_html__('Today', 'event_espresso'),
399
+				'count'       => $this->total_events_today(),
400
+				'bulk_action' => array(
401
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
402
+				),
403
+			),
404
+			'month' => array(
405
+				'slug'        => 'month',
406
+				'label'       => esc_html__('This Month', 'event_espresso'),
407
+				'count'       => $this->total_events_this_month(),
408
+				'bulk_action' => array(
409
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
410
+				),
411
+			),
412
+		);
413
+		$this->_views = array_merge($this->_views, $new_views);
414
+	}
415
+
416
+
417
+	/**
418
+	 * Returns the extra action links for the default list table view.
419
+	 * @param array     $action_links
420
+	 * @param \EE_Event $event
421
+	 * @return array
422
+	 * @throws EE_Error
423
+	 */
424
+	public function extra_list_table_actions(array $action_links, \EE_Event $event)
425
+	{
426
+		if (EE_Registry::instance()->CAP->current_user_can(
427
+			'ee_read_registrations',
428
+			'espresso_registrations_reports',
429
+			$event->ID()
430
+		)
431
+		) {
432
+			$reports_query_args = array(
433
+				'action' => 'reports',
434
+				'EVT_ID' => $event->ID(),
435
+			);
436
+			$reports_link       = EE_Admin_Page::add_query_args_and_nonce($reports_query_args, REG_ADMIN_URL);
437
+			$action_links[]     = '<a href="'
438
+								  . $reports_link
439
+								  . '" title="'
440
+								  . esc_attr__('View Report', 'event_espresso')
441
+								  . '"><div class="dashicons dashicons-chart-bar"></div></a>'
442
+								  . "\n\t";
443
+		}
444
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
445
+			EE_Registry::instance()->load_helper('MSG_Template');
446
+			$action_links[] = EEH_MSG_Template::get_message_action_link(
447
+				'see_notifications_for',
448
+				null,
449
+				array('EVT_ID' => $event->ID())
450
+			);
451
+		}
452
+		return $action_links;
453
+	}
454
+
455
+
456
+	/**
457
+	 * @param $items
458
+	 * @return mixed
459
+	 */
460
+	public function additional_legend_items($items)
461
+	{
462
+		if (EE_Registry::instance()->CAP->current_user_can(
463
+			'ee_read_registrations',
464
+			'espresso_registrations_reports'
465
+		)
466
+		) {
467
+			$items['reports'] = array(
468
+				'class' => 'dashicons dashicons-chart-bar',
469
+				'desc'  => esc_html__('Event Reports', 'event_espresso'),
470
+			);
471
+		}
472
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
473
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
474
+			if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
475
+				$items['view_related_messages'] = array(
476
+					'class' => $related_for_icon['css_class'],
477
+					'desc'  => $related_for_icon['label'],
478
+				);
479
+			}
480
+		}
481
+		return $items;
482
+	}
483
+
484
+
485
+	/**
486
+	 * This is the callback method for the duplicate event route
487
+	 * Method looks for 'EVT_ID' in the request and retrieves that event and its details and duplicates them
488
+	 * into a new event.  We add a hook so that any plugins that add extra event details can hook into this
489
+	 * action.  Note that the dupe will have **DUPLICATE** as its title and slug.
490
+	 * After duplication the redirect is to the new event edit page.
491
+	 *
492
+	 * @return void
493
+	 * @access protected
494
+	 * @throws EE_Error If EE_Event is not available with given ID
495
+	 */
496
+	protected function _duplicate_event()
497
+	{
498
+		// first make sure the ID for the event is in the request.
499
+		//  If it isn't then we need to bail and redirect back to overview list table (cause how did we get here?)
500
+		if (! isset($this->_req_data['EVT_ID'])) {
501
+			EE_Error::add_error(
502
+				esc_html__(
503
+					'In order to duplicate an event an Event ID is required.  None was given.',
504
+					'event_espresso'
505
+				),
506
+				__FILE__,
507
+				__FUNCTION__,
508
+				__LINE__
509
+			);
510
+			$this->_redirect_after_action(false, '', '', array(), true);
511
+			return;
512
+		}
513
+		//k we've got EVT_ID so let's use that to get the event we'll duplicate
514
+		$orig_event = EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']);
515
+		if (! $orig_event instanceof EE_Event) {
516
+			throw new EE_Error(
517
+				sprintf(
518
+					esc_html__('An EE_Event object could not be retrieved for the given ID (%s)', 'event_espresso'),
519
+					$this->_req_data['EVT_ID']
520
+				)
521
+			);
522
+		}
523
+		//k now let's clone the $orig_event before getting relations
524
+		$new_event = clone $orig_event;
525
+		//original datetimes
526
+		$orig_datetimes = $orig_event->get_many_related('Datetime');
527
+		//other original relations
528
+		$orig_ven = $orig_event->get_many_related('Venue');
529
+		//reset the ID and modify other details to make it clear this is a dupe
530
+		$new_event->set('EVT_ID', 0);
531
+		$new_name = $new_event->name() . ' ' . esc_html__('**DUPLICATE**', 'event_espresso');
532
+		$new_event->set('EVT_name', $new_name);
533
+		$new_event->set(
534
+			'EVT_slug',
535
+			wp_unique_post_slug(
536
+				sanitize_title($orig_event->name()),
537
+				0,
538
+				'publish',
539
+				'espresso_events',
540
+				0
541
+			)
542
+		);
543
+		$new_event->set('status', 'draft');
544
+		//duplicate discussion settings
545
+		$new_event->set('comment_status', $orig_event->get('comment_status'));
546
+		$new_event->set('ping_status', $orig_event->get('ping_status'));
547
+		//save the new event
548
+		$new_event->save();
549
+		//venues
550
+		foreach ($orig_ven as $ven) {
551
+			$new_event->_add_relation_to($ven, 'Venue');
552
+		}
553
+		$new_event->save();
554
+		//now we need to get the question group relations and handle that
555
+		//first primary question groups
556
+		$orig_primary_qgs = $orig_event->get_many_related(
557
+			'Question_Group',
558
+			array(array('Event_Question_Group.EQG_primary' => 1))
559
+		);
560
+		if (! empty($orig_primary_qgs)) {
561
+			foreach ($orig_primary_qgs as $id => $obj) {
562
+				if ($obj instanceof EE_Question_Group) {
563
+					$new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 1));
564
+				}
565
+			}
566
+		}
567
+		//next additional attendee question groups
568
+		$orig_additional_qgs = $orig_event->get_many_related(
569
+			'Question_Group',
570
+			array(array('Event_Question_Group.EQG_primary' => 0))
571
+		);
572
+		if (! empty($orig_additional_qgs)) {
573
+			foreach ($orig_additional_qgs as $id => $obj) {
574
+				if ($obj instanceof EE_Question_Group) {
575
+					$new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 0));
576
+				}
577
+			}
578
+		}
579
+
580
+		$new_event->save();
581
+
582
+		//k now that we have the new event saved we can loop through the datetimes and start adding relations.
583
+		$cloned_tickets = array();
584
+		foreach ($orig_datetimes as $orig_dtt) {
585
+			if (! $orig_dtt instanceof EE_Datetime) {
586
+				continue;
587
+			}
588
+			$new_dtt   = clone $orig_dtt;
589
+			$orig_tkts = $orig_dtt->tickets();
590
+			//save new dtt then add to event
591
+			$new_dtt->set('DTT_ID', 0);
592
+			$new_dtt->set('DTT_sold', 0);
593
+			$new_dtt->set_reserved(0);
594
+			$new_dtt->save();
595
+			$new_event->_add_relation_to($new_dtt, 'Datetime');
596
+			$new_event->save();
597
+			//now let's get the ticket relations setup.
598
+			foreach ((array)$orig_tkts as $orig_tkt) {
599
+				//it's possible a datetime will have no tickets so let's verify we HAVE a ticket first.
600
+				if (! $orig_tkt instanceof EE_Ticket) {
601
+					continue;
602
+				}
603
+				//is this ticket archived?  If it is then let's skip
604
+				if ($orig_tkt->get('TKT_deleted')) {
605
+					continue;
606
+				}
607
+				// does this original ticket already exist in the clone_tickets cache?
608
+				//  If so we'll just use the new ticket from it.
609
+				if (isset($cloned_tickets[$orig_tkt->ID()])) {
610
+					$new_tkt = $cloned_tickets[$orig_tkt->ID()];
611
+				} else {
612
+					$new_tkt = clone $orig_tkt;
613
+					//get relations on the $orig_tkt that we need to setup.
614
+					$orig_prices = $orig_tkt->prices();
615
+					$new_tkt->set('TKT_ID', 0);
616
+					$new_tkt->set('TKT_sold', 0);
617
+					$new_tkt->set('TKT_reserved', 0);
618
+					$new_tkt->save(); //make sure new ticket has ID.
619
+					//price relations on new ticket need to be setup.
620
+					foreach ($orig_prices as $orig_price) {
621
+						$new_price = clone $orig_price;
622
+						$new_price->set('PRC_ID', 0);
623
+						$new_price->save();
624
+						$new_tkt->_add_relation_to($new_price, 'Price');
625
+						$new_tkt->save();
626
+					}
627
+
628
+					do_action(
629
+						'AHEE__Extend_Events_Admin_Page___duplicate_event__duplicate_ticket__after',
630
+						$orig_tkt,
631
+						$new_tkt,
632
+						$orig_prices,
633
+						$orig_event,
634
+						$orig_dtt,
635
+						$new_dtt
636
+					);
637
+				}
638
+				// k now we can add the new ticket as a relation to the new datetime
639
+				// and make sure its added to our cached $cloned_tickets array
640
+				// for use with later datetimes that have the same ticket.
641
+				$new_dtt->_add_relation_to($new_tkt, 'Ticket');
642
+				$new_dtt->save();
643
+				$cloned_tickets[$orig_tkt->ID()] = $new_tkt;
644
+			}
645
+		}
646
+		//clone taxonomy information
647
+		$taxonomies_to_clone_with = apply_filters(
648
+			'FHEE__Extend_Events_Admin_Page___duplicate_event__taxonomies_to_clone',
649
+			array('espresso_event_categories', 'espresso_event_type', 'post_tag')
650
+		);
651
+		//get terms for original event (notice)
652
+		$orig_terms = wp_get_object_terms($orig_event->ID(), $taxonomies_to_clone_with);
653
+		//loop through terms and add them to new event.
654
+		foreach ($orig_terms as $term) {
655
+			wp_set_object_terms($new_event->ID(), $term->term_id, $term->taxonomy, true);
656
+		}
657
+
658
+		//duplicate other core WP_Post items for this event.
659
+		//post thumbnail (feature image).
660
+		$feature_image_id = get_post_thumbnail_id($orig_event->ID());
661
+		if ($feature_image_id) {
662
+			update_post_meta($new_event->ID(), '_thumbnail_id', $feature_image_id);
663
+		}
664
+
665
+		//duplicate page_template setting
666
+		$page_template = get_post_meta($orig_event->ID(), '_wp_page_template', true);
667
+		if ($page_template) {
668
+			update_post_meta($new_event->ID(), '_wp_page_template', $page_template);
669
+		}
670
+
671
+		do_action('AHEE__Extend_Events_Admin_Page___duplicate_event__after', $new_event, $orig_event);
672
+		//now let's redirect to the edit page for this duplicated event if we have a new event id.
673
+		if ($new_event->ID()) {
674
+			$redirect_args = array(
675
+				'post'   => $new_event->ID(),
676
+				'action' => 'edit',
677
+			);
678
+			EE_Error::add_success(
679
+				esc_html__(
680
+					'Event successfully duplicated.  Please review the details below and make any necessary edits',
681
+					'event_espresso'
682
+				)
683
+			);
684
+		} else {
685
+			$redirect_args = array(
686
+				'action' => 'default',
687
+			);
688
+			EE_Error::add_error(
689
+				esc_html__('Not able to duplicate event.  Something went wrong.', 'event_espresso'),
690
+				__FILE__,
691
+				__FUNCTION__,
692
+				__LINE__
693
+			);
694
+		}
695
+		$this->_redirect_after_action(false, '', '', $redirect_args, true);
696
+	}
697
+
698
+
699
+	/**
700
+	 * Generates output for the import page.
701
+	 * @throws DomainException
702
+	 */
703
+	protected function _import_page()
704
+	{
705
+		$title                                      = esc_html__('Import', 'event_espresso');
706
+		$intro                                      = esc_html__(
707
+			'If you have a previously exported Event Espresso 4 information in a Comma Separated Value (CSV) file format, you can upload the file here: ',
708
+			'event_espresso'
709
+		);
710
+		$form_url                                   = EVENTS_ADMIN_URL;
711
+		$action                                     = 'import_events';
712
+		$type                                       = 'csv';
713
+		$this->_template_args['form']               = EE_Import::instance()->upload_form(
714
+			$title, $intro, $form_url, $action, $type
715
+		);
716
+		$this->_template_args['sample_file_link']   = EE_Admin_Page::add_query_args_and_nonce(
717
+			array('action' => 'sample_export_file'),
718
+			$this->_admin_base_url
719
+		);
720
+		$content                                    = EEH_Template::display_template(
721
+			EVENTS_CAF_TEMPLATE_PATH . 'import_page.template.php',
722
+			$this->_template_args,
723
+			true
724
+		);
725
+		$this->_template_args['admin_page_content'] = $content;
726
+		$this->display_admin_page_with_sidebar();
727
+	}
728
+
729
+
730
+	/**
731
+	 * _import_events
732
+	 * This handles displaying the screen and running imports for importing events.
733
+	 *
734
+	 * @return void
735
+	 */
736
+	protected function _import_events()
737
+	{
738
+		require_once(EE_CLASSES . 'EE_Import.class.php');
739
+		$success = EE_Import::instance()->import();
740
+		$this->_redirect_after_action($success, 'Import File', 'ran', array('action' => 'import_page'), true);
741
+	}
742
+
743
+
744
+	/**
745
+	 * _events_export
746
+	 * Will export all (or just the given event) to a Excel compatible file.
747
+	 *
748
+	 * @access protected
749
+	 * @return void
750
+	 */
751
+	protected function _events_export()
752
+	{
753
+		if (isset($this->_req_data['EVT_ID'])) {
754
+			$event_ids = $this->_req_data['EVT_ID'];
755
+		} elseif (isset($this->_req_data['EVT_IDs'])) {
756
+			$event_ids = $this->_req_data['EVT_IDs'];
757
+		} else {
758
+			$event_ids = null;
759
+		}
760
+		//todo: I don't like doing this but it'll do until we modify EE_Export Class.
761
+		$new_request_args = array(
762
+			'export' => 'report',
763
+			'action' => 'all_event_data',
764
+			'EVT_ID' => $event_ids,
765
+		);
766
+		$this->_req_data  = array_merge($this->_req_data, $new_request_args);
767
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
768
+			require_once(EE_CLASSES . 'EE_Export.class.php');
769
+			$EE_Export = EE_Export::instance($this->_req_data);
770
+			$EE_Export->export();
771
+		}
772
+	}
773
+
774
+
775
+	/**
776
+	 * handle category exports()
777
+	 *
778
+	 * @return void
779
+	 */
780
+	protected function _categories_export()
781
+	{
782
+		//todo: I don't like doing this but it'll do until we modify EE_Export Class.
783
+		$new_request_args = array(
784
+			'export'       => 'report',
785
+			'action'       => 'categories',
786
+			'category_ids' => $this->_req_data['EVT_CAT_ID'],
787
+		);
788
+		$this->_req_data  = array_merge($this->_req_data, $new_request_args);
789
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
790
+			require_once(EE_CLASSES . 'EE_Export.class.php');
791
+			$EE_Export = EE_Export::instance($this->_req_data);
792
+			$EE_Export->export();
793
+		}
794
+	}
795
+
796
+
797
+	/**
798
+	 * Creates a sample CSV file for importing
799
+	 */
800
+	protected function _sample_export_file()
801
+	{
802
+		//		require_once(EE_CLASSES . 'EE_Export.class.php');
803
+		EE_Export::instance()->export_sample();
804
+	}
805
+
806
+
807
+	/*************        Template Settings        *************/
808
+	/**
809
+	 * Generates template settings page output
810
+	 * @throws DomainException
811
+	 * @throws EE_Error
812
+	 */
813
+	protected function _template_settings()
814
+	{
815
+		$this->_template_args['values'] = $this->_yes_no_values;
816
+		/**
817
+		 * Note leaving this filter in for backward compatibility this was moved in 4.6.x
818
+		 * from General_Settings_Admin_Page to here.
819
+		 */
820
+		$this->_template_args = apply_filters(
821
+			'FHEE__General_Settings_Admin_Page__template_settings__template_args',
822
+			$this->_template_args
823
+		);
824
+		$this->_set_add_edit_form_tags('update_template_settings');
825
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
826
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
827
+			EVENTS_CAF_TEMPLATE_PATH . 'template_settings.template.php',
828
+			$this->_template_args,
829
+			true
830
+		);
831
+		$this->display_admin_page_with_sidebar();
832
+	}
833
+
834
+
835
+	/**
836
+	 * Handler for updating template settings.
837
+	 */
838
+	protected function _update_template_settings()
839
+	{
840
+		/**
841
+		 * Note leaving this filter in for backward compatibility this was moved in 4.6.x
842
+		 * from General_Settings_Admin_Page to here.
843
+		 */
844
+		EE_Registry::instance()->CFG->template_settings = apply_filters(
845
+			'FHEE__General_Settings_Admin_Page__update_template_settings__data',
846
+			EE_Registry::instance()->CFG->template_settings,
847
+			$this->_req_data
848
+		);
849
+		//update custom post type slugs and detect if we need to flush rewrite rules
850
+		$old_slug                                          = EE_Registry::instance()->CFG->core->event_cpt_slug;
851
+		EE_Registry::instance()->CFG->core->event_cpt_slug = empty($this->_req_data['event_cpt_slug'])
852
+			? EE_Registry::instance()->CFG->core->event_cpt_slug
853
+			: sanitize_title_with_dashes($this->_req_data['event_cpt_slug']);
854
+		$what                                              = 'Template Settings';
855
+		$success                                           = $this->_update_espresso_configuration(
856
+			$what,
857
+			EE_Registry::instance()->CFG->template_settings,
858
+			__FILE__,
859
+			__FUNCTION__,
860
+			__LINE__
861
+		);
862
+		if (EE_Registry::instance()->CFG->core->event_cpt_slug != $old_slug) {
863
+			update_option('ee_flush_rewrite_rules', true);
864
+		}
865
+		$this->_redirect_after_action($success, $what, 'updated', array('action' => 'template_settings'));
866
+	}
867
+
868
+
869
+	/**
870
+	 * _premium_event_editor_meta_boxes
871
+	 * add all metaboxes related to the event_editor
872
+	 *
873
+	 * @access protected
874
+	 * @return void
875
+	 * @throws EE_Error
876
+	 */
877
+	protected function _premium_event_editor_meta_boxes()
878
+	{
879
+		$this->verify_cpt_object();
880
+		add_meta_box(
881
+			'espresso_event_editor_event_options',
882
+			esc_html__('Event Registration Options', 'event_espresso'),
883
+			array($this, 'registration_options_meta_box'),
884
+			$this->page_slug,
885
+			'side',
886
+			'core'
887
+		);
888
+	}
889
+
890
+
891
+	/**
892
+	 * override caf metabox
893
+	 *
894
+	 * @return void
895
+	 * @throws DomainException
896
+	 */
897
+	public function registration_options_meta_box()
898
+	{
899
+		$yes_no_values                                    = array(
900
+			array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
901
+			array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
902
+		);
903
+		$default_reg_status_values                        = EEM_Registration::reg_status_array(
904
+			array(
905
+				EEM_Registration::status_id_cancelled,
906
+				EEM_Registration::status_id_declined,
907
+				EEM_Registration::status_id_incomplete,
908
+				EEM_Registration::status_id_wait_list,
909
+			),
910
+			true
911
+		);
912
+		$template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
913
+		$template_args['_event']                          = $this->_cpt_model_obj;
914
+		$template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
915
+		$template_args['default_registration_status']     = EEH_Form_Fields::select_input(
916
+			'default_reg_status',
917
+			$default_reg_status_values,
918
+			$this->_cpt_model_obj->default_registration_status()
919
+		);
920
+		$template_args['display_description']             = EEH_Form_Fields::select_input(
921
+			'display_desc',
922
+			$yes_no_values,
923
+			$this->_cpt_model_obj->display_description()
924
+		);
925
+		$template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
926
+			'display_ticket_selector',
927
+			$yes_no_values,
928
+			$this->_cpt_model_obj->display_ticket_selector(),
929
+			'',
930
+			'',
931
+			false
932
+		);
933
+		$template_args['EVT_default_registration_status'] = EEH_Form_Fields::select_input(
934
+			'EVT_default_registration_status',
935
+			$default_reg_status_values,
936
+			$this->_cpt_model_obj->default_registration_status()
937
+		);
938
+		$template_args['additional_registration_options'] = apply_filters(
939
+			'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
940
+			'',
941
+			$template_args,
942
+			$yes_no_values,
943
+			$default_reg_status_values
944
+		);
945
+		EEH_Template::display_template(
946
+			EVENTS_CAF_TEMPLATE_PATH . 'event_registration_options.template.php',
947
+			$template_args
948
+		);
949
+	}
950
+
951
+
952
+
953
+	/**
954
+	 * wp_list_table_mods for caf
955
+	 * ============================
956
+	 */
957
+	/**
958
+	 * hook into list table filters and provide filters for caffeinated list table
959
+	 *
960
+	 * @param  array $old_filters    any existing filters present
961
+	 * @param  array $list_table_obj the list table object
962
+	 * @return array                  new filters
963
+	 */
964
+	public function list_table_filters($old_filters, $list_table_obj)
965
+	{
966
+		$filters = array();
967
+		//first month/year filters
968
+		$filters[] = $this->espresso_event_months_dropdown();
969
+		$status    = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
970
+		//active status dropdown
971
+		if ($status !== 'draft') {
972
+			$filters[] = $this->active_status_dropdown(
973
+				isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : ''
974
+			);
975
+		}
976
+		//category filter
977
+		$filters[] = $this->category_dropdown();
978
+		return array_merge($old_filters, $filters);
979
+	}
980
+
981
+
982
+	/**
983
+	 * espresso_event_months_dropdown
984
+	 *
985
+	 * @access public
986
+	 * @return string                dropdown listing month/year selections for events.
987
+	 */
988
+	public function espresso_event_months_dropdown()
989
+	{
990
+		// what we need to do is get all PRIMARY datetimes for all events to filter on.
991
+		// Note we need to include any other filters that are set!
992
+		$status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
993
+		//categories?
994
+		$category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
995
+			? $this->_req_data['EVT_CAT']
996
+			: null;
997
+		//active status?
998
+		$active_status = isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : null;
999
+		$cur_date      = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
1000
+		return EEH_Form_Fields::generate_event_months_dropdown($cur_date, $status, $category, $active_status);
1001
+	}
1002
+
1003
+
1004
+	/**
1005
+	 * returns a list of "active" statuses on the event
1006
+	 *
1007
+	 * @param  string $current_value whatever the current active status is
1008
+	 * @return string
1009
+	 */
1010
+	public function active_status_dropdown($current_value = '')
1011
+	{
1012
+		$select_name = 'active_status';
1013
+		$values      = array(
1014
+			'none'     => esc_html__('Show Active/Inactive', 'event_espresso'),
1015
+			'active'   => esc_html__('Active', 'event_espresso'),
1016
+			'upcoming' => esc_html__('Upcoming', 'event_espresso'),
1017
+			'expired'  => esc_html__('Expired', 'event_espresso'),
1018
+			'inactive' => esc_html__('Inactive', 'event_espresso'),
1019
+		);
1020
+		$id          = 'id="espresso-active-status-dropdown-filter"';
1021
+		$class       = 'wide';
1022
+		return EEH_Form_Fields::select_input($select_name, $values, $current_value, $id, $class);
1023
+	}
1024
+
1025
+
1026
+	/**
1027
+	 * output a dropdown of the categories for the category filter on the event admin list table
1028
+	 *
1029
+	 * @access  public
1030
+	 * @return string html
1031
+	 */
1032
+	public function category_dropdown()
1033
+	{
1034
+		$cur_cat = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
1035
+		return EEH_Form_Fields::generate_event_category_dropdown($cur_cat);
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * get total number of events today
1041
+	 *
1042
+	 * @access public
1043
+	 * @return int
1044
+	 * @throws EE_Error
1045
+	 */
1046
+	public function total_events_today()
1047
+	{
1048
+		$start = EEM_Datetime::instance()->convert_datetime_for_query(
1049
+			'DTT_EVT_start',
1050
+			date('Y-m-d') . ' 00:00:00',
1051
+			'Y-m-d H:i:s',
1052
+			'UTC'
1053
+		);
1054
+		$end   = EEM_Datetime::instance()->convert_datetime_for_query(
1055
+			'DTT_EVT_start',
1056
+			date('Y-m-d') . ' 23:59:59',
1057
+			'Y-m-d H:i:s',
1058
+			'UTC'
1059
+		);
1060
+		$where = array(
1061
+			'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1062
+		);
1063
+		$count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1064
+		return $count;
1065
+	}
1066
+
1067
+
1068
+	/**
1069
+	 * get total number of events this month
1070
+	 *
1071
+	 * @access public
1072
+	 * @return int
1073
+	 * @throws EE_Error
1074
+	 */
1075
+	public function total_events_this_month()
1076
+	{
1077
+		//Dates
1078
+		$this_year_r     = date('Y');
1079
+		$this_month_r    = date('m');
1080
+		$days_this_month = date('t');
1081
+		$start           = EEM_Datetime::instance()->convert_datetime_for_query(
1082
+			'DTT_EVT_start',
1083
+			$this_year_r . '-' . $this_month_r . '-01 00:00:00',
1084
+			'Y-m-d H:i:s',
1085
+			'UTC'
1086
+		);
1087
+		$end             = EEM_Datetime::instance()->convert_datetime_for_query(
1088
+			'DTT_EVT_start',
1089
+			$this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' 23:59:59',
1090
+			'Y-m-d H:i:s',
1091
+			'UTC'
1092
+		);
1093
+		$where           = array(
1094
+			'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1095
+		);
1096
+		$count           = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1097
+		return $count;
1098
+	}
1099
+
1100
+
1101
+	/** DEFAULT TICKETS STUFF **/
1102
+
1103
+	/**
1104
+	 * Output default tickets list table view.
1105
+	 */
1106
+	public function _tickets_overview_list_table()
1107
+	{
1108
+		$this->_search_btn_label = esc_html__('Tickets', 'event_espresso');
1109
+		$this->display_admin_list_table_page_with_no_sidebar();
1110
+	}
1111
+
1112
+
1113
+	/**
1114
+	 * @param int  $per_page
1115
+	 * @param bool $count
1116
+	 * @param bool $trashed
1117
+	 * @return \EE_Soft_Delete_Base_Class[]|int
1118
+	 */
1119
+	public function get_default_tickets($per_page = 10, $count = false, $trashed = false)
1120
+	{
1121
+		$orderby = empty($this->_req_data['orderby']) ? 'TKT_name' : $this->_req_data['orderby'];
1122
+		$order   = empty($this->_req_data['order']) ? 'ASC' : $this->_req_data['order'];
1123
+		switch ($orderby) {
1124
+			case 'TKT_name':
1125
+				$orderby = array('TKT_name' => $order);
1126
+				break;
1127
+			case 'TKT_price':
1128
+				$orderby = array('TKT_price' => $order);
1129
+				break;
1130
+			case 'TKT_uses':
1131
+				$orderby = array('TKT_uses' => $order);
1132
+				break;
1133
+			case 'TKT_min':
1134
+				$orderby = array('TKT_min' => $order);
1135
+				break;
1136
+			case 'TKT_max':
1137
+				$orderby = array('TKT_max' => $order);
1138
+				break;
1139
+			case 'TKT_qty':
1140
+				$orderby = array('TKT_qty' => $order);
1141
+				break;
1142
+		}
1143
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1144
+			? $this->_req_data['paged']
1145
+			: 1;
1146
+		$per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1147
+			? $this->_req_data['perpage']
1148
+			: $per_page;
1149
+		$_where       = array(
1150
+			'TKT_is_default' => 1,
1151
+			'TKT_deleted'    => $trashed,
1152
+		);
1153
+		$offset       = ($current_page - 1) * $per_page;
1154
+		$limit        = array($offset, $per_page);
1155
+		if (isset($this->_req_data['s'])) {
1156
+			$sstr         = '%' . $this->_req_data['s'] . '%';
1157
+			$_where['OR'] = array(
1158
+				'TKT_name'        => array('LIKE', $sstr),
1159
+				'TKT_description' => array('LIKE', $sstr),
1160
+			);
1161
+		}
1162
+		$query_params = array(
1163
+			$_where,
1164
+			'order_by' => $orderby,
1165
+			'limit'    => $limit,
1166
+			'group_by' => 'TKT_ID',
1167
+		);
1168
+		if ($count) {
1169
+			return EEM_Ticket::instance()->count_deleted_and_undeleted(array($_where));
1170
+		} else {
1171
+			return EEM_Ticket::instance()->get_all_deleted_and_undeleted($query_params);
1172
+		}
1173
+	}
1174
+
1175
+
1176
+	/**
1177
+	 * @param bool $trash
1178
+	 * @throws EE_Error
1179
+	 */
1180
+	protected function _trash_or_restore_ticket($trash = false)
1181
+	{
1182
+		$success = 1;
1183
+		$TKT     = EEM_Ticket::instance();
1184
+		//checkboxes?
1185
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1186
+			//if array has more than one element then success message should be plural
1187
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1188
+			//cycle thru the boxes
1189
+			while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1190
+				if ($trash) {
1191
+					if (! $TKT->delete_by_ID($TKT_ID)) {
1192
+						$success = 0;
1193
+					}
1194
+				} else {
1195
+					if (! $TKT->restore_by_ID($TKT_ID)) {
1196
+						$success = 0;
1197
+					}
1198
+				}
1199
+			}
1200
+		} else {
1201
+			//grab single id and trash
1202
+			$TKT_ID = absint($this->_req_data['TKT_ID']);
1203
+			if ($trash) {
1204
+				if (! $TKT->delete_by_ID($TKT_ID)) {
1205
+					$success = 0;
1206
+				}
1207
+			} else {
1208
+				if (! $TKT->restore_by_ID($TKT_ID)) {
1209
+					$success = 0;
1210
+				}
1211
+			}
1212
+		}
1213
+		$action_desc = $trash ? 'moved to the trash' : 'restored';
1214
+		$query_args  = array(
1215
+			'action' => 'ticket_list_table',
1216
+			'status' => $trash ? '' : 'trashed',
1217
+		);
1218
+		$this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1219
+	}
1220
+
1221
+
1222
+	/**
1223
+	 * Handles trashing default ticket.
1224
+	 */
1225
+	protected function _delete_ticket()
1226
+	{
1227
+		$success = 1;
1228
+		//checkboxes?
1229
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1230
+			//if array has more than one element then success message should be plural
1231
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1232
+			//cycle thru the boxes
1233
+			while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1234
+				//delete
1235
+				if (! $this->_delete_the_ticket($TKT_ID)) {
1236
+					$success = 0;
1237
+				}
1238
+			}
1239
+		} else {
1240
+			//grab single id and trash
1241
+			$TKT_ID = absint($this->_req_data['TKT_ID']);
1242
+			if (! $this->_delete_the_ticket($TKT_ID)) {
1243
+				$success = 0;
1244
+			}
1245
+		}
1246
+		$action_desc = 'deleted';
1247
+		$query_args  = array(
1248
+			'action' => 'ticket_list_table',
1249
+			'status' => 'trashed',
1250
+		);
1251
+		//fail safe.  If the default ticket count === 1 then we need to redirect to event overview.
1252
+		if (EEM_Ticket::instance()->count_deleted_and_undeleted(
1253
+			array(array('TKT_is_default' => 1)),
1254
+			'TKT_ID',
1255
+			true
1256
+		)
1257
+		) {
1258
+			$query_args = array();
1259
+		}
1260
+		$this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1261
+	}
1262
+
1263
+
1264
+	/**
1265
+	 * @param int $TKT_ID
1266
+	 * @return bool|int
1267
+	 * @throws EE_Error
1268
+	 */
1269
+	protected function _delete_the_ticket($TKT_ID)
1270
+	{
1271
+		$tkt = EEM_Ticket::instance()->get_one_by_ID($TKT_ID);
1272
+		$tkt->_remove_relations('Datetime');
1273
+		//delete all related prices first
1274
+		$tkt->delete_related_permanently('Price');
1275
+		return $tkt->delete_permanently();
1276
+	}
1277 1277
 }
Please login to merge, or discard this patch.
modules/ticket_selector/DisplayTicketSelector.php 1 patch
Indentation   +680 added lines, -680 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
 use WP_Post;
18 18
 
19 19
 if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
20
-    exit( 'No direct script access allowed' );
20
+	exit( 'No direct script access allowed' );
21 21
 }
22 22
 
23 23
 
@@ -34,688 +34,688 @@  discard block
 block discarded – undo
34 34
 class DisplayTicketSelector
35 35
 {
36 36
 
37
-    /**
38
-     * event that ticket selector is being generated for
39
-     *
40
-     * @access protected
41
-     * @var EE_Event $event
42
-     */
43
-    protected $event;
44
-
45
-    /**
46
-     * Used to flag when the ticket selector is being called from an external iframe.
47
-     *
48
-     * @var bool $iframe
49
-     */
50
-    protected $iframe = false;
51
-
52
-    /**
53
-     * max attendees that can register for event at one time
54
-     *
55
-     * @var int $max_attendees
56
-     */
57
-    private $max_attendees = EE_INF;
58
-
59
-    /**
60
-     *@var string $date_format
61
-     */
62
-    private $date_format;
63
-
64
-    /**
65
-     *@var string $time_format
66
-     */
67
-    private $time_format;
68
-
69
-
70
-
71
-    /**
72
-     * DisplayTicketSelector constructor.
73
-     */
74
-    public function __construct()
75
-    {
76
-        $this->date_format = apply_filters(
77
-            'FHEE__EED_Ticket_Selector__display_ticket_selector__date_format',
78
-            get_option('date_format')
79
-        );
80
-        $this->time_format = apply_filters(
81
-            'FHEE__EED_Ticket_Selector__display_ticket_selector__time_format',
82
-            get_option('time_format')
83
-        );
84
-    }
85
-
86
-
87
-
88
-    /**
89
-     * @param boolean $iframe
90
-     */
91
-    public function setIframe( $iframe = true )
92
-    {
93
-        $this->iframe = filter_var( $iframe, FILTER_VALIDATE_BOOLEAN );
94
-    }
95
-
96
-
97
-    /**
98
-     * finds and sets the \EE_Event object for use throughout class
99
-     *
100
-     * @param mixed $event
101
-     * @return bool
102
-     * @throws EE_Error
103
-     */
104
-    protected function setEvent( $event = null )
105
-    {
106
-        if ( $event === null ) {
107
-            global $post;
108
-            $event = $post;
109
-        }
110
-        if ( $event instanceof EE_Event ) {
111
-            $this->event = $event;
112
-        } else if ( $event instanceof WP_Post ) {
113
-            if ( isset( $event->EE_Event ) && $event->EE_Event instanceof EE_Event ) {
114
-                $this->event = $event->EE_Event;
115
-            } else if ( $event->post_type === 'espresso_events' ) {
116
-                $event->EE_Event = EEM_Event::instance()->instantiate_class_from_post_object( $event );
117
-                $this->event = $event->EE_Event;
118
-            }
119
-        } else {
120
-            $user_msg = __( 'No Event object or an invalid Event object was supplied.', 'event_espresso' );
121
-            $dev_msg = $user_msg . __(
122
-                    'In order to generate a ticket selector, please ensure you are passing either an EE_Event object or a WP_Post object of the post type "espresso_event" to the EE_Ticket_Selector class constructor.',
123
-                    'event_espresso'
124
-                );
125
-            EE_Error::add_error( $user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__ );
126
-            return false;
127
-        }
128
-        return true;
129
-    }
130
-
131
-
132
-
133
-    /**
134
-     * @return int
135
-     */
136
-    public function getMaxAttendees()
137
-    {
138
-        return $this->max_attendees;
139
-    }
140
-
141
-
142
-
143
-    /**
144
-     * @param int $max_attendees
145
-     */
146
-    public function setMaxAttendees($max_attendees)
147
-    {
148
-        $this->max_attendees = absint(
149
-            apply_filters(
150
-                'FHEE__EE_Ticket_Selector__display_ticket_selector__max_tickets',
151
-                $max_attendees
152
-            )
153
-        );
154
-    }
155
-
156
-
157
-
158
-    /**
159
-     * creates buttons for selecting number of attendees for an event
160
-     *
161
-     * @param WP_Post|int $event
162
-     * @param bool         $view_details
163
-     * @return string
164
-     * @throws EE_Error
165
-     */
166
-    public function display( $event = null, $view_details = false )
167
-    {
168
-        // reset filter for displaying submit button
169
-        remove_filter( 'FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true' );
170
-        // poke and prod incoming event till it tells us what it is
171
-        if ( ! $this->setEvent( $event ) ) {
172
-            return false;
173
-        }
174
-        // begin gathering template arguments by getting event status
175
-        $template_args = array( 'event_status' => $this->event->get_active_status() );
176
-        if ( $this->activeEventAndShowTicketSelector($event, $template_args['event_status'], $view_details) ) {
177
-            return ! is_single() ? $this->displayViewDetailsButton() : '';
178
-        }
179
-        // filter the maximum qty that can appear in the Ticket Selector qty dropdowns
180
-        $this->setMaxAttendees($this->event->additional_limit());
181
-        if ($this->getMaxAttendees() < 1) {
182
-            return $this->ticketSalesClosedMessage();
183
-        }
184
-        // is the event expired ?
185
-        $template_args['event_is_expired'] = $this->event->is_expired();
186
-        if ( $template_args[ 'event_is_expired' ] ) {
187
-            return $this->expiredEventMessage();
188
-        }
189
-        // get all tickets for this event ordered by the datetime
190
-        $tickets = $this->getTickets();
191
-        if (count($tickets) < 1) {
192
-            return $this->noTicketAvailableMessage();
193
-        }
194
-        if (EED_Events_Archive::is_iframe()){
195
-            $this->setIframe();
196
-        }
197
-        // redirecting to another site for registration ??
198
-        $external_url = (string) $this->event->external_url();
199
-        // if redirecting to another site for registration, then we don't load the TS
200
-        $ticket_selector = $external_url
201
-            ? $this->externalEventRegistration()
202
-            : $this->loadTicketSelector($tickets,$template_args);
203
-        // now set up the form (but not for the admin)
204
-        $ticket_selector = ! is_admin()
205
-            ? $this->formOpen($this->event->ID(), $external_url) . $ticket_selector
206
-            : $ticket_selector;
207
-        // submit button and form close tag
208
-        $ticket_selector .= ! is_admin() ? $this->displaySubmitButton($external_url) : '';
209
-        return $ticket_selector;
210
-    }
211
-
212
-
213
-
214
-    /**
215
-     * displayTicketSelector
216
-     * examines the event properties and determines whether a Ticket Selector should be displayed
217
-     *
218
-     * @param WP_Post|int $event
219
-     * @param string       $_event_active_status
220
-     * @param bool         $view_details
221
-     * @return bool
222
-     * @throws EE_Error
223
-     */
224
-    protected function activeEventAndShowTicketSelector($event, $_event_active_status, $view_details)
225
-    {
226
-        $event_post = $this->event instanceof EE_Event ? $this->event->ID() : $event;
227
-        return ! is_admin()
228
-               && (
229
-                   ! $this->event->display_ticket_selector()
230
-                   || $view_details
231
-                   || post_password_required($event_post)
232
-                   || (
233
-                       $_event_active_status !== EE_Datetime::active
234
-                       && $_event_active_status !== EE_Datetime::upcoming
235
-                       && $_event_active_status !== EE_Datetime::sold_out
236
-                       && ! (
237
-                           $_event_active_status === EE_Datetime::inactive
238
-                           && is_user_logged_in()
239
-                       )
240
-                   )
241
-               );
242
-    }
243
-
244
-
245
-
246
-    /**
247
-     * noTicketAvailableMessage
248
-     * notice displayed if event is expired
249
-     *
250
-     * @return string
251
-     * @throws EE_Error
252
-     */
253
-    protected function expiredEventMessage()
254
-    {
255
-        return '<div class="ee-event-expired-notice"><span class="important-notice">' . esc_html__(
256
-            'We\'re sorry, but all tickets sales have ended because the event is expired.',
257
-            'event_espresso'
258
-        ) . '</span></div><!-- .ee-event-expired-notice -->';
259
-    }
260
-
261
-
262
-
263
-    /**
264
-     * noTicketAvailableMessage
265
-     * notice displayed if event has no more tickets available
266
-     *
267
-     * @return string
268
-     * @throws EE_Error
269
-     */
270
-    protected function noTicketAvailableMessage()
271
-    {
272
-        $no_ticket_available_msg = esc_html__( 'We\'re sorry, but all ticket sales have ended.', 'event_espresso' );
273
-        if (current_user_can('edit_post', $this->event->ID())) {
274
-            $no_ticket_available_msg .= sprintf(
275
-                esc_html__(
276
-                    '%1$sNote to Event Admin:%2$sNo tickets were found for this event. This effectively turns off ticket sales. Please ensure that at least one ticket is available for if you want people to be able to register.%3$s(click to edit this event)%4$s',
277
-                    'event_espresso'
278
-                ),
279
-                '<div class="ee-attention" style="text-align: left;"><b>',
280
-                '</b><br />',
281
-                '<span class="edit-link"><a class="post-edit-link" href="'.get_edit_post_link($this->event->ID()).'">',
282
-                '</a></span></div><!-- .ee-attention noTicketAvailableMessage -->'
283
-            );
284
-        }
285
-        return '
37
+	/**
38
+	 * event that ticket selector is being generated for
39
+	 *
40
+	 * @access protected
41
+	 * @var EE_Event $event
42
+	 */
43
+	protected $event;
44
+
45
+	/**
46
+	 * Used to flag when the ticket selector is being called from an external iframe.
47
+	 *
48
+	 * @var bool $iframe
49
+	 */
50
+	protected $iframe = false;
51
+
52
+	/**
53
+	 * max attendees that can register for event at one time
54
+	 *
55
+	 * @var int $max_attendees
56
+	 */
57
+	private $max_attendees = EE_INF;
58
+
59
+	/**
60
+	 *@var string $date_format
61
+	 */
62
+	private $date_format;
63
+
64
+	/**
65
+	 *@var string $time_format
66
+	 */
67
+	private $time_format;
68
+
69
+
70
+
71
+	/**
72
+	 * DisplayTicketSelector constructor.
73
+	 */
74
+	public function __construct()
75
+	{
76
+		$this->date_format = apply_filters(
77
+			'FHEE__EED_Ticket_Selector__display_ticket_selector__date_format',
78
+			get_option('date_format')
79
+		);
80
+		$this->time_format = apply_filters(
81
+			'FHEE__EED_Ticket_Selector__display_ticket_selector__time_format',
82
+			get_option('time_format')
83
+		);
84
+	}
85
+
86
+
87
+
88
+	/**
89
+	 * @param boolean $iframe
90
+	 */
91
+	public function setIframe( $iframe = true )
92
+	{
93
+		$this->iframe = filter_var( $iframe, FILTER_VALIDATE_BOOLEAN );
94
+	}
95
+
96
+
97
+	/**
98
+	 * finds and sets the \EE_Event object for use throughout class
99
+	 *
100
+	 * @param mixed $event
101
+	 * @return bool
102
+	 * @throws EE_Error
103
+	 */
104
+	protected function setEvent( $event = null )
105
+	{
106
+		if ( $event === null ) {
107
+			global $post;
108
+			$event = $post;
109
+		}
110
+		if ( $event instanceof EE_Event ) {
111
+			$this->event = $event;
112
+		} else if ( $event instanceof WP_Post ) {
113
+			if ( isset( $event->EE_Event ) && $event->EE_Event instanceof EE_Event ) {
114
+				$this->event = $event->EE_Event;
115
+			} else if ( $event->post_type === 'espresso_events' ) {
116
+				$event->EE_Event = EEM_Event::instance()->instantiate_class_from_post_object( $event );
117
+				$this->event = $event->EE_Event;
118
+			}
119
+		} else {
120
+			$user_msg = __( 'No Event object or an invalid Event object was supplied.', 'event_espresso' );
121
+			$dev_msg = $user_msg . __(
122
+					'In order to generate a ticket selector, please ensure you are passing either an EE_Event object or a WP_Post object of the post type "espresso_event" to the EE_Ticket_Selector class constructor.',
123
+					'event_espresso'
124
+				);
125
+			EE_Error::add_error( $user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__ );
126
+			return false;
127
+		}
128
+		return true;
129
+	}
130
+
131
+
132
+
133
+	/**
134
+	 * @return int
135
+	 */
136
+	public function getMaxAttendees()
137
+	{
138
+		return $this->max_attendees;
139
+	}
140
+
141
+
142
+
143
+	/**
144
+	 * @param int $max_attendees
145
+	 */
146
+	public function setMaxAttendees($max_attendees)
147
+	{
148
+		$this->max_attendees = absint(
149
+			apply_filters(
150
+				'FHEE__EE_Ticket_Selector__display_ticket_selector__max_tickets',
151
+				$max_attendees
152
+			)
153
+		);
154
+	}
155
+
156
+
157
+
158
+	/**
159
+	 * creates buttons for selecting number of attendees for an event
160
+	 *
161
+	 * @param WP_Post|int $event
162
+	 * @param bool         $view_details
163
+	 * @return string
164
+	 * @throws EE_Error
165
+	 */
166
+	public function display( $event = null, $view_details = false )
167
+	{
168
+		// reset filter for displaying submit button
169
+		remove_filter( 'FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true' );
170
+		// poke and prod incoming event till it tells us what it is
171
+		if ( ! $this->setEvent( $event ) ) {
172
+			return false;
173
+		}
174
+		// begin gathering template arguments by getting event status
175
+		$template_args = array( 'event_status' => $this->event->get_active_status() );
176
+		if ( $this->activeEventAndShowTicketSelector($event, $template_args['event_status'], $view_details) ) {
177
+			return ! is_single() ? $this->displayViewDetailsButton() : '';
178
+		}
179
+		// filter the maximum qty that can appear in the Ticket Selector qty dropdowns
180
+		$this->setMaxAttendees($this->event->additional_limit());
181
+		if ($this->getMaxAttendees() < 1) {
182
+			return $this->ticketSalesClosedMessage();
183
+		}
184
+		// is the event expired ?
185
+		$template_args['event_is_expired'] = $this->event->is_expired();
186
+		if ( $template_args[ 'event_is_expired' ] ) {
187
+			return $this->expiredEventMessage();
188
+		}
189
+		// get all tickets for this event ordered by the datetime
190
+		$tickets = $this->getTickets();
191
+		if (count($tickets) < 1) {
192
+			return $this->noTicketAvailableMessage();
193
+		}
194
+		if (EED_Events_Archive::is_iframe()){
195
+			$this->setIframe();
196
+		}
197
+		// redirecting to another site for registration ??
198
+		$external_url = (string) $this->event->external_url();
199
+		// if redirecting to another site for registration, then we don't load the TS
200
+		$ticket_selector = $external_url
201
+			? $this->externalEventRegistration()
202
+			: $this->loadTicketSelector($tickets,$template_args);
203
+		// now set up the form (but not for the admin)
204
+		$ticket_selector = ! is_admin()
205
+			? $this->formOpen($this->event->ID(), $external_url) . $ticket_selector
206
+			: $ticket_selector;
207
+		// submit button and form close tag
208
+		$ticket_selector .= ! is_admin() ? $this->displaySubmitButton($external_url) : '';
209
+		return $ticket_selector;
210
+	}
211
+
212
+
213
+
214
+	/**
215
+	 * displayTicketSelector
216
+	 * examines the event properties and determines whether a Ticket Selector should be displayed
217
+	 *
218
+	 * @param WP_Post|int $event
219
+	 * @param string       $_event_active_status
220
+	 * @param bool         $view_details
221
+	 * @return bool
222
+	 * @throws EE_Error
223
+	 */
224
+	protected function activeEventAndShowTicketSelector($event, $_event_active_status, $view_details)
225
+	{
226
+		$event_post = $this->event instanceof EE_Event ? $this->event->ID() : $event;
227
+		return ! is_admin()
228
+			   && (
229
+				   ! $this->event->display_ticket_selector()
230
+				   || $view_details
231
+				   || post_password_required($event_post)
232
+				   || (
233
+					   $_event_active_status !== EE_Datetime::active
234
+					   && $_event_active_status !== EE_Datetime::upcoming
235
+					   && $_event_active_status !== EE_Datetime::sold_out
236
+					   && ! (
237
+						   $_event_active_status === EE_Datetime::inactive
238
+						   && is_user_logged_in()
239
+					   )
240
+				   )
241
+			   );
242
+	}
243
+
244
+
245
+
246
+	/**
247
+	 * noTicketAvailableMessage
248
+	 * notice displayed if event is expired
249
+	 *
250
+	 * @return string
251
+	 * @throws EE_Error
252
+	 */
253
+	protected function expiredEventMessage()
254
+	{
255
+		return '<div class="ee-event-expired-notice"><span class="important-notice">' . esc_html__(
256
+			'We\'re sorry, but all tickets sales have ended because the event is expired.',
257
+			'event_espresso'
258
+		) . '</span></div><!-- .ee-event-expired-notice -->';
259
+	}
260
+
261
+
262
+
263
+	/**
264
+	 * noTicketAvailableMessage
265
+	 * notice displayed if event has no more tickets available
266
+	 *
267
+	 * @return string
268
+	 * @throws EE_Error
269
+	 */
270
+	protected function noTicketAvailableMessage()
271
+	{
272
+		$no_ticket_available_msg = esc_html__( 'We\'re sorry, but all ticket sales have ended.', 'event_espresso' );
273
+		if (current_user_can('edit_post', $this->event->ID())) {
274
+			$no_ticket_available_msg .= sprintf(
275
+				esc_html__(
276
+					'%1$sNote to Event Admin:%2$sNo tickets were found for this event. This effectively turns off ticket sales. Please ensure that at least one ticket is available for if you want people to be able to register.%3$s(click to edit this event)%4$s',
277
+					'event_espresso'
278
+				),
279
+				'<div class="ee-attention" style="text-align: left;"><b>',
280
+				'</b><br />',
281
+				'<span class="edit-link"><a class="post-edit-link" href="'.get_edit_post_link($this->event->ID()).'">',
282
+				'</a></span></div><!-- .ee-attention noTicketAvailableMessage -->'
283
+			);
284
+		}
285
+		return '
286 286
             <div class="ee-event-expired-notice">
287 287
                 <span class="important-notice">' . $no_ticket_available_msg . '</span>
288 288
             </div><!-- .ee-event-expired-notice -->';
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * ticketSalesClosed
295
-     * notice displayed if event ticket sales are turned off
296
-     *
297
-     * @return string
298
-     * @throws EE_Error
299
-     */
300
-    protected function ticketSalesClosedMessage()
301
-    {
302
-        $sales_closed_msg = esc_html__(
303
-            'We\'re sorry, but ticket sales have been closed at this time. Please check back again later.',
304
-            'event_espresso'
305
-        );
306
-        if (current_user_can('edit_post', $this->event->ID())) {
307
-            $sales_closed_msg .= sprintf(
308
-                esc_html__(
309
-                    '%sNote to Event Admin:%sThe "Maximum number of tickets allowed per order for this event" in the Event Registration Options has been set to "0". This effectively turns off ticket sales. %s(click to edit this event)%s',
310
-                    'event_espresso'
311
-                ),
312
-                '<div class="ee-attention" style="text-align: left;"><b>',
313
-                '</b><br />',
314
-                '<span class="edit-link"><a class="post-edit-link" href="'.get_edit_post_link($this->event->ID()).'">',
315
-                '</a></span></div><!-- .ee-attention ticketSalesClosedMessage -->'
316
-            );
317
-        }
318
-        return '<p><span class="important-notice">' . $sales_closed_msg . '</span></p>';
319
-    }
320
-
321
-
322
-
323
-    /**
324
-     * getTickets
325
-     *
326
-     * @return \EE_Base_Class[]|\EE_Ticket[]
327
-     * @throws EE_Error
328
-     */
329
-    protected function getTickets()
330
-    {
331
-        $ticket_query_args = array(
332
-            array('Datetime.EVT_ID' => $this->event->ID()),
333
-            'order_by' => array(
334
-                'TKT_order'              => 'ASC',
335
-                'TKT_required'           => 'DESC',
336
-                'TKT_start_date'         => 'ASC',
337
-                'TKT_end_date'           => 'ASC',
338
-                'Datetime.DTT_EVT_start' => 'DESC',
339
-            ),
340
-        );
341
-        if (
342
-            ! (
343
-                EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector instanceof EE_Ticket_Selector_Config
344
-                && EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector->show_expired_tickets
345
-            )
346
-        ) {
347
-            //use the correct applicable time query depending on what version of core is being run.
348
-            $current_time = method_exists('EEM_Datetime', 'current_time_for_query')
349
-                ? time()
350
-                : current_time('timestamp');
351
-            $ticket_query_args[0]['TKT_end_date'] = array('>', $current_time);
352
-        }
353
-        return EEM_Ticket::instance()->get_all($ticket_query_args);
354
-    }
355
-
356
-
357
-
358
-    /**
359
-     * loadTicketSelector
360
-     * begins to assemble template arguments
361
-     * and decides whether to load a "simple" ticket selector, or the standard
362
-     *
363
-     * @param \EE_Ticket[] $tickets
364
-     * @param array $template_args
365
-     * @return string
366
-     * @throws EE_Error
367
-     */
368
-    protected function loadTicketSelector(array $tickets, array $template_args)
369
-    {
370
-        $template_args['event'] = $this->event;
371
-        $template_args['EVT_ID'] = $this->event->ID();
372
-        $template_args['event_is_expired'] = $this->event->is_expired();
373
-        $template_args['max_atndz'] = $this->getMaxAttendees();
374
-        $template_args['date_format'] = $this->date_format;
375
-        $template_args['time_format'] = $this->time_format;
376
-        /**
377
-         * Filters the anchor ID used when redirecting to the Ticket Selector if no quantity selected
378
-         *
379
-         * @since 4.9.13
380
-         * @param     string  '#tkt-slctr-tbl-' . $EVT_ID The html ID to anchor to
381
-         * @param int $EVT_ID The Event ID
382
-         */
383
-        $template_args['anchor_id'] = apply_filters(
384
-            'FHEE__EE_Ticket_Selector__redirect_anchor_id',
385
-            '#tkt-slctr-tbl-' . $this->event->ID(),
386
-            $this->event->ID()
387
-        );
388
-        $template_args['tickets'] = $tickets;
389
-        $template_args['ticket_count'] = count($tickets);
390
-        $ticket_selector = $this->simpleTicketSelector( $tickets, $template_args);
391
-        return $ticket_selector instanceof TicketSelectorSimple
392
-            ? $ticket_selector
393
-            : new TicketSelectorStandard(
394
-                $this->event,
395
-                $tickets,
396
-                $this->getMaxAttendees(),
397
-                $template_args,
398
-                $this->date_format,
399
-                $this->time_format
400
-            );
401
-    }
402
-
403
-
404
-
405
-    /**
406
-     * simpleTicketSelector
407
-     * there's one ticket, and max attendees is set to one,
408
-     * so if the event is free, then this is a "simple" ticket selector
409
-     * a.k.a. "Dude Where's my Ticket Selector?"
410
-     *
411
-     * @param \EE_Ticket[] $tickets
412
-     * @param array  $template_args
413
-     * @return string
414
-     * @throws EE_Error
415
-     */
416
-    protected function simpleTicketSelector($tickets, array $template_args)
417
-    {
418
-        // if there is only ONE ticket with a max qty of ONE
419
-        if (count($tickets) > 1 || $this->getMaxAttendees() !== 1) {
420
-            return '';
421
-        }
422
-        /** @var \EE_Ticket $ticket */
423
-        $ticket = reset($tickets);
424
-        // if the ticket is free... then not much need for the ticket selector
425
-        if (
426
-            apply_filters(
427
-                'FHEE__ticket_selector_chart_template__hide_ticket_selector',
428
-                $ticket->is_free(),
429
-                $this->event->ID()
430
-            )
431
-        ) {
432
-            return new TicketSelectorSimple(
433
-                $this->event,
434
-                $ticket,
435
-                $this->getMaxAttendees(),
436
-                $template_args
437
-            );
438
-        }
439
-        return '';
440
-    }
441
-
442
-
443
-
444
-    /**
445
-     * externalEventRegistration
446
-     *
447
-     * @return string
448
-     */
449
-    public function externalEventRegistration()
450
-    {
451
-        // if not we still need to trigger the display of the submit button
452
-        add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
453
-        //display notice to admin that registration is external
454
-        return is_admin()
455
-            ? esc_html__(
456
-                'Registration is at an external URL for this event.',
457
-                'event_espresso'
458
-            )
459
-            : '';
460
-    }
461
-
462
-
463
-
464
-    /**
465
-     * formOpen
466
-     *
467
-     * @param        int    $ID
468
-     * @param        string $external_url
469
-     * @return        string
470
-     */
471
-    public function formOpen( $ID = 0, $external_url = '' )
472
-    {
473
-        // if redirecting, we don't need any anything else
474
-        if ( $external_url ) {
475
-            $html = '<form method="GET" action="' . EEH_URL::refactor_url($external_url) . '"';
476
-            // open link in new window ?
477
-            $html .= apply_filters(
478
-                'FHEE__EventEspresso_modules_ticket_selector_DisplayTicketSelector__formOpen__external_url_target_blank',
479
-                EED_Events_Archive::is_iframe()
480
-            )
481
-                ? ' target="_blank"'
482
-                : '';
483
-            $html .= '>';
484
-            $query_args = EEH_URL::get_query_string( $external_url );
485
-            foreach ( (array)$query_args as $query_arg => $value ) {
486
-                $html .= '<input type="hidden" name="' . $query_arg . '" value="' . $value . '">';
487
-            }
488
-            return $html;
489
-        }
490
-        // if there is no submit button, then don't start building a form
491
-        // because the "View Details" button will build its own form
492
-        if ( ! apply_filters( 'FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false ) ) {
493
-            return '';
494
-        }
495
-        $checkout_url = EEH_Event_View::event_link_url( $ID );
496
-        if ( ! $checkout_url ) {
497
-            EE_Error::add_error(
498
-                esc_html__( 'The URL for the Event Details page could not be retrieved.', 'event_espresso' ),
499
-                __FILE__,
500
-                __FUNCTION__,
501
-                __LINE__
502
-            );
503
-        }
504
-        // set no cache headers and constants
505
-        EE_System::do_not_cache();
506
-        $extra_params = $this->iframe ? ' target="_blank"' : '';
507
-        $html = '<form method="POST" action="' . $checkout_url . '"' . $extra_params . '>';
508
-        $html .= '<input type="hidden" name="ee" value="process_ticket_selections">';
509
-        $html = apply_filters( 'FHEE__EE_Ticket_Selector__ticket_selector_form_open__html', $html, $this->event );
510
-        return $html;
511
-    }
512
-
513
-
514
-
515
-    /**
516
-     * displaySubmitButton
517
-     *
518
-     * @param  string $external_url
519
-     * @return string
520
-     * @throws EE_Error
521
-     */
522
-    public function displaySubmitButton($external_url = '')
523
-    {
524
-        $html = '';
525
-        if ( ! is_admin()) {
526
-            // standard TS displayed with submit button, ie: "Register Now"
527
-            if (apply_filters('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false)) {
528
-                $html .= $this->displayRegisterNowButton();
529
-                $html .= empty($external_url)
530
-                    ? $this->ticketSelectorEndDiv()
531
-                    : $this->clearTicketSelector();
532
-                $html .= '<br/>' . $this->formClose();
533
-            } else if ($this->getMaxAttendees() === 1) {
534
-                // its a "Dude Where's my Ticket Selector?" (DWMTS) type event (ie: $_max_atndz === 1)
535
-                if ($this->event->is_sold_out()) {
536
-                    // then instead of a View Details or Submit button, just display a "Sold Out" message
537
-                    $html .= apply_filters(
538
-                        'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__sold_out_msg',
539
-                        sprintf(
540
-                            __(
541
-                                '%1$s"%2$s" is currently sold out.%4$sPlease check back again later, as spots may become available.%3$s',
542
-                                'event_espresso'
543
-                            ),
544
-                            '<p class="no-ticket-selector-msg clear-float">',
545
-                            $this->event->name(),
546
-                            '</p>',
547
-                            '<br />'
548
-                        ),
549
-                        $this->event
550
-                    );
551
-                    if (
552
-                        apply_filters(
553
-                            'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__no_tickets_but_display_register_now_button',
554
-                            false,
555
-                            $this->event
556
-                        )
557
-                    ) {
558
-                        $html .= $this->displayRegisterNowButton();
559
-                    }
560
-                    // sold out DWMTS event, no TS, no submit or view details button, but has additional content
561
-                    $html .=  $this->ticketSelectorEndDiv();
562
-                } else if (
563
-                    apply_filters('FHEE__EE_Ticket_Selector__hide_ticket_selector', false)
564
-                    && ! is_single()
565
-                ) {
566
-                    // this is a "Dude Where's my Ticket Selector?" (DWMTS) type event,
567
-                    // but no tickets are available, so display event's "View Details" button.
568
-                    // it is being viewed via somewhere other than a single post
569
-                    $html .= $this->displayViewDetailsButton(true);
570
-                } else {
571
-                    $html .= $this->ticketSelectorEndDiv();
572
-                }
573
-            } else if (is_archive()) {
574
-                // event list, no tickets available so display event's "View Details" button
575
-                $html .= $this->ticketSelectorEndDiv();
576
-                $html .= $this->displayViewDetailsButton();
577
-            } else {
578
-                if (
579
-                    apply_filters(
580
-                        'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__no_tickets_but_display_register_now_button',
581
-                        false,
582
-                        $this->event
583
-                    )
584
-                ) {
585
-                    $html .= $this->displayRegisterNowButton();
586
-                }
587
-                // no submit or view details button, and no additional content
588
-                $html .= $this->ticketSelectorEndDiv();
589
-            }
590
-            if ( ! $this->iframe && ! is_archive()) {
591
-                $html .= EEH_Template::powered_by_event_espresso('', '', array('utm_content' => 'ticket_selector'));
592
-            }
593
-        }
594
-	    return apply_filters(
595
-		    'FHEE__EventEspresso_modules_ticket_selector_DisplayTicketSelector__displaySubmitButton__html',
596
-		    $html,
597
-		    $this->event
598
-	    );
599
-    }
600
-
601
-
602
-
603
-    /**
604
-     * @return string
605
-     * @throws EE_Error
606
-     */
607
-    public function displayRegisterNowButton()
608
-    {
609
-        $btn_text = apply_filters(
610
-            'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__btn_text',
611
-            __('Register Now', 'event_espresso'),
612
-            $this->event
613
-        );
614
-        $external_url = $this->event->external_url();
615
-        $html = EEH_HTML::div(
616
-            '', 'ticket-selector-submit-' . $this->event->ID() . '-btn-wrap', 'ticket-selector-submit-btn-wrap'
617
-        );
618
-        $html .= '<input id="ticket-selector-submit-' . $this->event->ID() . '-btn"';
619
-        $html .= ' class="ticket-selector-submit-btn ';
620
-        $html .= empty($external_url) ? 'ticket-selector-submit-ajax"' : '"';
621
-        $html .= ' type="submit" value="' . $btn_text . '" />';
622
-        $html .= EEH_HTML::divx() . '<!-- .ticket-selector-submit-btn-wrap -->';
623
-        $html .= apply_filters(
624
-            'FHEE__EE_Ticket_Selector__after_ticket_selector_submit',
625
-            '',
626
-            $this->event
627
-        );
628
-        return $html;
629
-    }
630
-
631
-
632
-    /**
633
-     * displayViewDetailsButton
634
-     *
635
-     * @param bool $DWMTS indicates a "Dude Where's my Ticket Selector?" (DWMTS) type event
636
-     *                    (ie: $_max_atndz === 1) where there are no available tickets,
637
-     *                    either because they are sold out, expired, or not yet on sale.
638
-     *                    In this case, we need to close the form BEFORE adding any closing divs
639
-     * @return string
640
-     * @throws EE_Error
641
-     */
642
-    public function displayViewDetailsButton( $DWMTS = false )
643
-    {
644
-        if ( ! $this->event->get_permalink() ) {
645
-            EE_Error::add_error(
646
-                esc_html__( 'The URL for the Event Details page could not be retrieved.', 'event_espresso' ),
647
-                __FILE__, __FUNCTION__, __LINE__
648
-            );
649
-        }
650
-        $view_details_btn = '<form method="POST" action="';
651
-        $view_details_btn .= apply_filters(
652
-            'FHEE__EE_Ticket_Selector__display_view_details_btn__btn_url',
653
-            $this->event->get_permalink(),
654
-            $this->event
655
-        );
656
-        $view_details_btn .= '"';
657
-        // open link in new window ?
658
-        $view_details_btn .= apply_filters(
659
-            'FHEE__EventEspresso_modules_ticket_selector_DisplayTicketSelector__displayViewDetailsButton__url_target_blank',
660
-            EED_Events_Archive::is_iframe()
661
-        )
662
-            ? ' target="_blank"'
663
-            : '';
664
-        $view_details_btn .='>';
665
-        $btn_text = apply_filters(
666
-            'FHEE__EE_Ticket_Selector__display_view_details_btn__btn_text',
667
-            esc_html__('View Details', 'event_espresso'),
668
-            $this->event
669
-        );
670
-        $view_details_btn .= '<input id="ticket-selector-submit-'
671
-                             . $this->event->ID()
672
-                             . '-btn" class="ticket-selector-submit-btn view-details-btn" type="submit" value="'
673
-                             . $btn_text
674
-                             . '" />';
675
-        $view_details_btn .= apply_filters( 'FHEE__EE_Ticket_Selector__after_view_details_btn', '', $this->event );
676
-        if ($DWMTS) {
677
-            $view_details_btn .= $this->formClose();
678
-            $view_details_btn .= $this->ticketSelectorEndDiv();
679
-            $view_details_btn .= '<br/>';
680
-        } else {
681
-            $view_details_btn .= $this->clearTicketSelector();
682
-            $view_details_btn .= '<br/>';
683
-            $view_details_btn .= $this->formClose();
684
-        }
685
-        return $view_details_btn;
686
-    }
687
-
688
-
689
-
690
-    /**
691
-     * @return string
692
-     */
693
-    public function ticketSelectorEndDiv()
694
-    {
695
-        return $this->clearTicketSelector() . '</div><!-- ticketSelectorEndDiv -->';
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     * @return string
702
-     */
703
-    public function clearTicketSelector()
704
-    {
705
-        // standard TS displayed, appears after a "Register Now" or "view Details" button
706
-        return '<div class="clear"></div><!-- clearTicketSelector -->';
707
-    }
708
-
709
-
710
-
711
-    /**
712
-     * @access        public
713
-     * @return        string
714
-     */
715
-    public function formClose()
716
-    {
717
-        return '</form>';
718
-    }
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * ticketSalesClosed
295
+	 * notice displayed if event ticket sales are turned off
296
+	 *
297
+	 * @return string
298
+	 * @throws EE_Error
299
+	 */
300
+	protected function ticketSalesClosedMessage()
301
+	{
302
+		$sales_closed_msg = esc_html__(
303
+			'We\'re sorry, but ticket sales have been closed at this time. Please check back again later.',
304
+			'event_espresso'
305
+		);
306
+		if (current_user_can('edit_post', $this->event->ID())) {
307
+			$sales_closed_msg .= sprintf(
308
+				esc_html__(
309
+					'%sNote to Event Admin:%sThe "Maximum number of tickets allowed per order for this event" in the Event Registration Options has been set to "0". This effectively turns off ticket sales. %s(click to edit this event)%s',
310
+					'event_espresso'
311
+				),
312
+				'<div class="ee-attention" style="text-align: left;"><b>',
313
+				'</b><br />',
314
+				'<span class="edit-link"><a class="post-edit-link" href="'.get_edit_post_link($this->event->ID()).'">',
315
+				'</a></span></div><!-- .ee-attention ticketSalesClosedMessage -->'
316
+			);
317
+		}
318
+		return '<p><span class="important-notice">' . $sales_closed_msg . '</span></p>';
319
+	}
320
+
321
+
322
+
323
+	/**
324
+	 * getTickets
325
+	 *
326
+	 * @return \EE_Base_Class[]|\EE_Ticket[]
327
+	 * @throws EE_Error
328
+	 */
329
+	protected function getTickets()
330
+	{
331
+		$ticket_query_args = array(
332
+			array('Datetime.EVT_ID' => $this->event->ID()),
333
+			'order_by' => array(
334
+				'TKT_order'              => 'ASC',
335
+				'TKT_required'           => 'DESC',
336
+				'TKT_start_date'         => 'ASC',
337
+				'TKT_end_date'           => 'ASC',
338
+				'Datetime.DTT_EVT_start' => 'DESC',
339
+			),
340
+		);
341
+		if (
342
+			! (
343
+				EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector instanceof EE_Ticket_Selector_Config
344
+				&& EE_Registry::instance()->CFG->template_settings->EED_Ticket_Selector->show_expired_tickets
345
+			)
346
+		) {
347
+			//use the correct applicable time query depending on what version of core is being run.
348
+			$current_time = method_exists('EEM_Datetime', 'current_time_for_query')
349
+				? time()
350
+				: current_time('timestamp');
351
+			$ticket_query_args[0]['TKT_end_date'] = array('>', $current_time);
352
+		}
353
+		return EEM_Ticket::instance()->get_all($ticket_query_args);
354
+	}
355
+
356
+
357
+
358
+	/**
359
+	 * loadTicketSelector
360
+	 * begins to assemble template arguments
361
+	 * and decides whether to load a "simple" ticket selector, or the standard
362
+	 *
363
+	 * @param \EE_Ticket[] $tickets
364
+	 * @param array $template_args
365
+	 * @return string
366
+	 * @throws EE_Error
367
+	 */
368
+	protected function loadTicketSelector(array $tickets, array $template_args)
369
+	{
370
+		$template_args['event'] = $this->event;
371
+		$template_args['EVT_ID'] = $this->event->ID();
372
+		$template_args['event_is_expired'] = $this->event->is_expired();
373
+		$template_args['max_atndz'] = $this->getMaxAttendees();
374
+		$template_args['date_format'] = $this->date_format;
375
+		$template_args['time_format'] = $this->time_format;
376
+		/**
377
+		 * Filters the anchor ID used when redirecting to the Ticket Selector if no quantity selected
378
+		 *
379
+		 * @since 4.9.13
380
+		 * @param     string  '#tkt-slctr-tbl-' . $EVT_ID The html ID to anchor to
381
+		 * @param int $EVT_ID The Event ID
382
+		 */
383
+		$template_args['anchor_id'] = apply_filters(
384
+			'FHEE__EE_Ticket_Selector__redirect_anchor_id',
385
+			'#tkt-slctr-tbl-' . $this->event->ID(),
386
+			$this->event->ID()
387
+		);
388
+		$template_args['tickets'] = $tickets;
389
+		$template_args['ticket_count'] = count($tickets);
390
+		$ticket_selector = $this->simpleTicketSelector( $tickets, $template_args);
391
+		return $ticket_selector instanceof TicketSelectorSimple
392
+			? $ticket_selector
393
+			: new TicketSelectorStandard(
394
+				$this->event,
395
+				$tickets,
396
+				$this->getMaxAttendees(),
397
+				$template_args,
398
+				$this->date_format,
399
+				$this->time_format
400
+			);
401
+	}
402
+
403
+
404
+
405
+	/**
406
+	 * simpleTicketSelector
407
+	 * there's one ticket, and max attendees is set to one,
408
+	 * so if the event is free, then this is a "simple" ticket selector
409
+	 * a.k.a. "Dude Where's my Ticket Selector?"
410
+	 *
411
+	 * @param \EE_Ticket[] $tickets
412
+	 * @param array  $template_args
413
+	 * @return string
414
+	 * @throws EE_Error
415
+	 */
416
+	protected function simpleTicketSelector($tickets, array $template_args)
417
+	{
418
+		// if there is only ONE ticket with a max qty of ONE
419
+		if (count($tickets) > 1 || $this->getMaxAttendees() !== 1) {
420
+			return '';
421
+		}
422
+		/** @var \EE_Ticket $ticket */
423
+		$ticket = reset($tickets);
424
+		// if the ticket is free... then not much need for the ticket selector
425
+		if (
426
+			apply_filters(
427
+				'FHEE__ticket_selector_chart_template__hide_ticket_selector',
428
+				$ticket->is_free(),
429
+				$this->event->ID()
430
+			)
431
+		) {
432
+			return new TicketSelectorSimple(
433
+				$this->event,
434
+				$ticket,
435
+				$this->getMaxAttendees(),
436
+				$template_args
437
+			);
438
+		}
439
+		return '';
440
+	}
441
+
442
+
443
+
444
+	/**
445
+	 * externalEventRegistration
446
+	 *
447
+	 * @return string
448
+	 */
449
+	public function externalEventRegistration()
450
+	{
451
+		// if not we still need to trigger the display of the submit button
452
+		add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
453
+		//display notice to admin that registration is external
454
+		return is_admin()
455
+			? esc_html__(
456
+				'Registration is at an external URL for this event.',
457
+				'event_espresso'
458
+			)
459
+			: '';
460
+	}
461
+
462
+
463
+
464
+	/**
465
+	 * formOpen
466
+	 *
467
+	 * @param        int    $ID
468
+	 * @param        string $external_url
469
+	 * @return        string
470
+	 */
471
+	public function formOpen( $ID = 0, $external_url = '' )
472
+	{
473
+		// if redirecting, we don't need any anything else
474
+		if ( $external_url ) {
475
+			$html = '<form method="GET" action="' . EEH_URL::refactor_url($external_url) . '"';
476
+			// open link in new window ?
477
+			$html .= apply_filters(
478
+				'FHEE__EventEspresso_modules_ticket_selector_DisplayTicketSelector__formOpen__external_url_target_blank',
479
+				EED_Events_Archive::is_iframe()
480
+			)
481
+				? ' target="_blank"'
482
+				: '';
483
+			$html .= '>';
484
+			$query_args = EEH_URL::get_query_string( $external_url );
485
+			foreach ( (array)$query_args as $query_arg => $value ) {
486
+				$html .= '<input type="hidden" name="' . $query_arg . '" value="' . $value . '">';
487
+			}
488
+			return $html;
489
+		}
490
+		// if there is no submit button, then don't start building a form
491
+		// because the "View Details" button will build its own form
492
+		if ( ! apply_filters( 'FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false ) ) {
493
+			return '';
494
+		}
495
+		$checkout_url = EEH_Event_View::event_link_url( $ID );
496
+		if ( ! $checkout_url ) {
497
+			EE_Error::add_error(
498
+				esc_html__( 'The URL for the Event Details page could not be retrieved.', 'event_espresso' ),
499
+				__FILE__,
500
+				__FUNCTION__,
501
+				__LINE__
502
+			);
503
+		}
504
+		// set no cache headers and constants
505
+		EE_System::do_not_cache();
506
+		$extra_params = $this->iframe ? ' target="_blank"' : '';
507
+		$html = '<form method="POST" action="' . $checkout_url . '"' . $extra_params . '>';
508
+		$html .= '<input type="hidden" name="ee" value="process_ticket_selections">';
509
+		$html = apply_filters( 'FHEE__EE_Ticket_Selector__ticket_selector_form_open__html', $html, $this->event );
510
+		return $html;
511
+	}
512
+
513
+
514
+
515
+	/**
516
+	 * displaySubmitButton
517
+	 *
518
+	 * @param  string $external_url
519
+	 * @return string
520
+	 * @throws EE_Error
521
+	 */
522
+	public function displaySubmitButton($external_url = '')
523
+	{
524
+		$html = '';
525
+		if ( ! is_admin()) {
526
+			// standard TS displayed with submit button, ie: "Register Now"
527
+			if (apply_filters('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false)) {
528
+				$html .= $this->displayRegisterNowButton();
529
+				$html .= empty($external_url)
530
+					? $this->ticketSelectorEndDiv()
531
+					: $this->clearTicketSelector();
532
+				$html .= '<br/>' . $this->formClose();
533
+			} else if ($this->getMaxAttendees() === 1) {
534
+				// its a "Dude Where's my Ticket Selector?" (DWMTS) type event (ie: $_max_atndz === 1)
535
+				if ($this->event->is_sold_out()) {
536
+					// then instead of a View Details or Submit button, just display a "Sold Out" message
537
+					$html .= apply_filters(
538
+						'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__sold_out_msg',
539
+						sprintf(
540
+							__(
541
+								'%1$s"%2$s" is currently sold out.%4$sPlease check back again later, as spots may become available.%3$s',
542
+								'event_espresso'
543
+							),
544
+							'<p class="no-ticket-selector-msg clear-float">',
545
+							$this->event->name(),
546
+							'</p>',
547
+							'<br />'
548
+						),
549
+						$this->event
550
+					);
551
+					if (
552
+						apply_filters(
553
+							'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__no_tickets_but_display_register_now_button',
554
+							false,
555
+							$this->event
556
+						)
557
+					) {
558
+						$html .= $this->displayRegisterNowButton();
559
+					}
560
+					// sold out DWMTS event, no TS, no submit or view details button, but has additional content
561
+					$html .=  $this->ticketSelectorEndDiv();
562
+				} else if (
563
+					apply_filters('FHEE__EE_Ticket_Selector__hide_ticket_selector', false)
564
+					&& ! is_single()
565
+				) {
566
+					// this is a "Dude Where's my Ticket Selector?" (DWMTS) type event,
567
+					// but no tickets are available, so display event's "View Details" button.
568
+					// it is being viewed via somewhere other than a single post
569
+					$html .= $this->displayViewDetailsButton(true);
570
+				} else {
571
+					$html .= $this->ticketSelectorEndDiv();
572
+				}
573
+			} else if (is_archive()) {
574
+				// event list, no tickets available so display event's "View Details" button
575
+				$html .= $this->ticketSelectorEndDiv();
576
+				$html .= $this->displayViewDetailsButton();
577
+			} else {
578
+				if (
579
+					apply_filters(
580
+						'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__no_tickets_but_display_register_now_button',
581
+						false,
582
+						$this->event
583
+					)
584
+				) {
585
+					$html .= $this->displayRegisterNowButton();
586
+				}
587
+				// no submit or view details button, and no additional content
588
+				$html .= $this->ticketSelectorEndDiv();
589
+			}
590
+			if ( ! $this->iframe && ! is_archive()) {
591
+				$html .= EEH_Template::powered_by_event_espresso('', '', array('utm_content' => 'ticket_selector'));
592
+			}
593
+		}
594
+		return apply_filters(
595
+			'FHEE__EventEspresso_modules_ticket_selector_DisplayTicketSelector__displaySubmitButton__html',
596
+			$html,
597
+			$this->event
598
+		);
599
+	}
600
+
601
+
602
+
603
+	/**
604
+	 * @return string
605
+	 * @throws EE_Error
606
+	 */
607
+	public function displayRegisterNowButton()
608
+	{
609
+		$btn_text = apply_filters(
610
+			'FHEE__EE_Ticket_Selector__display_ticket_selector_submit__btn_text',
611
+			__('Register Now', 'event_espresso'),
612
+			$this->event
613
+		);
614
+		$external_url = $this->event->external_url();
615
+		$html = EEH_HTML::div(
616
+			'', 'ticket-selector-submit-' . $this->event->ID() . '-btn-wrap', 'ticket-selector-submit-btn-wrap'
617
+		);
618
+		$html .= '<input id="ticket-selector-submit-' . $this->event->ID() . '-btn"';
619
+		$html .= ' class="ticket-selector-submit-btn ';
620
+		$html .= empty($external_url) ? 'ticket-selector-submit-ajax"' : '"';
621
+		$html .= ' type="submit" value="' . $btn_text . '" />';
622
+		$html .= EEH_HTML::divx() . '<!-- .ticket-selector-submit-btn-wrap -->';
623
+		$html .= apply_filters(
624
+			'FHEE__EE_Ticket_Selector__after_ticket_selector_submit',
625
+			'',
626
+			$this->event
627
+		);
628
+		return $html;
629
+	}
630
+
631
+
632
+	/**
633
+	 * displayViewDetailsButton
634
+	 *
635
+	 * @param bool $DWMTS indicates a "Dude Where's my Ticket Selector?" (DWMTS) type event
636
+	 *                    (ie: $_max_atndz === 1) where there are no available tickets,
637
+	 *                    either because they are sold out, expired, or not yet on sale.
638
+	 *                    In this case, we need to close the form BEFORE adding any closing divs
639
+	 * @return string
640
+	 * @throws EE_Error
641
+	 */
642
+	public function displayViewDetailsButton( $DWMTS = false )
643
+	{
644
+		if ( ! $this->event->get_permalink() ) {
645
+			EE_Error::add_error(
646
+				esc_html__( 'The URL for the Event Details page could not be retrieved.', 'event_espresso' ),
647
+				__FILE__, __FUNCTION__, __LINE__
648
+			);
649
+		}
650
+		$view_details_btn = '<form method="POST" action="';
651
+		$view_details_btn .= apply_filters(
652
+			'FHEE__EE_Ticket_Selector__display_view_details_btn__btn_url',
653
+			$this->event->get_permalink(),
654
+			$this->event
655
+		);
656
+		$view_details_btn .= '"';
657
+		// open link in new window ?
658
+		$view_details_btn .= apply_filters(
659
+			'FHEE__EventEspresso_modules_ticket_selector_DisplayTicketSelector__displayViewDetailsButton__url_target_blank',
660
+			EED_Events_Archive::is_iframe()
661
+		)
662
+			? ' target="_blank"'
663
+			: '';
664
+		$view_details_btn .='>';
665
+		$btn_text = apply_filters(
666
+			'FHEE__EE_Ticket_Selector__display_view_details_btn__btn_text',
667
+			esc_html__('View Details', 'event_espresso'),
668
+			$this->event
669
+		);
670
+		$view_details_btn .= '<input id="ticket-selector-submit-'
671
+							 . $this->event->ID()
672
+							 . '-btn" class="ticket-selector-submit-btn view-details-btn" type="submit" value="'
673
+							 . $btn_text
674
+							 . '" />';
675
+		$view_details_btn .= apply_filters( 'FHEE__EE_Ticket_Selector__after_view_details_btn', '', $this->event );
676
+		if ($DWMTS) {
677
+			$view_details_btn .= $this->formClose();
678
+			$view_details_btn .= $this->ticketSelectorEndDiv();
679
+			$view_details_btn .= '<br/>';
680
+		} else {
681
+			$view_details_btn .= $this->clearTicketSelector();
682
+			$view_details_btn .= '<br/>';
683
+			$view_details_btn .= $this->formClose();
684
+		}
685
+		return $view_details_btn;
686
+	}
687
+
688
+
689
+
690
+	/**
691
+	 * @return string
692
+	 */
693
+	public function ticketSelectorEndDiv()
694
+	{
695
+		return $this->clearTicketSelector() . '</div><!-- ticketSelectorEndDiv -->';
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 * @return string
702
+	 */
703
+	public function clearTicketSelector()
704
+	{
705
+		// standard TS displayed, appears after a "Register Now" or "view Details" button
706
+		return '<div class="clear"></div><!-- clearTicketSelector -->';
707
+	}
708
+
709
+
710
+
711
+	/**
712
+	 * @access        public
713
+	 * @return        string
714
+	 */
715
+	public function formClose()
716
+	{
717
+		return '</form>';
718
+	}
719 719
 
720 720
 
721 721
 
Please login to merge, or discard this patch.