Completed
Branch FET-10260-expose-default-query... (0e28a3)
by
unknown
176:17 queued 163:36
created
core/libraries/rest_api/controllers/model/Read.php 2 patches
Indentation   +1114 added lines, -1114 removed lines patch added patch discarded remove patch
@@ -7,7 +7,7 @@  discard block
 block discarded – undo
7 7
 use EventEspresso\core\libraries\rest_api\Model_Data_Translator;
8 8
 
9 9
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
10
-    exit('No direct script access allowed');
10
+	exit('No direct script access allowed');
11 11
 }
12 12
 
13 13
 
@@ -25,1119 +25,1119 @@  discard block
 block discarded – undo
25 25
 
26 26
 
27 27
 
28
-    /**
29
-     * @var Calculated_Model_Fields
30
-     */
31
-    protected $_fields_calculator;
32
-
33
-
34
-
35
-    /**
36
-     * Read constructor.
37
-     */
38
-    public function __construct()
39
-    {
40
-        parent::__construct();
41
-        $this->_fields_calculator = new Calculated_Model_Fields();
42
-    }
43
-
44
-
45
-
46
-    /**
47
-     * Handles requests to get all (or a filtered subset) of entities for a particular model
48
-     *
49
-     * @param \WP_REST_Request $request
50
-     * @return \WP_REST_Response|\WP_Error
51
-     */
52
-    public static function handle_request_get_all(\WP_REST_Request $request)
53
-    {
54
-        $controller = new Read();
55
-        try {
56
-            $matches = $controller->parse_route(
57
-                $request->get_route(),
58
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)~',
59
-                array('version', 'model')
60
-            );
61
-            $controller->set_requested_version($matches['version']);
62
-            $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
63
-            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
64
-                return $controller->send_response(
65
-                    new \WP_Error(
66
-                        'endpoint_parsing_error',
67
-                        sprintf(
68
-                            __('There is no model for endpoint %s. Please contact event espresso support',
69
-                                'event_espresso'),
70
-                            $model_name_singular
71
-                        )
72
-                    )
73
-                );
74
-            }
75
-            return $controller->send_response(
76
-                $controller->get_entities_from_model(
77
-                    $controller->get_model_version_info()->load_model($model_name_singular),
78
-                    $request
79
-                )
80
-            );
81
-        } catch (\Exception $e) {
82
-            return $controller->send_response($e);
83
-        }
84
-    }
85
-
86
-
87
-
88
-    /**
89
-     * Gets a single entity related to the model indicated in the path and its id
90
-     *
91
-     * @param \WP_REST_Request $request
92
-     * @return \WP_REST_Response|\WP_Error
93
-     */
94
-    public static function handle_request_get_one(\WP_REST_Request $request)
95
-    {
96
-        $controller = new Read();
97
-        try {
98
-            $matches = $controller->parse_route(
99
-                $request->get_route(),
100
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)~',
101
-                array('version', 'model', 'id'));
102
-            $controller->set_requested_version($matches['version']);
103
-            $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
104
-            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
105
-                return $controller->send_response(
106
-                    new \WP_Error(
107
-                        'endpoint_parsing_error',
108
-                        sprintf(
109
-                            __('There is no model for endpoint %s. Please contact event espresso support',
110
-                                'event_espresso'),
111
-                            $model_name_singular
112
-                        )
113
-                    )
114
-                );
115
-            }
116
-            return $controller->send_response(
117
-                $controller->get_entity_from_model(
118
-                    $controller->get_model_version_info()->load_model($model_name_singular),
119
-                    $request
120
-                )
121
-            );
122
-        } catch (\Exception $e) {
123
-            return $controller->send_response($e);
124
-        }
125
-    }
126
-
127
-
128
-
129
-    /**
130
-     * Gets all the related entities (or if its a belongs-to relation just the one)
131
-     * to the item with the given id
132
-     *
133
-     * @param \WP_REST_Request $request
134
-     * @return \WP_REST_Response|\WP_Error
135
-     */
136
-    public static function handle_request_get_related(\WP_REST_Request $request)
137
-    {
138
-        $controller = new Read();
139
-        try {
140
-            $matches = $controller->parse_route(
141
-                $request->get_route(),
142
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)/(.*)~',
143
-                array('version', 'model', 'id', 'related_model')
144
-            );
145
-            $controller->set_requested_version($matches['version']);
146
-            $main_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
147
-            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
148
-                return $controller->send_response(
149
-                    new \WP_Error(
150
-                        'endpoint_parsing_error',
151
-                        sprintf(
152
-                            __('There is no model for endpoint %s. Please contact event espresso support',
153
-                                'event_espresso'),
154
-                            $main_model_name_singular
155
-                        )
156
-                    )
157
-                );
158
-            }
159
-            $main_model = $controller->get_model_version_info()->load_model($main_model_name_singular);
160
-            //assume the related model name is plural and try to find the model's name
161
-            $related_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['related_model']);
162
-            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
163
-                //so the word didn't singularize well. Maybe that's just because it's a singular word?
164
-                $related_model_name_singular = \EEH_Inflector::humanize($matches['related_model']);
165
-            }
166
-            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
167
-                return $controller->send_response(
168
-                    new \WP_Error(
169
-                        'endpoint_parsing_error',
170
-                        sprintf(
171
-                            __('There is no model for endpoint %s. Please contact event espresso support',
172
-                                'event_espresso'),
173
-                            $related_model_name_singular
174
-                        )
175
-                    )
176
-                );
177
-            }
178
-            return $controller->send_response(
179
-                $controller->get_entities_from_relation(
180
-                    $request->get_param('id'),
181
-                    $main_model->related_settings_for($related_model_name_singular),
182
-                    $request
183
-                )
184
-            );
185
-        } catch (\Exception $e) {
186
-            return $controller->send_response($e);
187
-        }
188
-    }
189
-
190
-
191
-
192
-    /**
193
-     * Gets a collection for the given model and filters
194
-     *
195
-     * @param \EEM_Base        $model
196
-     * @param \WP_REST_Request $request
197
-     * @return array|\WP_Error
198
-     */
199
-    public function get_entities_from_model($model, $request)
200
-    {
201
-        $query_params = $this->create_model_query_params($model, $request->get_params());
202
-        if ( ! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
203
-            $model_name_plural = \EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
204
-            return new \WP_Error(
205
-                sprintf('rest_%s_cannot_list', $model_name_plural),
206
-                sprintf(
207
-                    __('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
208
-                    $model_name_plural,
209
-                    Capabilities::get_missing_permissions_string($model, $query_params['caps'])
210
-                ),
211
-                array('status' => 403)
212
-            );
213
-        }
214
-        if ( ! $request->get_header('no_rest_headers')) {
215
-            $this->_set_headers_from_query_params($model, $query_params);
216
-        }
217
-        /** @type array $results */
218
-        $results = $model->get_all_wpdb_results($query_params);
219
-        $nice_results = array();
220
-        foreach ($results as $result) {
221
-            $nice_results[] = $this->create_entity_from_wpdb_result(
222
-                $model,
223
-                $result,
224
-                $request
225
-            );
226
-        }
227
-        return $nice_results;
228
-    }
229
-
230
-
231
-
232
-    /**
233
-     * @param array                   $primary_model_query_params query params for finding the item from which
234
-     *                                                            relations will be based
235
-     * @param \EE_Model_Relation_Base $relation
236
-     * @param \WP_REST_Request        $request
237
-     * @return \WP_Error|array
238
-     */
239
-    protected function _get_entities_from_relation($primary_model_query_params, $relation, $request)
240
-    {
241
-        $context = $this->validate_context($request->get_param('caps'));
242
-        $model = $relation->get_this_model();
243
-        $related_model = $relation->get_other_model();
244
-        if ( ! isset($primary_model_query_params[0])) {
245
-            $primary_model_query_params[0] = array();
246
-        }
247
-        //check if they can access the 1st model object
248
-        $primary_model_query_params = array(
249
-            0       => $primary_model_query_params[0],
250
-            'limit' => 1,
251
-        );
252
-        if ($model instanceof \EEM_Soft_Delete_Base) {
253
-            $primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($primary_model_query_params);
254
-        }
255
-        $restricted_query_params = $primary_model_query_params;
256
-        $restricted_query_params['caps'] = $context;
257
-        $this->_set_debug_info('main model query params', $restricted_query_params);
258
-        $this->_set_debug_info('missing caps', Capabilities::get_missing_permissions_string($related_model, $context));
259
-        if (
260
-        ! (
261
-            Capabilities::current_user_has_partial_access_to($related_model, $context)
262
-            && $model->exists($restricted_query_params)
263
-        )
264
-        ) {
265
-            if ($relation instanceof \EE_Belongs_To_Relation) {
266
-                $related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
267
-            } else {
268
-                $related_model_name_maybe_plural = \EEH_Inflector::pluralize_and_lower($related_model->get_this_model_name());
269
-            }
270
-            return new \WP_Error(
271
-                sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
272
-                sprintf(
273
-                    __('Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
274
-                        'event_espresso'),
275
-                    $related_model_name_maybe_plural,
276
-                    $relation->get_this_model()->get_this_model_name(),
277
-                    implode(
278
-                        ',',
279
-                        array_keys(
280
-                            Capabilities::get_missing_permissions($related_model, $context)
281
-                        )
282
-                    )
283
-                ),
284
-                array('status' => 403)
285
-            );
286
-        }
287
-        $query_params = $this->create_model_query_params($relation->get_other_model(), $request->get_params());
288
-        foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
289
-            $query_params[0][$relation->get_this_model()->get_this_model_name()
290
-                             . '.'
291
-                             . $where_condition_key] = $where_condition_value;
292
-        }
293
-        $query_params['default_where_conditions'] = 'none';
294
-        $query_params['caps'] = $context;
295
-        if ( ! $request->get_header('no_rest_headers')) {
296
-            $this->_set_headers_from_query_params($relation->get_other_model(), $query_params);
297
-        }
298
-        /** @type array $results */
299
-        $results = $relation->get_other_model()->get_all_wpdb_results($query_params);
300
-        $nice_results = array();
301
-        foreach ($results as $result) {
302
-            $nice_result = $this->create_entity_from_wpdb_result(
303
-                $relation->get_other_model(),
304
-                $result,
305
-                $request
306
-            );
307
-            if ($relation instanceof \EE_HABTM_Relation) {
308
-                //put the unusual stuff (properties from the HABTM relation) first, and make sure
309
-                //if there are conflicts we prefer the properties from the main model
310
-                $join_model_result = $this->create_entity_from_wpdb_result(
311
-                    $relation->get_join_model(),
312
-                    $result,
313
-                    $request
314
-                );
315
-                $joined_result = array_merge($nice_result, $join_model_result);
316
-                //but keep the meta stuff from the main model
317
-                if (isset($nice_result['meta'])) {
318
-                    $joined_result['meta'] = $nice_result['meta'];
319
-                }
320
-                $nice_result = $joined_result;
321
-            }
322
-            $nice_results[] = $nice_result;
323
-        }
324
-        if ($relation instanceof \EE_Belongs_To_Relation) {
325
-            return array_shift($nice_results);
326
-        } else {
327
-            return $nice_results;
328
-        }
329
-    }
330
-
331
-
332
-
333
-    /**
334
-     * Gets the collection for given relation object
335
-     * The same as Read::get_entities_from_model(), except if the relation
336
-     * is a HABTM relation, in which case it merges any non-foreign-key fields from
337
-     * the join-model-object into the results
338
-     *
339
-     * @param string                  $id the ID of the thing we are fetching related stuff from
340
-     * @param \EE_Model_Relation_Base $relation
341
-     * @param \WP_REST_Request        $request
342
-     * @return array|\WP_Error
343
-     * @throws \EE_Error
344
-     */
345
-    public function get_entities_from_relation($id, $relation, $request)
346
-    {
347
-        if ( ! $relation->get_this_model()->has_primary_key_field()) {
348
-            throw new \EE_Error(
349
-                sprintf(
350
-                    __('Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
351
-                        'event_espresso'),
352
-                    $relation->get_this_model()->get_this_model_name()
353
-                )
354
-            );
355
-        }
356
-        return $this->_get_entities_from_relation(
357
-            array(
358
-                array(
359
-                    $relation->get_this_model()->primary_key_name() => $id,
360
-                ),
361
-            ),
362
-            $relation,
363
-            $request
364
-        );
365
-    }
366
-
367
-
368
-
369
-    /**
370
-     * Sets the headers that are based on the model and query params,
371
-     * like the total records. This should only be called on the original request
372
-     * from the client, not on subsequent internal
373
-     *
374
-     * @param \EEM_Base $model
375
-     * @param array     $query_params
376
-     * @return void
377
-     */
378
-    protected function _set_headers_from_query_params($model, $query_params)
379
-    {
380
-        $this->_set_debug_info('model query params', $query_params);
381
-        $this->_set_debug_info('missing caps',
382
-            Capabilities::get_missing_permissions_string($model, $query_params['caps']));
383
-        //normally the limit to a 2-part array, where the 2nd item is the limit
384
-        if ( ! isset($query_params['limit'])) {
385
-            $query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
386
-        }
387
-        if (is_array($query_params['limit'])) {
388
-            $limit_parts = $query_params['limit'];
389
-        } else {
390
-            $limit_parts = explode(',', $query_params['limit']);
391
-            if (count($limit_parts) == 1) {
392
-                $limit_parts = array(0, $limit_parts[0]);
393
-            }
394
-        }
395
-        //remove the group by and having parts of the query, as those will
396
-        //make the sql query return an array of values, instead of just a single value
397
-        unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
398
-        $count = $model->count($query_params, null, true);
399
-        $pages = $count / $limit_parts[1];
400
-        $this->_set_response_header('Total', $count, false);
401
-        $this->_set_response_header('PageSize', $limit_parts[1], false);
402
-        $this->_set_response_header('TotalPages', ceil($pages), false);
403
-    }
404
-
405
-
406
-
407
-    /**
408
-     * Changes database results into REST API entities
409
-     *
410
-     * @param \EEM_Base        $model
411
-     * @param array            $db_row     like results from $wpdb->get_results()
412
-     * @param \WP_REST_Request $rest_request
413
-     * @param string           $deprecated no longer used
414
-     * @return array ready for being converted into json for sending to client
415
-     */
416
-    public function create_entity_from_wpdb_result($model, $db_row, $rest_request, $deprecated = null)
417
-    {
418
-        if ( ! $rest_request instanceof \WP_REST_Request) {
419
-            //ok so this was called in the old style, where the 3rd arg was
420
-            //$include, and the 4th arg was $context
421
-            //now setup the request just to avoid fatal errors, although we won't be able
422
-            //to truly make use of it because it's kinda devoid of info
423
-            $rest_request = new \WP_REST_Request();
424
-            $rest_request->set_param('include', $rest_request);
425
-            $rest_request->set_param('caps', $deprecated);
426
-        }
427
-        if ($rest_request->get_param('caps') == null) {
428
-            $rest_request->set_param('caps', \EEM_Base::caps_read);
429
-        }
430
-        $entity_array = $this->_create_bare_entity_from_wpdb_results($model, $db_row);
431
-        $entity_array = $this->_add_extra_fields($model, $db_row, $entity_array);
432
-        $entity_array['_links'] = $this->_get_entity_links($model, $db_row, $entity_array);
433
-        $entity_array['_calculated_fields'] = $this->_get_entity_calculations($model, $db_row, $rest_request);
434
-        $entity_array = $this->_include_requested_models($model, $rest_request, $entity_array, $db_row);
435
-        $entity_array = apply_filters(
436
-            'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
437
-            $entity_array,
438
-            $model,
439
-            $rest_request->get_param('caps'),
440
-            $rest_request,
441
-            $this
442
-        );
443
-        $result_without_inaccessible_fields = Capabilities::filter_out_inaccessible_entity_fields(
444
-            $entity_array,
445
-            $model,
446
-            $rest_request->get_param('caps'),
447
-            $this->get_model_version_info(),
448
-            $model->get_index_primary_key_string(
449
-                $model->deduce_fields_n_values_from_cols_n_values($db_row)
450
-            )
451
-        );
452
-        $this->_set_debug_info(
453
-            'inaccessible fields',
454
-            array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
455
-        );
456
-        return apply_filters(
457
-            'FHEE__Read__create_entity_from_wpdb_results__entity_return',
458
-            $result_without_inaccessible_fields,
459
-            $model,
460
-            $rest_request->get_param('caps')
461
-        );
462
-    }
463
-
464
-
465
-
466
-    /**
467
-     * Creates a REST entity array (JSON object we're going to return in the response, but
468
-     * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
469
-     * from $wpdb->get_row( $sql, ARRAY_A)
470
-     *
471
-     * @param \EEM_Base $model
472
-     * @param array     $db_row
473
-     * @return array entity mostly ready for converting to JSON and sending in the response
474
-     */
475
-    protected function _create_bare_entity_from_wpdb_results(\EEM_Base $model, $db_row)
476
-    {
477
-        $result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
478
-        $result = array_intersect_key($result,
479
-            $this->get_model_version_info()->fields_on_model_in_this_version($model));
480
-        foreach ($result as $field_name => $raw_field_value) {
481
-            $field_obj = $model->field_settings_for($field_name);
482
-            $field_value = $field_obj->prepare_for_set_from_db($raw_field_value);
483
-            if ($this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_ignored())) {
484
-                unset($result[$field_name]);
485
-            } elseif (
486
-            $this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_rendered_format())
487
-            ) {
488
-                $result[$field_name] = array(
489
-                    'raw'      => $field_obj->prepare_for_get($field_value),
490
-                    'rendered' => $field_obj->prepare_for_pretty_echoing($field_value),
491
-                );
492
-            } elseif (
493
-            $this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_pretty_format())
494
-            ) {
495
-                $result[$field_name] = array(
496
-                    'raw'    => $field_obj->prepare_for_get($field_value),
497
-                    'pretty' => $field_obj->prepare_for_pretty_echoing($field_value),
498
-                );
499
-            } elseif ($field_obj instanceof \EE_Datetime_Field) {
500
-                if ($field_value instanceof \DateTime) {
501
-                    $timezone = $field_value->getTimezone();
502
-                    $field_value->setTimezone(new \DateTimeZone('UTC'));
503
-                    $result[$field_name . '_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
504
-                        $field_obj,
505
-                        $field_value,
506
-                        $this->get_model_version_info()->requested_version()
507
-                    );
508
-                    $field_value->setTimezone($timezone);
509
-                    $result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
510
-                        $field_obj,
511
-                        $field_value,
512
-                        $this->get_model_version_info()->requested_version()
513
-                    );
514
-                }
515
-            } else {
516
-                $result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
517
-                    $field_obj,
518
-                    $field_obj->prepare_for_get($field_value),
519
-                    $this->get_model_version_info()->requested_version()
520
-                );
521
-            }
522
-        }
523
-        return $result;
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     * Adds a few extra fields to the entity response
530
-     *
531
-     * @param \EEM_Base $model
532
-     * @param array     $db_row
533
-     * @param array     $entity_array
534
-     * @return array modified entity
535
-     */
536
-    protected function _add_extra_fields(\EEM_Base $model, $db_row, $entity_array)
537
-    {
538
-        if ($model instanceof \EEM_CPT_Base) {
539
-            $entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
540
-        }
541
-        return $entity_array;
542
-    }
543
-
544
-
545
-
546
-    /**
547
-     * Gets links we want to add to the response
548
-     *
549
-     * @global \WP_REST_Server $wp_rest_server
550
-     * @param \EEM_Base        $model
551
-     * @param array            $db_row
552
-     * @param array            $entity_array
553
-     * @return array the _links item in the entity
554
-     */
555
-    protected function _get_entity_links($model, $db_row, $entity_array)
556
-    {
557
-        //add basic links
558
-        $links = array();
559
-        if ($model->has_primary_key_field()) {
560
-            $links['self'] = array(
561
-                array(
562
-                    'href' => $this->get_versioned_link_to(
563
-                        \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
564
-                        . '/'
565
-                        . $entity_array[$model->primary_key_name()]
566
-                    ),
567
-                ),
568
-            );
569
-        }
570
-        $links['collection'] = array(
571
-            array(
572
-                'href' => $this->get_versioned_link_to(
573
-                    \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
574
-                ),
575
-            ),
576
-        );
577
-        //add link to the wp core endpoint, if wp api is active
578
-        global $wp_rest_server;
579
-        if ($model instanceof \EEM_CPT_Base
580
-            && $wp_rest_server instanceof \WP_REST_Server
581
-            && $wp_rest_server->get_route_options('/wp/v2/posts')
582
-            && $model->has_primary_key_field()
583
-        ) {
584
-            $links[\EED_Core_Rest_Api::ee_api_link_namespace . 'self_wp_post'] = array(
585
-                array(
586
-                    'href'   => rest_url('/wp/v2/posts/' . $db_row[$model->get_primary_key_field()
587
-                                                                         ->get_qualified_column()]),
588
-                    'single' => true,
589
-                ),
590
-            );
591
-        }
592
-        //add links to related models
593
-        if ($model->has_primary_key_field()) {
594
-            foreach ($this->get_model_version_info()->relation_settings($model) as $relation_name => $relation_obj) {
595
-                $related_model_part = Read::get_related_entity_name($relation_name, $relation_obj);
596
-                $links[\EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
597
-                    array(
598
-                        'href'   => $this->get_versioned_link_to(
599
-                            \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
600
-                            . '/'
601
-                            . $entity_array[$model->primary_key_name()]
602
-                            . '/'
603
-                            . $related_model_part
604
-                        ),
605
-                        'single' => $relation_obj instanceof \EE_Belongs_To_Relation ? true : false,
606
-                    ),
607
-                );
608
-            }
609
-        }
610
-        return $links;
611
-    }
612
-
613
-
614
-
615
-    /**
616
-     * Adds the included models indicated in the request to the entity provided
617
-     *
618
-     * @param \EEM_Base        $model
619
-     * @param \WP_REST_Request $rest_request
620
-     * @param array            $entity_array
621
-     * @param array            $db_row
622
-     * @return array the modified entity
623
-     */
624
-    protected function _include_requested_models(
625
-        \EEM_Base $model,
626
-        \WP_REST_Request $rest_request,
627
-        $entity_array,
628
-        $db_row = array()
629
-    ) {
630
-        //if $db_row not included, hope the entity array has what we need
631
-        if ( ! $db_row) {
632
-            $db_row = $entity_array;
633
-        }
634
-        $includes_for_this_model = $this->explode_and_get_items_prefixed_with($rest_request->get_param('include'), '');
635
-        $includes_for_this_model = $this->_remove_model_names_from_array($includes_for_this_model);
636
-        //if they passed in * or didn't specify any includes, return everything
637
-        if ( ! in_array('*', $includes_for_this_model)
638
-             && ! empty($includes_for_this_model)
639
-        ) {
640
-            if ($model->has_primary_key_field()) {
641
-                //always include the primary key. ya just gotta know that at least
642
-                $includes_for_this_model[] = $model->primary_key_name();
643
-            }
644
-            if ($this->explode_and_get_items_prefixed_with($rest_request->get_param('calculate'), '')) {
645
-                $includes_for_this_model[] = '_calculated_fields';
646
-            }
647
-            $entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
648
-        }
649
-        $relation_settings = $this->get_model_version_info()->relation_settings($model);
650
-        foreach ($relation_settings as $relation_name => $relation_obj) {
651
-            $related_fields_to_include = $this->explode_and_get_items_prefixed_with(
652
-                $rest_request->get_param('include'),
653
-                $relation_name
654
-            );
655
-            $related_fields_to_calculate = $this->explode_and_get_items_prefixed_with(
656
-                $rest_request->get_param('calculate'),
657
-                $relation_name
658
-            );
659
-            //did they specify they wanted to include a related model, or
660
-            //specific fields from a related model?
661
-            //or did they specify to calculate a field from a related model?
662
-            if ($related_fields_to_include || $related_fields_to_calculate) {
663
-                //if so, we should include at least some part of the related model
664
-                $pretend_related_request = new \WP_REST_Request();
665
-                $pretend_related_request->set_query_params(
666
-                    array(
667
-                        'caps'      => $rest_request->get_param('caps'),
668
-                        'include'   => $related_fields_to_include,
669
-                        'calculate' => $related_fields_to_calculate,
670
-                    )
671
-                );
672
-                $pretend_related_request->add_header('no_rest_headers', true);
673
-                $primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
674
-                    $model->get_index_primary_key_string(
675
-                        $model->deduce_fields_n_values_from_cols_n_values($db_row)
676
-                    )
677
-                );
678
-                $related_results = $this->_get_entities_from_relation(
679
-                    $primary_model_query_params,
680
-                    $relation_obj,
681
-                    $pretend_related_request
682
-                );
683
-                $entity_array[Read::get_related_entity_name($relation_name, $relation_obj)] = $related_results
684
-                                                                                              instanceof
685
-                                                                                              \WP_Error
686
-                    ? null
687
-                    : $related_results;
688
-            }
689
-        }
690
-        return $entity_array;
691
-    }
692
-
693
-
694
-
695
-    /**
696
-     * Returns a new array with all the names of models removed. Eg
697
-     * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
698
-     *
699
-     * @param array $arr
700
-     * @return array
701
-     */
702
-    private function _remove_model_names_from_array($arr)
703
-    {
704
-        return array_diff($arr, array_keys(\EE_Registry::instance()->non_abstract_db_models));
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     * Gets the calculated fields for the response
711
-     *
712
-     * @param \EEM_Base        $model
713
-     * @param array            $wpdb_row
714
-     * @param \WP_REST_Request $rest_request
715
-     * @return \stdClass the _calculations item in the entity
716
-     */
717
-    protected function _get_entity_calculations($model, $wpdb_row, $rest_request)
718
-    {
719
-        $calculated_fields = $this->explode_and_get_items_prefixed_with(
720
-            $rest_request->get_param('calculate'),
721
-            ''
722
-        );
723
-        //note: setting calculate=* doesn't do anything
724
-        $calculated_fields_to_return = new \stdClass();
725
-        foreach ($calculated_fields as $field_to_calculate) {
726
-            try {
727
-                $calculated_fields_to_return->$field_to_calculate = Model_Data_Translator::prepare_field_value_for_json(
728
-                    null,
729
-                    $this->_fields_calculator->retrieve_calculated_field_value(
730
-                        $model,
731
-                        $field_to_calculate,
732
-                        $wpdb_row,
733
-                        $rest_request,
734
-                        $this
735
-                    ),
736
-                    $this->get_model_version_info()->requested_version()
737
-                );
738
-            } catch (Rest_Exception $e) {
739
-                //if we don't have permission to read it, just leave it out. but let devs know about the problem
740
-                $this->_set_response_header(
741
-                    'Notices-Field-Calculation-Errors['
742
-                    . $e->get_string_code()
743
-                    . ']['
744
-                    . $model->get_this_model_name()
745
-                    . ']['
746
-                    . $field_to_calculate
747
-                    . ']',
748
-                    $e->getMessage(),
749
-                    true
750
-                );
751
-            }
752
-        }
753
-        return $calculated_fields_to_return;
754
-    }
755
-
756
-
757
-
758
-    /**
759
-     * Gets the full URL to the resource, taking the requested version into account
760
-     *
761
-     * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
762
-     * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
763
-     */
764
-    public function get_versioned_link_to($link_part_after_version_and_slash)
765
-    {
766
-        return rest_url(
767
-            \EED_Core_Rest_Api::ee_api_namespace
768
-            . $this->get_model_version_info()->requested_version()
769
-            . '/'
770
-            . $link_part_after_version_and_slash
771
-        );
772
-    }
773
-
774
-
775
-
776
-    /**
777
-     * Gets the correct lowercase name for the relation in the API according
778
-     * to the relation's type
779
-     *
780
-     * @param string                  $relation_name
781
-     * @param \EE_Model_Relation_Base $relation_obj
782
-     * @return string
783
-     */
784
-    public static function get_related_entity_name($relation_name, $relation_obj)
785
-    {
786
-        if ($relation_obj instanceof \EE_Belongs_To_Relation) {
787
-            return strtolower($relation_name);
788
-        } else {
789
-            return \EEH_Inflector::pluralize_and_lower($relation_name);
790
-        }
791
-    }
792
-
793
-
794
-
795
-    /**
796
-     * Gets the one model object with the specified id for the specified model
797
-     *
798
-     * @param \EEM_Base        $model
799
-     * @param \WP_REST_Request $request
800
-     * @return array|\WP_Error
801
-     */
802
-    public function get_entity_from_model($model, $request)
803
-    {
804
-        $query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
805
-        if ($model instanceof \EEM_Soft_Delete_Base) {
806
-            $query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
807
-        }
808
-        $restricted_query_params = $query_params;
809
-        $restricted_query_params['caps'] = $this->validate_context($request->get_param('caps'));
810
-        $this->_set_debug_info('model query params', $restricted_query_params);
811
-        $model_rows = $model->get_all_wpdb_results($restricted_query_params);
812
-        if ( ! empty ($model_rows)) {
813
-            return $this->create_entity_from_wpdb_result(
814
-                $model,
815
-                array_shift($model_rows),
816
-                $request);
817
-        } else {
818
-            //ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
819
-            $lowercase_model_name = strtolower($model->get_this_model_name());
820
-            $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
821
-            if ( ! empty($model_rows_found_sans_restrictions)) {
822
-                //you got shafted- it existed but we didn't want to tell you!
823
-                return new \WP_Error(
824
-                    'rest_user_cannot_read',
825
-                    sprintf(
826
-                        __('Sorry, you cannot read this %1$s. Missing permissions are: %2$s', 'event_espresso'),
827
-                        strtolower($model->get_this_model_name()),
828
-                        Capabilities::get_missing_permissions_string(
829
-                            $model,
830
-                            $this->validate_context($request->get_param('caps')))
831
-                    ),
832
-                    array('status' => 403)
833
-                );
834
-            } else {
835
-                //it's not you. It just doesn't exist
836
-                return new \WP_Error(
837
-                    sprintf('rest_%s_invalid_id', $lowercase_model_name),
838
-                    sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
839
-                    array('status' => 404)
840
-                );
841
-            }
842
-        }
843
-    }
844
-
845
-
846
-
847
-    /**
848
-     * If a context is provided which isn't valid, maybe it was added in a future
849
-     * version so just treat it as a default read
850
-     *
851
-     * @param string $context
852
-     * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
853
-     */
854
-    public function validate_context($context)
855
-    {
856
-        if ( ! $context) {
857
-            $context = \EEM_Base::caps_read;
858
-        }
859
-        $valid_contexts = \EEM_Base::valid_cap_contexts();
860
-        if (in_array($context, $valid_contexts)) {
861
-            return $context;
862
-        } else {
863
-            return \EEM_Base::caps_read;
864
-        }
865
-    }
866
-
867
-
868
-
869
-    /**
870
-     * Verifies the passed in value is an allowable default where conditions value.
871
-     * @param $default_query_params
872
-     * @return string
873
-     */
874
-    public function validate_default_query_params( $default_query_params ) {
875
-        $valid_default_where_conditions_for_api_calls = array(
876
-            \EEM_Base::default_where_conditions_all,
877
-            \EEM_Base::default_where_conditions_minimum_all,
878
-            \EEM_Base::default_where_conditions_minimum_others
879
-        );
880
-        if ( ! $default_query_params ) {
881
-            $default_query_params = \EEM_Base::default_where_conditions_all;
882
-        }
883
-        if(
884
-            in_array(
885
-                $default_query_params,
886
-                $valid_default_where_conditions_for_api_calls,
887
-                true
888
-            )
889
-        ) {
890
-            return $default_query_params;
891
-        } else {
892
-            return \EEM_Base::default_where_conditions_all;
893
-        }
894
-    }
895
-
896
-
897
-
898
-    /**
899
-     * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
900
-     * Note: right now the query parameter keys for fields (and related fields)
901
-     * can be left as-is, but it's quite possible this will change someday.
902
-     * Also, this method's contents might be candidate for moving to Model_Data_Translator
903
-     *
904
-     * @param \EEM_Base $model
905
-     * @param array     $query_parameters from $_GET parameter @see Read:handle_request_get_all
906
-     * @return array like what EEM_Base::get_all() expects or FALSE to indicate
907
-     *                                    that absolutely no results should be returned
908
-     * @throws \EE_Error
909
-     */
910
-    public function create_model_query_params($model, $query_parameters)
911
-    {
912
-        $model_query_params = array();
913
-        if (isset($query_parameters['where'])) {
914
-            $model_query_params[0] = Model_Data_Translator::prepare_conditions_query_params_for_models(
915
-                $query_parameters['where'],
916
-                $model,
917
-                $this->get_model_version_info()->requested_version()
918
-            );
919
-        }
920
-        if (isset($query_parameters['order_by'])) {
921
-            $order_by = $query_parameters['order_by'];
922
-        } elseif (isset($query_parameters['orderby'])) {
923
-            $order_by = $query_parameters['orderby'];
924
-        } else {
925
-            $order_by = null;
926
-        }
927
-        if ($order_by !== null) {
928
-            if (is_array($order_by)) {
929
-                $order_by = Model_Data_Translator::prepare_field_names_in_array_keys_from_json($order_by);
930
-            } else {
931
-                //it's a single item
932
-                $order_by = Model_Data_Translator::prepare_field_name_from_json($order_by);
933
-            }
934
-            $model_query_params['order_by'] = $order_by;
935
-        }
936
-        if (isset($query_parameters['group_by'])) {
937
-            $group_by = $query_parameters['group_by'];
938
-        } elseif (isset($query_parameters['groupby'])) {
939
-            $group_by = $query_parameters['groupby'];
940
-        } else {
941
-            $group_by = array_keys($model->get_combined_primary_key_fields());
942
-        }
943
-        //make sure they're all real names
944
-        if (is_array($group_by)) {
945
-            $group_by = Model_Data_Translator::prepare_field_names_from_json($group_by);
946
-        }
947
-        if ($group_by !== null) {
948
-            $model_query_params['group_by'] = $group_by;
949
-        }
950
-        if (isset($query_parameters['having'])) {
951
-            $model_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_models(
952
-                $query_parameters['having'],
953
-                $model,
954
-                $this->get_model_version_info()->requested_version()
955
-            );
956
-        }
957
-        if (isset($query_parameters['order'])) {
958
-            $model_query_params['order'] = $query_parameters['order'];
959
-        }
960
-        if (isset($query_parameters['mine'])) {
961
-            $model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
962
-        }
963
-        if (isset($query_parameters['limit'])) {
964
-            //limit should be either a string like '23' or '23,43', or an array with two items in it
965
-            if ( ! is_array($query_parameters['limit'])) {
966
-                $limit_array = explode(',', (string)$query_parameters['limit']);
967
-            } else {
968
-                $limit_array = $query_parameters['limit'];
969
-            }
970
-            $sanitized_limit = array();
971
-            foreach ($limit_array as $key => $limit_part) {
972
-                if ($this->_debug_mode && ( ! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
973
-                    throw new \EE_Error(
974
-                        sprintf(
975
-                            __('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.',
976
-                                'event_espresso'),
977
-                            wp_json_encode($query_parameters['limit'])
978
-                        )
979
-                    );
980
-                }
981
-                $sanitized_limit[] = (int)$limit_part;
982
-            }
983
-            $model_query_params['limit'] = implode(',', $sanitized_limit);
984
-        } else {
985
-            $model_query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
986
-        }
987
-        if (isset($query_parameters['caps'])) {
988
-            $model_query_params['caps'] = $this->validate_context($query_parameters['caps']);
989
-        } else {
990
-            $model_query_params['caps'] = \EEM_Base::caps_read;
991
-        }
992
-        if (isset($query_parameters['default_query_params'])) {
993
-            $model_query_params['default_where_conditions'] = $this->validate_default_query_params($query_parameters['default_where_conditions']);
994
-        }
995
-        return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
996
-    }
997
-
998
-
999
-
1000
-    /**
1001
-     * Changes the REST-style query params for use in the models
1002
-     *
1003
-     * @deprecated
1004
-     * @param \EEM_Base $model
1005
-     * @param array     $query_params sub-array from @see EEM_Base::get_all()
1006
-     * @return array
1007
-     */
1008
-    public function prepare_rest_query_params_key_for_models($model, $query_params)
1009
-    {
1010
-        $model_ready_query_params = array();
1011
-        foreach ($query_params as $key => $value) {
1012
-            if (is_array($value)) {
1013
-                $model_ready_query_params[$key] = $this->prepare_rest_query_params_key_for_models($model, $value);
1014
-            } else {
1015
-                $model_ready_query_params[$key] = $value;
1016
-            }
1017
-        }
1018
-        return $model_ready_query_params;
1019
-    }
1020
-
1021
-
1022
-
1023
-    /**
1024
-     * @deprecated
1025
-     * @param $model
1026
-     * @param $query_params
1027
-     * @return array
1028
-     */
1029
-    public function prepare_rest_query_params_values_for_models($model, $query_params)
1030
-    {
1031
-        $model_ready_query_params = array();
1032
-        foreach ($query_params as $key => $value) {
1033
-            if (is_array($value)) {
1034
-                $model_ready_query_params[$key] = $this->prepare_rest_query_params_values_for_models($model, $value);
1035
-            } else {
1036
-                $model_ready_query_params[$key] = $value;
1037
-            }
1038
-        }
1039
-        return $model_ready_query_params;
1040
-    }
1041
-
1042
-
1043
-
1044
-    /**
1045
-     * Explodes the string on commas, and only returns items with $prefix followed by a period.
1046
-     * If no prefix is specified, returns items with no period.
1047
-     *
1048
-     * @param string|array $string_to_explode eg "jibba,jabba, blah, blaabla" or array('jibba', 'jabba' )
1049
-     * @param string       $prefix            "Event" or "foobar"
1050
-     * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1051
-     *                                        we only return strings starting with that and a period; if no prefix was
1052
-     *                                        specified we return all items containing NO periods
1053
-     */
1054
-    public function explode_and_get_items_prefixed_with($string_to_explode, $prefix)
1055
-    {
1056
-        if (is_string($string_to_explode)) {
1057
-            $exploded_contents = explode(',', $string_to_explode);
1058
-        } else if (is_array($string_to_explode)) {
1059
-            $exploded_contents = $string_to_explode;
1060
-        } else {
1061
-            $exploded_contents = array();
1062
-        }
1063
-        //if the string was empty, we want an empty array
1064
-        $exploded_contents = array_filter($exploded_contents);
1065
-        $contents_with_prefix = array();
1066
-        foreach ($exploded_contents as $item) {
1067
-            $item = trim($item);
1068
-            //if no prefix was provided, so we look for items with no "." in them
1069
-            if ( ! $prefix) {
1070
-                //does this item have a period?
1071
-                if (strpos($item, '.') === false) {
1072
-                    //if not, then its what we're looking for
1073
-                    $contents_with_prefix[] = $item;
1074
-                }
1075
-            } else if (strpos($item, $prefix . '.') === 0) {
1076
-                //this item has the prefix and a period, grab it
1077
-                $contents_with_prefix[] = substr(
1078
-                    $item,
1079
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1080
-                );
1081
-            } else if ($item === $prefix) {
1082
-                //this item is JUST the prefix
1083
-                //so let's grab everything after, which is a blank string
1084
-                $contents_with_prefix[] = '';
1085
-            }
1086
-        }
1087
-        return $contents_with_prefix;
1088
-    }
1089
-
1090
-
1091
-
1092
-    /**
1093
-     * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1094
-     * Deprecated because its return values were really quite confusing- sometimes it returned
1095
-     * an empty array (when the include string was blank or '*') or sometimes it returned
1096
-     * array('*') (when you provided a model and a model of that kind was found).
1097
-     * Parses the $include_string so we fetch all the field names relating to THIS model
1098
-     * (ie have NO period in them), or for the provided model (ie start with the model
1099
-     * name and then a period).
1100
-     * @param string $include_string @see Read:handle_request_get_all
1101
-     * @param string $model_name
1102
-     * @return array of fields for this model. If $model_name is provided, then
1103
-     *                               the fields for that model, with the model's name removed from each.
1104
-     *                               If $include_string was blank or '*' returns an empty array
1105
-     */
1106
-    public function extract_includes_for_this_model($include_string, $model_name = null)
1107
-    {
1108
-        if (is_array($include_string)) {
1109
-            $include_string = implode(',', $include_string);
1110
-        }
1111
-        if ($include_string === '*' || $include_string === '') {
1112
-            return array();
1113
-        }
1114
-        $includes = explode(',', $include_string);
1115
-        $extracted_fields_to_include = array();
1116
-        if ($model_name) {
1117
-            foreach ($includes as $field_to_include) {
1118
-                $field_to_include = trim($field_to_include);
1119
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1120
-                    //found the model name at the exact start
1121
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1122
-                    $extracted_fields_to_include[] = $field_sans_model_name;
1123
-                } elseif ($field_to_include == $model_name) {
1124
-                    $extracted_fields_to_include[] = '*';
1125
-                }
1126
-            }
1127
-        } else {
1128
-            //look for ones with no period
1129
-            foreach ($includes as $field_to_include) {
1130
-                $field_to_include = trim($field_to_include);
1131
-                if (
1132
-                    strpos($field_to_include, '.') === false
1133
-                    && ! $this->get_model_version_info()->is_model_name_in_this_version($field_to_include)
1134
-                ) {
1135
-                    $extracted_fields_to_include[] = $field_to_include;
1136
-                }
1137
-            }
1138
-        }
1139
-        return $extracted_fields_to_include;
1140
-    }
28
+	/**
29
+	 * @var Calculated_Model_Fields
30
+	 */
31
+	protected $_fields_calculator;
32
+
33
+
34
+
35
+	/**
36
+	 * Read constructor.
37
+	 */
38
+	public function __construct()
39
+	{
40
+		parent::__construct();
41
+		$this->_fields_calculator = new Calculated_Model_Fields();
42
+	}
43
+
44
+
45
+
46
+	/**
47
+	 * Handles requests to get all (or a filtered subset) of entities for a particular model
48
+	 *
49
+	 * @param \WP_REST_Request $request
50
+	 * @return \WP_REST_Response|\WP_Error
51
+	 */
52
+	public static function handle_request_get_all(\WP_REST_Request $request)
53
+	{
54
+		$controller = new Read();
55
+		try {
56
+			$matches = $controller->parse_route(
57
+				$request->get_route(),
58
+				'~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)~',
59
+				array('version', 'model')
60
+			);
61
+			$controller->set_requested_version($matches['version']);
62
+			$model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
63
+			if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
64
+				return $controller->send_response(
65
+					new \WP_Error(
66
+						'endpoint_parsing_error',
67
+						sprintf(
68
+							__('There is no model for endpoint %s. Please contact event espresso support',
69
+								'event_espresso'),
70
+							$model_name_singular
71
+						)
72
+					)
73
+				);
74
+			}
75
+			return $controller->send_response(
76
+				$controller->get_entities_from_model(
77
+					$controller->get_model_version_info()->load_model($model_name_singular),
78
+					$request
79
+				)
80
+			);
81
+		} catch (\Exception $e) {
82
+			return $controller->send_response($e);
83
+		}
84
+	}
85
+
86
+
87
+
88
+	/**
89
+	 * Gets a single entity related to the model indicated in the path and its id
90
+	 *
91
+	 * @param \WP_REST_Request $request
92
+	 * @return \WP_REST_Response|\WP_Error
93
+	 */
94
+	public static function handle_request_get_one(\WP_REST_Request $request)
95
+	{
96
+		$controller = new Read();
97
+		try {
98
+			$matches = $controller->parse_route(
99
+				$request->get_route(),
100
+				'~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)~',
101
+				array('version', 'model', 'id'));
102
+			$controller->set_requested_version($matches['version']);
103
+			$model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
104
+			if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
105
+				return $controller->send_response(
106
+					new \WP_Error(
107
+						'endpoint_parsing_error',
108
+						sprintf(
109
+							__('There is no model for endpoint %s. Please contact event espresso support',
110
+								'event_espresso'),
111
+							$model_name_singular
112
+						)
113
+					)
114
+				);
115
+			}
116
+			return $controller->send_response(
117
+				$controller->get_entity_from_model(
118
+					$controller->get_model_version_info()->load_model($model_name_singular),
119
+					$request
120
+				)
121
+			);
122
+		} catch (\Exception $e) {
123
+			return $controller->send_response($e);
124
+		}
125
+	}
126
+
127
+
128
+
129
+	/**
130
+	 * Gets all the related entities (or if its a belongs-to relation just the one)
131
+	 * to the item with the given id
132
+	 *
133
+	 * @param \WP_REST_Request $request
134
+	 * @return \WP_REST_Response|\WP_Error
135
+	 */
136
+	public static function handle_request_get_related(\WP_REST_Request $request)
137
+	{
138
+		$controller = new Read();
139
+		try {
140
+			$matches = $controller->parse_route(
141
+				$request->get_route(),
142
+				'~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)/(.*)~',
143
+				array('version', 'model', 'id', 'related_model')
144
+			);
145
+			$controller->set_requested_version($matches['version']);
146
+			$main_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
147
+			if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
148
+				return $controller->send_response(
149
+					new \WP_Error(
150
+						'endpoint_parsing_error',
151
+						sprintf(
152
+							__('There is no model for endpoint %s. Please contact event espresso support',
153
+								'event_espresso'),
154
+							$main_model_name_singular
155
+						)
156
+					)
157
+				);
158
+			}
159
+			$main_model = $controller->get_model_version_info()->load_model($main_model_name_singular);
160
+			//assume the related model name is plural and try to find the model's name
161
+			$related_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['related_model']);
162
+			if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
163
+				//so the word didn't singularize well. Maybe that's just because it's a singular word?
164
+				$related_model_name_singular = \EEH_Inflector::humanize($matches['related_model']);
165
+			}
166
+			if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
167
+				return $controller->send_response(
168
+					new \WP_Error(
169
+						'endpoint_parsing_error',
170
+						sprintf(
171
+							__('There is no model for endpoint %s. Please contact event espresso support',
172
+								'event_espresso'),
173
+							$related_model_name_singular
174
+						)
175
+					)
176
+				);
177
+			}
178
+			return $controller->send_response(
179
+				$controller->get_entities_from_relation(
180
+					$request->get_param('id'),
181
+					$main_model->related_settings_for($related_model_name_singular),
182
+					$request
183
+				)
184
+			);
185
+		} catch (\Exception $e) {
186
+			return $controller->send_response($e);
187
+		}
188
+	}
189
+
190
+
191
+
192
+	/**
193
+	 * Gets a collection for the given model and filters
194
+	 *
195
+	 * @param \EEM_Base        $model
196
+	 * @param \WP_REST_Request $request
197
+	 * @return array|\WP_Error
198
+	 */
199
+	public function get_entities_from_model($model, $request)
200
+	{
201
+		$query_params = $this->create_model_query_params($model, $request->get_params());
202
+		if ( ! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
203
+			$model_name_plural = \EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
204
+			return new \WP_Error(
205
+				sprintf('rest_%s_cannot_list', $model_name_plural),
206
+				sprintf(
207
+					__('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
208
+					$model_name_plural,
209
+					Capabilities::get_missing_permissions_string($model, $query_params['caps'])
210
+				),
211
+				array('status' => 403)
212
+			);
213
+		}
214
+		if ( ! $request->get_header('no_rest_headers')) {
215
+			$this->_set_headers_from_query_params($model, $query_params);
216
+		}
217
+		/** @type array $results */
218
+		$results = $model->get_all_wpdb_results($query_params);
219
+		$nice_results = array();
220
+		foreach ($results as $result) {
221
+			$nice_results[] = $this->create_entity_from_wpdb_result(
222
+				$model,
223
+				$result,
224
+				$request
225
+			);
226
+		}
227
+		return $nice_results;
228
+	}
229
+
230
+
231
+
232
+	/**
233
+	 * @param array                   $primary_model_query_params query params for finding the item from which
234
+	 *                                                            relations will be based
235
+	 * @param \EE_Model_Relation_Base $relation
236
+	 * @param \WP_REST_Request        $request
237
+	 * @return \WP_Error|array
238
+	 */
239
+	protected function _get_entities_from_relation($primary_model_query_params, $relation, $request)
240
+	{
241
+		$context = $this->validate_context($request->get_param('caps'));
242
+		$model = $relation->get_this_model();
243
+		$related_model = $relation->get_other_model();
244
+		if ( ! isset($primary_model_query_params[0])) {
245
+			$primary_model_query_params[0] = array();
246
+		}
247
+		//check if they can access the 1st model object
248
+		$primary_model_query_params = array(
249
+			0       => $primary_model_query_params[0],
250
+			'limit' => 1,
251
+		);
252
+		if ($model instanceof \EEM_Soft_Delete_Base) {
253
+			$primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($primary_model_query_params);
254
+		}
255
+		$restricted_query_params = $primary_model_query_params;
256
+		$restricted_query_params['caps'] = $context;
257
+		$this->_set_debug_info('main model query params', $restricted_query_params);
258
+		$this->_set_debug_info('missing caps', Capabilities::get_missing_permissions_string($related_model, $context));
259
+		if (
260
+		! (
261
+			Capabilities::current_user_has_partial_access_to($related_model, $context)
262
+			&& $model->exists($restricted_query_params)
263
+		)
264
+		) {
265
+			if ($relation instanceof \EE_Belongs_To_Relation) {
266
+				$related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
267
+			} else {
268
+				$related_model_name_maybe_plural = \EEH_Inflector::pluralize_and_lower($related_model->get_this_model_name());
269
+			}
270
+			return new \WP_Error(
271
+				sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
272
+				sprintf(
273
+					__('Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
274
+						'event_espresso'),
275
+					$related_model_name_maybe_plural,
276
+					$relation->get_this_model()->get_this_model_name(),
277
+					implode(
278
+						',',
279
+						array_keys(
280
+							Capabilities::get_missing_permissions($related_model, $context)
281
+						)
282
+					)
283
+				),
284
+				array('status' => 403)
285
+			);
286
+		}
287
+		$query_params = $this->create_model_query_params($relation->get_other_model(), $request->get_params());
288
+		foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
289
+			$query_params[0][$relation->get_this_model()->get_this_model_name()
290
+							 . '.'
291
+							 . $where_condition_key] = $where_condition_value;
292
+		}
293
+		$query_params['default_where_conditions'] = 'none';
294
+		$query_params['caps'] = $context;
295
+		if ( ! $request->get_header('no_rest_headers')) {
296
+			$this->_set_headers_from_query_params($relation->get_other_model(), $query_params);
297
+		}
298
+		/** @type array $results */
299
+		$results = $relation->get_other_model()->get_all_wpdb_results($query_params);
300
+		$nice_results = array();
301
+		foreach ($results as $result) {
302
+			$nice_result = $this->create_entity_from_wpdb_result(
303
+				$relation->get_other_model(),
304
+				$result,
305
+				$request
306
+			);
307
+			if ($relation instanceof \EE_HABTM_Relation) {
308
+				//put the unusual stuff (properties from the HABTM relation) first, and make sure
309
+				//if there are conflicts we prefer the properties from the main model
310
+				$join_model_result = $this->create_entity_from_wpdb_result(
311
+					$relation->get_join_model(),
312
+					$result,
313
+					$request
314
+				);
315
+				$joined_result = array_merge($nice_result, $join_model_result);
316
+				//but keep the meta stuff from the main model
317
+				if (isset($nice_result['meta'])) {
318
+					$joined_result['meta'] = $nice_result['meta'];
319
+				}
320
+				$nice_result = $joined_result;
321
+			}
322
+			$nice_results[] = $nice_result;
323
+		}
324
+		if ($relation instanceof \EE_Belongs_To_Relation) {
325
+			return array_shift($nice_results);
326
+		} else {
327
+			return $nice_results;
328
+		}
329
+	}
330
+
331
+
332
+
333
+	/**
334
+	 * Gets the collection for given relation object
335
+	 * The same as Read::get_entities_from_model(), except if the relation
336
+	 * is a HABTM relation, in which case it merges any non-foreign-key fields from
337
+	 * the join-model-object into the results
338
+	 *
339
+	 * @param string                  $id the ID of the thing we are fetching related stuff from
340
+	 * @param \EE_Model_Relation_Base $relation
341
+	 * @param \WP_REST_Request        $request
342
+	 * @return array|\WP_Error
343
+	 * @throws \EE_Error
344
+	 */
345
+	public function get_entities_from_relation($id, $relation, $request)
346
+	{
347
+		if ( ! $relation->get_this_model()->has_primary_key_field()) {
348
+			throw new \EE_Error(
349
+				sprintf(
350
+					__('Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
351
+						'event_espresso'),
352
+					$relation->get_this_model()->get_this_model_name()
353
+				)
354
+			);
355
+		}
356
+		return $this->_get_entities_from_relation(
357
+			array(
358
+				array(
359
+					$relation->get_this_model()->primary_key_name() => $id,
360
+				),
361
+			),
362
+			$relation,
363
+			$request
364
+		);
365
+	}
366
+
367
+
368
+
369
+	/**
370
+	 * Sets the headers that are based on the model and query params,
371
+	 * like the total records. This should only be called on the original request
372
+	 * from the client, not on subsequent internal
373
+	 *
374
+	 * @param \EEM_Base $model
375
+	 * @param array     $query_params
376
+	 * @return void
377
+	 */
378
+	protected function _set_headers_from_query_params($model, $query_params)
379
+	{
380
+		$this->_set_debug_info('model query params', $query_params);
381
+		$this->_set_debug_info('missing caps',
382
+			Capabilities::get_missing_permissions_string($model, $query_params['caps']));
383
+		//normally the limit to a 2-part array, where the 2nd item is the limit
384
+		if ( ! isset($query_params['limit'])) {
385
+			$query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
386
+		}
387
+		if (is_array($query_params['limit'])) {
388
+			$limit_parts = $query_params['limit'];
389
+		} else {
390
+			$limit_parts = explode(',', $query_params['limit']);
391
+			if (count($limit_parts) == 1) {
392
+				$limit_parts = array(0, $limit_parts[0]);
393
+			}
394
+		}
395
+		//remove the group by and having parts of the query, as those will
396
+		//make the sql query return an array of values, instead of just a single value
397
+		unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
398
+		$count = $model->count($query_params, null, true);
399
+		$pages = $count / $limit_parts[1];
400
+		$this->_set_response_header('Total', $count, false);
401
+		$this->_set_response_header('PageSize', $limit_parts[1], false);
402
+		$this->_set_response_header('TotalPages', ceil($pages), false);
403
+	}
404
+
405
+
406
+
407
+	/**
408
+	 * Changes database results into REST API entities
409
+	 *
410
+	 * @param \EEM_Base        $model
411
+	 * @param array            $db_row     like results from $wpdb->get_results()
412
+	 * @param \WP_REST_Request $rest_request
413
+	 * @param string           $deprecated no longer used
414
+	 * @return array ready for being converted into json for sending to client
415
+	 */
416
+	public function create_entity_from_wpdb_result($model, $db_row, $rest_request, $deprecated = null)
417
+	{
418
+		if ( ! $rest_request instanceof \WP_REST_Request) {
419
+			//ok so this was called in the old style, where the 3rd arg was
420
+			//$include, and the 4th arg was $context
421
+			//now setup the request just to avoid fatal errors, although we won't be able
422
+			//to truly make use of it because it's kinda devoid of info
423
+			$rest_request = new \WP_REST_Request();
424
+			$rest_request->set_param('include', $rest_request);
425
+			$rest_request->set_param('caps', $deprecated);
426
+		}
427
+		if ($rest_request->get_param('caps') == null) {
428
+			$rest_request->set_param('caps', \EEM_Base::caps_read);
429
+		}
430
+		$entity_array = $this->_create_bare_entity_from_wpdb_results($model, $db_row);
431
+		$entity_array = $this->_add_extra_fields($model, $db_row, $entity_array);
432
+		$entity_array['_links'] = $this->_get_entity_links($model, $db_row, $entity_array);
433
+		$entity_array['_calculated_fields'] = $this->_get_entity_calculations($model, $db_row, $rest_request);
434
+		$entity_array = $this->_include_requested_models($model, $rest_request, $entity_array, $db_row);
435
+		$entity_array = apply_filters(
436
+			'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
437
+			$entity_array,
438
+			$model,
439
+			$rest_request->get_param('caps'),
440
+			$rest_request,
441
+			$this
442
+		);
443
+		$result_without_inaccessible_fields = Capabilities::filter_out_inaccessible_entity_fields(
444
+			$entity_array,
445
+			$model,
446
+			$rest_request->get_param('caps'),
447
+			$this->get_model_version_info(),
448
+			$model->get_index_primary_key_string(
449
+				$model->deduce_fields_n_values_from_cols_n_values($db_row)
450
+			)
451
+		);
452
+		$this->_set_debug_info(
453
+			'inaccessible fields',
454
+			array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
455
+		);
456
+		return apply_filters(
457
+			'FHEE__Read__create_entity_from_wpdb_results__entity_return',
458
+			$result_without_inaccessible_fields,
459
+			$model,
460
+			$rest_request->get_param('caps')
461
+		);
462
+	}
463
+
464
+
465
+
466
+	/**
467
+	 * Creates a REST entity array (JSON object we're going to return in the response, but
468
+	 * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
469
+	 * from $wpdb->get_row( $sql, ARRAY_A)
470
+	 *
471
+	 * @param \EEM_Base $model
472
+	 * @param array     $db_row
473
+	 * @return array entity mostly ready for converting to JSON and sending in the response
474
+	 */
475
+	protected function _create_bare_entity_from_wpdb_results(\EEM_Base $model, $db_row)
476
+	{
477
+		$result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
478
+		$result = array_intersect_key($result,
479
+			$this->get_model_version_info()->fields_on_model_in_this_version($model));
480
+		foreach ($result as $field_name => $raw_field_value) {
481
+			$field_obj = $model->field_settings_for($field_name);
482
+			$field_value = $field_obj->prepare_for_set_from_db($raw_field_value);
483
+			if ($this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_ignored())) {
484
+				unset($result[$field_name]);
485
+			} elseif (
486
+			$this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_rendered_format())
487
+			) {
488
+				$result[$field_name] = array(
489
+					'raw'      => $field_obj->prepare_for_get($field_value),
490
+					'rendered' => $field_obj->prepare_for_pretty_echoing($field_value),
491
+				);
492
+			} elseif (
493
+			$this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_pretty_format())
494
+			) {
495
+				$result[$field_name] = array(
496
+					'raw'    => $field_obj->prepare_for_get($field_value),
497
+					'pretty' => $field_obj->prepare_for_pretty_echoing($field_value),
498
+				);
499
+			} elseif ($field_obj instanceof \EE_Datetime_Field) {
500
+				if ($field_value instanceof \DateTime) {
501
+					$timezone = $field_value->getTimezone();
502
+					$field_value->setTimezone(new \DateTimeZone('UTC'));
503
+					$result[$field_name . '_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
504
+						$field_obj,
505
+						$field_value,
506
+						$this->get_model_version_info()->requested_version()
507
+					);
508
+					$field_value->setTimezone($timezone);
509
+					$result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
510
+						$field_obj,
511
+						$field_value,
512
+						$this->get_model_version_info()->requested_version()
513
+					);
514
+				}
515
+			} else {
516
+				$result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
517
+					$field_obj,
518
+					$field_obj->prepare_for_get($field_value),
519
+					$this->get_model_version_info()->requested_version()
520
+				);
521
+			}
522
+		}
523
+		return $result;
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 * Adds a few extra fields to the entity response
530
+	 *
531
+	 * @param \EEM_Base $model
532
+	 * @param array     $db_row
533
+	 * @param array     $entity_array
534
+	 * @return array modified entity
535
+	 */
536
+	protected function _add_extra_fields(\EEM_Base $model, $db_row, $entity_array)
537
+	{
538
+		if ($model instanceof \EEM_CPT_Base) {
539
+			$entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
540
+		}
541
+		return $entity_array;
542
+	}
543
+
544
+
545
+
546
+	/**
547
+	 * Gets links we want to add to the response
548
+	 *
549
+	 * @global \WP_REST_Server $wp_rest_server
550
+	 * @param \EEM_Base        $model
551
+	 * @param array            $db_row
552
+	 * @param array            $entity_array
553
+	 * @return array the _links item in the entity
554
+	 */
555
+	protected function _get_entity_links($model, $db_row, $entity_array)
556
+	{
557
+		//add basic links
558
+		$links = array();
559
+		if ($model->has_primary_key_field()) {
560
+			$links['self'] = array(
561
+				array(
562
+					'href' => $this->get_versioned_link_to(
563
+						\EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
564
+						. '/'
565
+						. $entity_array[$model->primary_key_name()]
566
+					),
567
+				),
568
+			);
569
+		}
570
+		$links['collection'] = array(
571
+			array(
572
+				'href' => $this->get_versioned_link_to(
573
+					\EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
574
+				),
575
+			),
576
+		);
577
+		//add link to the wp core endpoint, if wp api is active
578
+		global $wp_rest_server;
579
+		if ($model instanceof \EEM_CPT_Base
580
+			&& $wp_rest_server instanceof \WP_REST_Server
581
+			&& $wp_rest_server->get_route_options('/wp/v2/posts')
582
+			&& $model->has_primary_key_field()
583
+		) {
584
+			$links[\EED_Core_Rest_Api::ee_api_link_namespace . 'self_wp_post'] = array(
585
+				array(
586
+					'href'   => rest_url('/wp/v2/posts/' . $db_row[$model->get_primary_key_field()
587
+																		 ->get_qualified_column()]),
588
+					'single' => true,
589
+				),
590
+			);
591
+		}
592
+		//add links to related models
593
+		if ($model->has_primary_key_field()) {
594
+			foreach ($this->get_model_version_info()->relation_settings($model) as $relation_name => $relation_obj) {
595
+				$related_model_part = Read::get_related_entity_name($relation_name, $relation_obj);
596
+				$links[\EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
597
+					array(
598
+						'href'   => $this->get_versioned_link_to(
599
+							\EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
600
+							. '/'
601
+							. $entity_array[$model->primary_key_name()]
602
+							. '/'
603
+							. $related_model_part
604
+						),
605
+						'single' => $relation_obj instanceof \EE_Belongs_To_Relation ? true : false,
606
+					),
607
+				);
608
+			}
609
+		}
610
+		return $links;
611
+	}
612
+
613
+
614
+
615
+	/**
616
+	 * Adds the included models indicated in the request to the entity provided
617
+	 *
618
+	 * @param \EEM_Base        $model
619
+	 * @param \WP_REST_Request $rest_request
620
+	 * @param array            $entity_array
621
+	 * @param array            $db_row
622
+	 * @return array the modified entity
623
+	 */
624
+	protected function _include_requested_models(
625
+		\EEM_Base $model,
626
+		\WP_REST_Request $rest_request,
627
+		$entity_array,
628
+		$db_row = array()
629
+	) {
630
+		//if $db_row not included, hope the entity array has what we need
631
+		if ( ! $db_row) {
632
+			$db_row = $entity_array;
633
+		}
634
+		$includes_for_this_model = $this->explode_and_get_items_prefixed_with($rest_request->get_param('include'), '');
635
+		$includes_for_this_model = $this->_remove_model_names_from_array($includes_for_this_model);
636
+		//if they passed in * or didn't specify any includes, return everything
637
+		if ( ! in_array('*', $includes_for_this_model)
638
+			 && ! empty($includes_for_this_model)
639
+		) {
640
+			if ($model->has_primary_key_field()) {
641
+				//always include the primary key. ya just gotta know that at least
642
+				$includes_for_this_model[] = $model->primary_key_name();
643
+			}
644
+			if ($this->explode_and_get_items_prefixed_with($rest_request->get_param('calculate'), '')) {
645
+				$includes_for_this_model[] = '_calculated_fields';
646
+			}
647
+			$entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
648
+		}
649
+		$relation_settings = $this->get_model_version_info()->relation_settings($model);
650
+		foreach ($relation_settings as $relation_name => $relation_obj) {
651
+			$related_fields_to_include = $this->explode_and_get_items_prefixed_with(
652
+				$rest_request->get_param('include'),
653
+				$relation_name
654
+			);
655
+			$related_fields_to_calculate = $this->explode_and_get_items_prefixed_with(
656
+				$rest_request->get_param('calculate'),
657
+				$relation_name
658
+			);
659
+			//did they specify they wanted to include a related model, or
660
+			//specific fields from a related model?
661
+			//or did they specify to calculate a field from a related model?
662
+			if ($related_fields_to_include || $related_fields_to_calculate) {
663
+				//if so, we should include at least some part of the related model
664
+				$pretend_related_request = new \WP_REST_Request();
665
+				$pretend_related_request->set_query_params(
666
+					array(
667
+						'caps'      => $rest_request->get_param('caps'),
668
+						'include'   => $related_fields_to_include,
669
+						'calculate' => $related_fields_to_calculate,
670
+					)
671
+				);
672
+				$pretend_related_request->add_header('no_rest_headers', true);
673
+				$primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
674
+					$model->get_index_primary_key_string(
675
+						$model->deduce_fields_n_values_from_cols_n_values($db_row)
676
+					)
677
+				);
678
+				$related_results = $this->_get_entities_from_relation(
679
+					$primary_model_query_params,
680
+					$relation_obj,
681
+					$pretend_related_request
682
+				);
683
+				$entity_array[Read::get_related_entity_name($relation_name, $relation_obj)] = $related_results
684
+																							  instanceof
685
+																							  \WP_Error
686
+					? null
687
+					: $related_results;
688
+			}
689
+		}
690
+		return $entity_array;
691
+	}
692
+
693
+
694
+
695
+	/**
696
+	 * Returns a new array with all the names of models removed. Eg
697
+	 * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
698
+	 *
699
+	 * @param array $arr
700
+	 * @return array
701
+	 */
702
+	private function _remove_model_names_from_array($arr)
703
+	{
704
+		return array_diff($arr, array_keys(\EE_Registry::instance()->non_abstract_db_models));
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 * Gets the calculated fields for the response
711
+	 *
712
+	 * @param \EEM_Base        $model
713
+	 * @param array            $wpdb_row
714
+	 * @param \WP_REST_Request $rest_request
715
+	 * @return \stdClass the _calculations item in the entity
716
+	 */
717
+	protected function _get_entity_calculations($model, $wpdb_row, $rest_request)
718
+	{
719
+		$calculated_fields = $this->explode_and_get_items_prefixed_with(
720
+			$rest_request->get_param('calculate'),
721
+			''
722
+		);
723
+		//note: setting calculate=* doesn't do anything
724
+		$calculated_fields_to_return = new \stdClass();
725
+		foreach ($calculated_fields as $field_to_calculate) {
726
+			try {
727
+				$calculated_fields_to_return->$field_to_calculate = Model_Data_Translator::prepare_field_value_for_json(
728
+					null,
729
+					$this->_fields_calculator->retrieve_calculated_field_value(
730
+						$model,
731
+						$field_to_calculate,
732
+						$wpdb_row,
733
+						$rest_request,
734
+						$this
735
+					),
736
+					$this->get_model_version_info()->requested_version()
737
+				);
738
+			} catch (Rest_Exception $e) {
739
+				//if we don't have permission to read it, just leave it out. but let devs know about the problem
740
+				$this->_set_response_header(
741
+					'Notices-Field-Calculation-Errors['
742
+					. $e->get_string_code()
743
+					. ']['
744
+					. $model->get_this_model_name()
745
+					. ']['
746
+					. $field_to_calculate
747
+					. ']',
748
+					$e->getMessage(),
749
+					true
750
+				);
751
+			}
752
+		}
753
+		return $calculated_fields_to_return;
754
+	}
755
+
756
+
757
+
758
+	/**
759
+	 * Gets the full URL to the resource, taking the requested version into account
760
+	 *
761
+	 * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
762
+	 * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
763
+	 */
764
+	public function get_versioned_link_to($link_part_after_version_and_slash)
765
+	{
766
+		return rest_url(
767
+			\EED_Core_Rest_Api::ee_api_namespace
768
+			. $this->get_model_version_info()->requested_version()
769
+			. '/'
770
+			. $link_part_after_version_and_slash
771
+		);
772
+	}
773
+
774
+
775
+
776
+	/**
777
+	 * Gets the correct lowercase name for the relation in the API according
778
+	 * to the relation's type
779
+	 *
780
+	 * @param string                  $relation_name
781
+	 * @param \EE_Model_Relation_Base $relation_obj
782
+	 * @return string
783
+	 */
784
+	public static function get_related_entity_name($relation_name, $relation_obj)
785
+	{
786
+		if ($relation_obj instanceof \EE_Belongs_To_Relation) {
787
+			return strtolower($relation_name);
788
+		} else {
789
+			return \EEH_Inflector::pluralize_and_lower($relation_name);
790
+		}
791
+	}
792
+
793
+
794
+
795
+	/**
796
+	 * Gets the one model object with the specified id for the specified model
797
+	 *
798
+	 * @param \EEM_Base        $model
799
+	 * @param \WP_REST_Request $request
800
+	 * @return array|\WP_Error
801
+	 */
802
+	public function get_entity_from_model($model, $request)
803
+	{
804
+		$query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
805
+		if ($model instanceof \EEM_Soft_Delete_Base) {
806
+			$query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
807
+		}
808
+		$restricted_query_params = $query_params;
809
+		$restricted_query_params['caps'] = $this->validate_context($request->get_param('caps'));
810
+		$this->_set_debug_info('model query params', $restricted_query_params);
811
+		$model_rows = $model->get_all_wpdb_results($restricted_query_params);
812
+		if ( ! empty ($model_rows)) {
813
+			return $this->create_entity_from_wpdb_result(
814
+				$model,
815
+				array_shift($model_rows),
816
+				$request);
817
+		} else {
818
+			//ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
819
+			$lowercase_model_name = strtolower($model->get_this_model_name());
820
+			$model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
821
+			if ( ! empty($model_rows_found_sans_restrictions)) {
822
+				//you got shafted- it existed but we didn't want to tell you!
823
+				return new \WP_Error(
824
+					'rest_user_cannot_read',
825
+					sprintf(
826
+						__('Sorry, you cannot read this %1$s. Missing permissions are: %2$s', 'event_espresso'),
827
+						strtolower($model->get_this_model_name()),
828
+						Capabilities::get_missing_permissions_string(
829
+							$model,
830
+							$this->validate_context($request->get_param('caps')))
831
+					),
832
+					array('status' => 403)
833
+				);
834
+			} else {
835
+				//it's not you. It just doesn't exist
836
+				return new \WP_Error(
837
+					sprintf('rest_%s_invalid_id', $lowercase_model_name),
838
+					sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
839
+					array('status' => 404)
840
+				);
841
+			}
842
+		}
843
+	}
844
+
845
+
846
+
847
+	/**
848
+	 * If a context is provided which isn't valid, maybe it was added in a future
849
+	 * version so just treat it as a default read
850
+	 *
851
+	 * @param string $context
852
+	 * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
853
+	 */
854
+	public function validate_context($context)
855
+	{
856
+		if ( ! $context) {
857
+			$context = \EEM_Base::caps_read;
858
+		}
859
+		$valid_contexts = \EEM_Base::valid_cap_contexts();
860
+		if (in_array($context, $valid_contexts)) {
861
+			return $context;
862
+		} else {
863
+			return \EEM_Base::caps_read;
864
+		}
865
+	}
866
+
867
+
868
+
869
+	/**
870
+	 * Verifies the passed in value is an allowable default where conditions value.
871
+	 * @param $default_query_params
872
+	 * @return string
873
+	 */
874
+	public function validate_default_query_params( $default_query_params ) {
875
+		$valid_default_where_conditions_for_api_calls = array(
876
+			\EEM_Base::default_where_conditions_all,
877
+			\EEM_Base::default_where_conditions_minimum_all,
878
+			\EEM_Base::default_where_conditions_minimum_others
879
+		);
880
+		if ( ! $default_query_params ) {
881
+			$default_query_params = \EEM_Base::default_where_conditions_all;
882
+		}
883
+		if(
884
+			in_array(
885
+				$default_query_params,
886
+				$valid_default_where_conditions_for_api_calls,
887
+				true
888
+			)
889
+		) {
890
+			return $default_query_params;
891
+		} else {
892
+			return \EEM_Base::default_where_conditions_all;
893
+		}
894
+	}
895
+
896
+
897
+
898
+	/**
899
+	 * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
900
+	 * Note: right now the query parameter keys for fields (and related fields)
901
+	 * can be left as-is, but it's quite possible this will change someday.
902
+	 * Also, this method's contents might be candidate for moving to Model_Data_Translator
903
+	 *
904
+	 * @param \EEM_Base $model
905
+	 * @param array     $query_parameters from $_GET parameter @see Read:handle_request_get_all
906
+	 * @return array like what EEM_Base::get_all() expects or FALSE to indicate
907
+	 *                                    that absolutely no results should be returned
908
+	 * @throws \EE_Error
909
+	 */
910
+	public function create_model_query_params($model, $query_parameters)
911
+	{
912
+		$model_query_params = array();
913
+		if (isset($query_parameters['where'])) {
914
+			$model_query_params[0] = Model_Data_Translator::prepare_conditions_query_params_for_models(
915
+				$query_parameters['where'],
916
+				$model,
917
+				$this->get_model_version_info()->requested_version()
918
+			);
919
+		}
920
+		if (isset($query_parameters['order_by'])) {
921
+			$order_by = $query_parameters['order_by'];
922
+		} elseif (isset($query_parameters['orderby'])) {
923
+			$order_by = $query_parameters['orderby'];
924
+		} else {
925
+			$order_by = null;
926
+		}
927
+		if ($order_by !== null) {
928
+			if (is_array($order_by)) {
929
+				$order_by = Model_Data_Translator::prepare_field_names_in_array_keys_from_json($order_by);
930
+			} else {
931
+				//it's a single item
932
+				$order_by = Model_Data_Translator::prepare_field_name_from_json($order_by);
933
+			}
934
+			$model_query_params['order_by'] = $order_by;
935
+		}
936
+		if (isset($query_parameters['group_by'])) {
937
+			$group_by = $query_parameters['group_by'];
938
+		} elseif (isset($query_parameters['groupby'])) {
939
+			$group_by = $query_parameters['groupby'];
940
+		} else {
941
+			$group_by = array_keys($model->get_combined_primary_key_fields());
942
+		}
943
+		//make sure they're all real names
944
+		if (is_array($group_by)) {
945
+			$group_by = Model_Data_Translator::prepare_field_names_from_json($group_by);
946
+		}
947
+		if ($group_by !== null) {
948
+			$model_query_params['group_by'] = $group_by;
949
+		}
950
+		if (isset($query_parameters['having'])) {
951
+			$model_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_models(
952
+				$query_parameters['having'],
953
+				$model,
954
+				$this->get_model_version_info()->requested_version()
955
+			);
956
+		}
957
+		if (isset($query_parameters['order'])) {
958
+			$model_query_params['order'] = $query_parameters['order'];
959
+		}
960
+		if (isset($query_parameters['mine'])) {
961
+			$model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
962
+		}
963
+		if (isset($query_parameters['limit'])) {
964
+			//limit should be either a string like '23' or '23,43', or an array with two items in it
965
+			if ( ! is_array($query_parameters['limit'])) {
966
+				$limit_array = explode(',', (string)$query_parameters['limit']);
967
+			} else {
968
+				$limit_array = $query_parameters['limit'];
969
+			}
970
+			$sanitized_limit = array();
971
+			foreach ($limit_array as $key => $limit_part) {
972
+				if ($this->_debug_mode && ( ! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
973
+					throw new \EE_Error(
974
+						sprintf(
975
+							__('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.',
976
+								'event_espresso'),
977
+							wp_json_encode($query_parameters['limit'])
978
+						)
979
+					);
980
+				}
981
+				$sanitized_limit[] = (int)$limit_part;
982
+			}
983
+			$model_query_params['limit'] = implode(',', $sanitized_limit);
984
+		} else {
985
+			$model_query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
986
+		}
987
+		if (isset($query_parameters['caps'])) {
988
+			$model_query_params['caps'] = $this->validate_context($query_parameters['caps']);
989
+		} else {
990
+			$model_query_params['caps'] = \EEM_Base::caps_read;
991
+		}
992
+		if (isset($query_parameters['default_query_params'])) {
993
+			$model_query_params['default_where_conditions'] = $this->validate_default_query_params($query_parameters['default_where_conditions']);
994
+		}
995
+		return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
996
+	}
997
+
998
+
999
+
1000
+	/**
1001
+	 * Changes the REST-style query params for use in the models
1002
+	 *
1003
+	 * @deprecated
1004
+	 * @param \EEM_Base $model
1005
+	 * @param array     $query_params sub-array from @see EEM_Base::get_all()
1006
+	 * @return array
1007
+	 */
1008
+	public function prepare_rest_query_params_key_for_models($model, $query_params)
1009
+	{
1010
+		$model_ready_query_params = array();
1011
+		foreach ($query_params as $key => $value) {
1012
+			if (is_array($value)) {
1013
+				$model_ready_query_params[$key] = $this->prepare_rest_query_params_key_for_models($model, $value);
1014
+			} else {
1015
+				$model_ready_query_params[$key] = $value;
1016
+			}
1017
+		}
1018
+		return $model_ready_query_params;
1019
+	}
1020
+
1021
+
1022
+
1023
+	/**
1024
+	 * @deprecated
1025
+	 * @param $model
1026
+	 * @param $query_params
1027
+	 * @return array
1028
+	 */
1029
+	public function prepare_rest_query_params_values_for_models($model, $query_params)
1030
+	{
1031
+		$model_ready_query_params = array();
1032
+		foreach ($query_params as $key => $value) {
1033
+			if (is_array($value)) {
1034
+				$model_ready_query_params[$key] = $this->prepare_rest_query_params_values_for_models($model, $value);
1035
+			} else {
1036
+				$model_ready_query_params[$key] = $value;
1037
+			}
1038
+		}
1039
+		return $model_ready_query_params;
1040
+	}
1041
+
1042
+
1043
+
1044
+	/**
1045
+	 * Explodes the string on commas, and only returns items with $prefix followed by a period.
1046
+	 * If no prefix is specified, returns items with no period.
1047
+	 *
1048
+	 * @param string|array $string_to_explode eg "jibba,jabba, blah, blaabla" or array('jibba', 'jabba' )
1049
+	 * @param string       $prefix            "Event" or "foobar"
1050
+	 * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1051
+	 *                                        we only return strings starting with that and a period; if no prefix was
1052
+	 *                                        specified we return all items containing NO periods
1053
+	 */
1054
+	public function explode_and_get_items_prefixed_with($string_to_explode, $prefix)
1055
+	{
1056
+		if (is_string($string_to_explode)) {
1057
+			$exploded_contents = explode(',', $string_to_explode);
1058
+		} else if (is_array($string_to_explode)) {
1059
+			$exploded_contents = $string_to_explode;
1060
+		} else {
1061
+			$exploded_contents = array();
1062
+		}
1063
+		//if the string was empty, we want an empty array
1064
+		$exploded_contents = array_filter($exploded_contents);
1065
+		$contents_with_prefix = array();
1066
+		foreach ($exploded_contents as $item) {
1067
+			$item = trim($item);
1068
+			//if no prefix was provided, so we look for items with no "." in them
1069
+			if ( ! $prefix) {
1070
+				//does this item have a period?
1071
+				if (strpos($item, '.') === false) {
1072
+					//if not, then its what we're looking for
1073
+					$contents_with_prefix[] = $item;
1074
+				}
1075
+			} else if (strpos($item, $prefix . '.') === 0) {
1076
+				//this item has the prefix and a period, grab it
1077
+				$contents_with_prefix[] = substr(
1078
+					$item,
1079
+					strpos($item, $prefix . '.') + strlen($prefix . '.')
1080
+				);
1081
+			} else if ($item === $prefix) {
1082
+				//this item is JUST the prefix
1083
+				//so let's grab everything after, which is a blank string
1084
+				$contents_with_prefix[] = '';
1085
+			}
1086
+		}
1087
+		return $contents_with_prefix;
1088
+	}
1089
+
1090
+
1091
+
1092
+	/**
1093
+	 * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1094
+	 * Deprecated because its return values were really quite confusing- sometimes it returned
1095
+	 * an empty array (when the include string was blank or '*') or sometimes it returned
1096
+	 * array('*') (when you provided a model and a model of that kind was found).
1097
+	 * Parses the $include_string so we fetch all the field names relating to THIS model
1098
+	 * (ie have NO period in them), or for the provided model (ie start with the model
1099
+	 * name and then a period).
1100
+	 * @param string $include_string @see Read:handle_request_get_all
1101
+	 * @param string $model_name
1102
+	 * @return array of fields for this model. If $model_name is provided, then
1103
+	 *                               the fields for that model, with the model's name removed from each.
1104
+	 *                               If $include_string was blank or '*' returns an empty array
1105
+	 */
1106
+	public function extract_includes_for_this_model($include_string, $model_name = null)
1107
+	{
1108
+		if (is_array($include_string)) {
1109
+			$include_string = implode(',', $include_string);
1110
+		}
1111
+		if ($include_string === '*' || $include_string === '') {
1112
+			return array();
1113
+		}
1114
+		$includes = explode(',', $include_string);
1115
+		$extracted_fields_to_include = array();
1116
+		if ($model_name) {
1117
+			foreach ($includes as $field_to_include) {
1118
+				$field_to_include = trim($field_to_include);
1119
+				if (strpos($field_to_include, $model_name . '.') === 0) {
1120
+					//found the model name at the exact start
1121
+					$field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1122
+					$extracted_fields_to_include[] = $field_sans_model_name;
1123
+				} elseif ($field_to_include == $model_name) {
1124
+					$extracted_fields_to_include[] = '*';
1125
+				}
1126
+			}
1127
+		} else {
1128
+			//look for ones with no period
1129
+			foreach ($includes as $field_to_include) {
1130
+				$field_to_include = trim($field_to_include);
1131
+				if (
1132
+					strpos($field_to_include, '.') === false
1133
+					&& ! $this->get_model_version_info()->is_model_name_in_this_version($field_to_include)
1134
+				) {
1135
+					$extracted_fields_to_include[] = $field_to_include;
1136
+				}
1137
+			}
1138
+		}
1139
+		return $extracted_fields_to_include;
1140
+	}
1141 1141
 }
1142 1142
 
1143 1143
 
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
         try {
56 56
             $matches = $controller->parse_route(
57 57
                 $request->get_route(),
58
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)~',
58
+                '~'.\EED_Core_Rest_Api::ee_api_namespace_for_regex.'(.*)~',
59 59
                 array('version', 'model')
60 60
             );
61 61
             $controller->set_requested_version($matches['version']);
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
         try {
98 98
             $matches = $controller->parse_route(
99 99
                 $request->get_route(),
100
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)~',
100
+                '~'.\EED_Core_Rest_Api::ee_api_namespace_for_regex.'(.*)/(.*)~',
101 101
                 array('version', 'model', 'id'));
102 102
             $controller->set_requested_version($matches['version']);
103 103
             $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
         try {
140 140
             $matches = $controller->parse_route(
141 141
                 $request->get_route(),
142
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)/(.*)~',
142
+                '~'.\EED_Core_Rest_Api::ee_api_namespace_for_regex.'(.*)/(.*)/(.*)~',
143 143
                 array('version', 'model', 'id', 'related_model')
144 144
             );
145 145
             $controller->set_requested_version($matches['version']);
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
                 if ($field_value instanceof \DateTime) {
501 501
                     $timezone = $field_value->getTimezone();
502 502
                     $field_value->setTimezone(new \DateTimeZone('UTC'));
503
-                    $result[$field_name . '_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
503
+                    $result[$field_name.'_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
504 504
                         $field_obj,
505 505
                         $field_value,
506 506
                         $this->get_model_version_info()->requested_version()
@@ -581,9 +581,9 @@  discard block
 block discarded – undo
581 581
             && $wp_rest_server->get_route_options('/wp/v2/posts')
582 582
             && $model->has_primary_key_field()
583 583
         ) {
584
-            $links[\EED_Core_Rest_Api::ee_api_link_namespace . 'self_wp_post'] = array(
584
+            $links[\EED_Core_Rest_Api::ee_api_link_namespace.'self_wp_post'] = array(
585 585
                 array(
586
-                    'href'   => rest_url('/wp/v2/posts/' . $db_row[$model->get_primary_key_field()
586
+                    'href'   => rest_url('/wp/v2/posts/'.$db_row[$model->get_primary_key_field()
587 587
                                                                          ->get_qualified_column()]),
588 588
                     'single' => true,
589 589
                 ),
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
         if ($model->has_primary_key_field()) {
594 594
             foreach ($this->get_model_version_info()->relation_settings($model) as $relation_name => $relation_obj) {
595 595
                 $related_model_part = Read::get_related_entity_name($relation_name, $relation_obj);
596
-                $links[\EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
596
+                $links[\EED_Core_Rest_Api::ee_api_link_namespace.$related_model_part] = array(
597 597
                     array(
598 598
                         'href'   => $this->get_versioned_link_to(
599 599
                             \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
@@ -871,16 +871,16 @@  discard block
 block discarded – undo
871 871
      * @param $default_query_params
872 872
      * @return string
873 873
      */
874
-    public function validate_default_query_params( $default_query_params ) {
874
+    public function validate_default_query_params($default_query_params) {
875 875
         $valid_default_where_conditions_for_api_calls = array(
876 876
             \EEM_Base::default_where_conditions_all,
877 877
             \EEM_Base::default_where_conditions_minimum_all,
878 878
             \EEM_Base::default_where_conditions_minimum_others
879 879
         );
880
-        if ( ! $default_query_params ) {
880
+        if ( ! $default_query_params) {
881 881
             $default_query_params = \EEM_Base::default_where_conditions_all;
882 882
         }
883
-        if(
883
+        if (
884 884
             in_array(
885 885
                 $default_query_params,
886 886
                 $valid_default_where_conditions_for_api_calls,
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
         if (isset($query_parameters['limit'])) {
964 964
             //limit should be either a string like '23' or '23,43', or an array with two items in it
965 965
             if ( ! is_array($query_parameters['limit'])) {
966
-                $limit_array = explode(',', (string)$query_parameters['limit']);
966
+                $limit_array = explode(',', (string) $query_parameters['limit']);
967 967
             } else {
968 968
                 $limit_array = $query_parameters['limit'];
969 969
             }
@@ -978,7 +978,7 @@  discard block
 block discarded – undo
978 978
                         )
979 979
                     );
980 980
                 }
981
-                $sanitized_limit[] = (int)$limit_part;
981
+                $sanitized_limit[] = (int) $limit_part;
982 982
             }
983 983
             $model_query_params['limit'] = implode(',', $sanitized_limit);
984 984
         } else {
@@ -1072,11 +1072,11 @@  discard block
 block discarded – undo
1072 1072
                     //if not, then its what we're looking for
1073 1073
                     $contents_with_prefix[] = $item;
1074 1074
                 }
1075
-            } else if (strpos($item, $prefix . '.') === 0) {
1075
+            } else if (strpos($item, $prefix.'.') === 0) {
1076 1076
                 //this item has the prefix and a period, grab it
1077 1077
                 $contents_with_prefix[] = substr(
1078 1078
                     $item,
1079
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1079
+                    strpos($item, $prefix.'.') + strlen($prefix.'.')
1080 1080
                 );
1081 1081
             } else if ($item === $prefix) {
1082 1082
                 //this item is JUST the prefix
@@ -1116,9 +1116,9 @@  discard block
 block discarded – undo
1116 1116
         if ($model_name) {
1117 1117
             foreach ($includes as $field_to_include) {
1118 1118
                 $field_to_include = trim($field_to_include);
1119
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1119
+                if (strpos($field_to_include, $model_name.'.') === 0) {
1120 1120
                     //found the model name at the exact start
1121
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1121
+                    $field_sans_model_name = str_replace($model_name.'.', '', $field_to_include);
1122 1122
                     $extracted_fields_to_include[] = $field_sans_model_name;
1123 1123
                 } elseif ($field_to_include == $model_name) {
1124 1124
                     $extracted_fields_to_include[] = '*';
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +5639 added lines, -5639 removed lines patch added patch discarded remove patch
@@ -29,5647 +29,5647 @@
 block discarded – undo
29 29
 abstract class EEM_Base extends EE_Base
30 30
 {
31 31
 
32
-    //admin posty
33
-    //basic -> grants access to mine -> if they don't have it, select none
34
-    //*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
-    //*_published -> grants access to published -> if they dont have it, select non-published
37
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
39
-    //frontend posty
40
-    //by default has access to published
41
-    //basic -> grants access to mine that arent published, and all published
42
-    //*_others ->grants access to others that arent private, all mine
43
-    //*_private -> grants full access
44
-    //frontend non-posty
45
-    //like admin posty
46
-    //category-y
47
-    //assign -> grants access to join-table
48
-    //(delete, edit)
49
-    //payment-method-y
50
-    //for each registered payment method,
51
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
-    /**
53
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
-     * They almost always WILL NOT, but it's not necessarily a requirement.
56
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
-     *
58
-     * @var boolean
59
-     */
60
-    private $_values_already_prepared_by_model_object = 0;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the data is just like form input that needs to have the model fields'
65
-     * prepare_for_set and prepare_for_use_in_db called on it
66
-     */
67
-    const not_prepared_by_model_object = 0;
68
-
69
-    /**
70
-     * when $_values_already_prepared_by_model_object equals this, we
71
-     * assume this value is coming from a model object and doesn't need to have
72
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
73
-     */
74
-    const prepared_by_model_object = 1;
75
-
76
-    /**
77
-     * when $_values_already_prepared_by_model_object equals this, we assume
78
-     * the values are already to be used in the database (ie no processing is done
79
-     * on them by the model's fields)
80
-     */
81
-    const prepared_for_use_in_db = 2;
82
-
83
-
84
-    protected $singular_item = 'Item';
85
-
86
-    protected $plural_item   = 'Items';
87
-
88
-    /**
89
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
-     */
91
-    protected $_tables;
92
-
93
-    /**
94
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
-     *
98
-     * @var \EE_Model_Field_Base[] $_fields
99
-     */
100
-    protected $_fields;
101
-
102
-    /**
103
-     * array of different kinds of relations
104
-     *
105
-     * @var \EE_Model_Relation_Base[] $_model_relations
106
-     */
107
-    protected $_model_relations;
108
-
109
-    /**
110
-     * @var \EE_Index[] $_indexes
111
-     */
112
-    protected $_indexes = array();
113
-
114
-    /**
115
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
116
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
-     * by setting the same columns as used in these queries in the query yourself.
118
-     *
119
-     * @var EE_Default_Where_Conditions
120
-     */
121
-    protected $_default_where_conditions_strategy;
122
-
123
-    /**
124
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
-     * This is particularly useful when you want something between 'none' and 'default'
126
-     *
127
-     * @var EE_Default_Where_Conditions
128
-     */
129
-    protected $_minimum_where_conditions_strategy;
130
-
131
-    /**
132
-     * String describing how to find the "owner" of this model's objects.
133
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
-     * But when there isn't, this indicates which related model, or transiently-related model,
135
-     * has the foreign key to the wp_users table.
136
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
-     * related to events, and events have a foreign key to wp_users.
138
-     * On EEM_Transaction, this would be 'Transaction.Event'
139
-     *
140
-     * @var string
141
-     */
142
-    protected $_model_chain_to_wp_user = '';
143
-
144
-    /**
145
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
-     * don't need it (particularly CPT models)
147
-     *
148
-     * @var bool
149
-     */
150
-    protected $_ignore_where_strategy = false;
151
-
152
-    /**
153
-     * String used in caps relating to this model. Eg, if the caps relating to this
154
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
-     *
156
-     * @var string. If null it hasn't been initialized yet. If false then we
157
-     * have indicated capabilities don't apply to this
158
-     */
159
-    protected $_caps_slug = null;
160
-
161
-    /**
162
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
-     * and next-level keys are capability names, and each's value is a
164
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
-     * they specify which context to use (ie, frontend, backend, edit or delete)
166
-     * and then each capability in the corresponding sub-array that they're missing
167
-     * adds the where conditions onto the query.
168
-     *
169
-     * @var array
170
-     */
171
-    protected $_cap_restrictions = array(
172
-        self::caps_read       => array(),
173
-        self::caps_read_admin => array(),
174
-        self::caps_edit       => array(),
175
-        self::caps_delete     => array(),
176
-    );
177
-
178
-    /**
179
-     * Array defining which cap restriction generators to use to create default
180
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
181
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
-     * automatically set this to false (not just null).
184
-     *
185
-     * @var EE_Restriction_Generator_Base[]
186
-     */
187
-    protected $_cap_restriction_generators = array();
188
-
189
-    /**
190
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
-     */
192
-    const caps_read       = 'read';
193
-
194
-    const caps_read_admin = 'read_admin';
195
-
196
-    const caps_edit       = 'edit';
197
-
198
-    const caps_delete     = 'delete';
199
-
200
-    /**
201
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
-     * maps to 'read' because when looking for relevant permissions we're going to use
204
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
205
-     *
206
-     * @var array
207
-     */
208
-    protected $_cap_contexts_to_cap_action_map = array(
209
-        self::caps_read       => 'read',
210
-        self::caps_read_admin => 'read',
211
-        self::caps_edit       => 'edit',
212
-        self::caps_delete     => 'delete',
213
-    );
214
-
215
-    /**
216
-     * Timezone
217
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
-     * EE_Datetime_Field data type will have access to it.
221
-     *
222
-     * @var string
223
-     */
224
-    protected $_timezone;
225
-
226
-
227
-    /**
228
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
-     * multisite.
230
-     *
231
-     * @var int
232
-     */
233
-    protected static $_model_query_blog_id;
234
-
235
-    /**
236
-     * A copy of _fields, except the array keys are the model names pointed to by
237
-     * the field
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cache_foreign_key_to_fields = array();
242
-
243
-    /**
244
-     * Cached list of all the fields on the model, indexed by their name
245
-     *
246
-     * @var EE_Model_Field_Base[]
247
-     */
248
-    private $_cached_fields = null;
249
-
250
-    /**
251
-     * Cached list of all the fields on the model, except those that are
252
-     * marked as only pertinent to the database
253
-     *
254
-     * @var EE_Model_Field_Base[]
255
-     */
256
-    private $_cached_fields_non_db_only = null;
257
-
258
-    /**
259
-     * A cached reference to the primary key for quick lookup
260
-     *
261
-     * @var EE_Model_Field_Base
262
-     */
263
-    private $_primary_key_field = null;
264
-
265
-    /**
266
-     * Flag indicating whether this model has a primary key or not
267
-     *
268
-     * @var boolean
269
-     */
270
-    protected $_has_primary_key_field = null;
271
-
272
-    /**
273
-     * Whether or not this model is based off a table in WP core only (CPTs should set
274
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
-     *
276
-     * @var boolean
277
-     */
278
-    protected $_wp_core_model = false;
279
-
280
-    /**
281
-     *    List of valid operators that can be used for querying.
282
-     * The keys are all operators we'll accept, the values are the real SQL
283
-     * operators used
284
-     *
285
-     * @var array
286
-     */
287
-    protected $_valid_operators = array(
288
-        '='           => '=',
289
-        '<='          => '<=',
290
-        '<'           => '<',
291
-        '>='          => '>=',
292
-        '>'           => '>',
293
-        '!='          => '!=',
294
-        'LIKE'        => 'LIKE',
295
-        'like'        => 'LIKE',
296
-        'NOT_LIKE'    => 'NOT LIKE',
297
-        'not_like'    => 'NOT LIKE',
298
-        'NOT LIKE'    => 'NOT LIKE',
299
-        'not like'    => 'NOT LIKE',
300
-        'IN'          => 'IN',
301
-        'in'          => 'IN',
302
-        'NOT_IN'      => 'NOT IN',
303
-        'not_in'      => 'NOT IN',
304
-        'NOT IN'      => 'NOT IN',
305
-        'not in'      => 'NOT IN',
306
-        'between'     => 'BETWEEN',
307
-        'BETWEEN'     => 'BETWEEN',
308
-        'IS_NOT_NULL' => 'IS NOT NULL',
309
-        'is_not_null' => 'IS NOT NULL',
310
-        'IS NOT NULL' => 'IS NOT NULL',
311
-        'is not null' => 'IS NOT NULL',
312
-        'IS_NULL'     => 'IS NULL',
313
-        'is_null'     => 'IS NULL',
314
-        'IS NULL'     => 'IS NULL',
315
-        'is null'     => 'IS NULL',
316
-        'REGEXP'      => 'REGEXP',
317
-        'regexp'      => 'REGEXP',
318
-        'NOT_REGEXP'  => 'NOT REGEXP',
319
-        'not_regexp'  => 'NOT REGEXP',
320
-        'NOT REGEXP'  => 'NOT REGEXP',
321
-        'not regexp'  => 'NOT REGEXP',
322
-    );
323
-
324
-    /**
325
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
-     *
327
-     * @var array
328
-     */
329
-    protected $_in_style_operators = array('IN', 'NOT IN');
330
-
331
-    /**
332
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
-     * '12-31-2012'"
334
-     *
335
-     * @var array
336
-     */
337
-    protected $_between_style_operators = array('BETWEEN');
338
-
339
-    /**
340
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
-     * on a join table.
342
-     *
343
-     * @var array
344
-     */
345
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
-
347
-    /**
348
-     * Allowed values for $query_params['order'] for ordering in queries
349
-     *
350
-     * @var array
351
-     */
352
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
-
354
-    /**
355
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
357
-     *
358
-     * @var array
359
-     */
360
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
-
362
-    /**
363
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
365
-     *
366
-     * @var array
367
-     */
368
-    private $_allowed_query_params = array(
369
-        0,
370
-        'limit',
371
-        'order_by',
372
-        'group_by',
373
-        'having',
374
-        'force_join',
375
-        'order',
376
-        'on_join_limit',
377
-        'default_where_conditions',
378
-        'caps',
379
-    );
380
-
381
-    /**
382
-     * All the data types that can be used in $wpdb->prepare statements.
383
-     *
384
-     * @var array
385
-     */
386
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
-
388
-    /**
389
-     *    EE_Registry Object
390
-     *
391
-     * @var    object
392
-     * @access    protected
393
-     */
394
-    protected $EE = null;
395
-
396
-
397
-    /**
398
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
-     *
400
-     * @var int
401
-     */
402
-    protected $_show_next_x_db_queries = 0;
403
-
404
-    /**
405
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
-     *
408
-     * @var array
409
-     */
410
-    protected $_custom_selections = array();
411
-
412
-    /**
413
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
-     * caches every model object we've fetched from the DB on this request
415
-     *
416
-     * @var array
417
-     */
418
-    protected $_entity_map;
419
-
420
-    /**
421
-     * constant used to show EEM_Base has not yet verified the db on this http request
422
-     */
423
-    const db_verified_none = 0;
424
-
425
-    /**
426
-     * constant used to show EEM_Base has verified the EE core db on this http request,
427
-     * but not the addons' dbs
428
-     */
429
-    const db_verified_core = 1;
430
-
431
-    /**
432
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
-     * the EE core db too)
434
-     */
435
-    const db_verified_addons = 2;
436
-
437
-    /**
438
-     * indicates whether an EEM_Base child has already re-verified the DB
439
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
440
-     * looking like EEM_Base::db_verified_*
441
-     *
442
-     * @var int - 0 = none, 1 = core, 2 = addons
443
-     */
444
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
445
-
446
-    /**
447
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
448
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed registrations
449
-     *        for non-trashed tickets for non-trashed datetimes)
450
-     */
451
-    const default_where_conditions_all = 'all';
452
-
453
-    /**
454
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
455
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
456
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
457
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
458
-     *        models which share tables with other models, this can return data for the wrong model.
459
-     */
460
-    const default_where_conditions_this_only = 'this_model_only';
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
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
469
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
470
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
471
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
472
-     *        (regardless of whether those events and venues are trashed)
473
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE events.
474
-     */
475
-    const default_where_conditions_minimum_all = 'minimum';
476
-    /**
477
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
478
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will return
479
-     *        non-trashed events for any venues, regardless of whether those associated venues are trashed or not)
480
-     */
481
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
482
-    /**
483
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be used,
484
-     *        because when querying from a model which shares its table with another model (eg Events and Venues)
485
-     *        it's possible it will return table entries for other models. You should use EEM_Base::default_where_conditions_minimum_all
486
-     *        instead.
487
-     */
488
-    const default_where_conditions_none = 'none';
489
-
490
-
491
-
492
-    /**
493
-     * About all child constructors:
494
-     * they should define the _tables, _fields and _model_relations arrays.
495
-     * Should ALWAYS be called after child constructor.
496
-     * In order to make the child constructors to be as simple as possible, this parent constructor
497
-     * finalizes constructing all the object's attributes.
498
-     * Generally, rather than requiring a child to code
499
-     * $this->_tables = array(
500
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
501
-     *        ...);
502
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
503
-     * each EE_Table has a function to set the table's alias after the constructor, using
504
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
505
-     * do something similar.
506
-     *
507
-     * @param null $timezone
508
-     * @throws \EE_Error
509
-     */
510
-    protected function __construct($timezone = null)
511
-    {
512
-        // check that the model has not been loaded too soon
513
-        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
514
-            throw new EE_Error (
515
-                sprintf(
516
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
517
-                        'event_espresso'),
518
-                    get_class($this)
519
-                )
520
-            );
521
-        }
522
-        /**
523
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
524
-         */
525
-        if (empty(EEM_Base::$_model_query_blog_id)) {
526
-            EEM_Base::set_model_query_blog_id();
527
-        }
528
-        /**
529
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
530
-         * just use EE_Register_Model_Extension
531
-         *
532
-         * @var EE_Table_Base[] $_tables
533
-         */
534
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
535
-        foreach ($this->_tables as $table_alias => $table_obj) {
536
-            /** @var $table_obj EE_Table_Base */
537
-            $table_obj->_construct_finalize_with_alias($table_alias);
538
-            if ($table_obj instanceof EE_Secondary_Table) {
539
-                /** @var $table_obj EE_Secondary_Table */
540
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
541
-            }
542
-        }
543
-        /**
544
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
545
-         * EE_Register_Model_Extension
546
-         *
547
-         * @param EE_Model_Field_Base[] $_fields
548
-         */
549
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
550
-        $this->_invalidate_field_caches();
551
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
552
-            if ( ! array_key_exists($table_alias, $this->_tables)) {
553
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
554
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
555
-            }
556
-            foreach ($fields_for_table as $field_name => $field_obj) {
557
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
558
-                //primary key field base has a slightly different _construct_finalize
559
-                /** @var $field_obj EE_Model_Field_Base */
560
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
561
-            }
562
-        }
563
-        // everything is related to Extra_Meta
564
-        if (get_class($this) !== 'EEM_Extra_Meta') {
565
-            //make extra meta related to everything, but don't block deleting things just
566
-            //because they have related extra meta info. For now just orphan those extra meta
567
-            //in the future we should automatically delete them
568
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
569
-        }
570
-        //and change logs
571
-        if (get_class($this) !== 'EEM_Change_Log') {
572
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
573
-        }
574
-        /**
575
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
576
-         * EE_Register_Model_Extension
577
-         *
578
-         * @param EE_Model_Relation_Base[] $_model_relations
579
-         */
580
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
581
-            $this->_model_relations);
582
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
583
-            /** @var $relation_obj EE_Model_Relation_Base */
584
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
585
-        }
586
-        foreach ($this->_indexes as $index_name => $index_obj) {
587
-            /** @var $index_obj EE_Index */
588
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
589
-        }
590
-        $this->set_timezone($timezone);
591
-        //finalize default where condition strategy, or set default
592
-        if ( ! $this->_default_where_conditions_strategy) {
593
-            //nothing was set during child constructor, so set default
594
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
595
-        }
596
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
597
-        if ( ! $this->_minimum_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
602
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
603
-        //to indicate to NOT set it, set it to the logical default
604
-        if ($this->_caps_slug === null) {
605
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
606
-        }
607
-        //initialize the standard cap restriction generators if none were specified by the child constructor
608
-        if ($this->_cap_restriction_generators !== false) {
609
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
610
-                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
611
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
612
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
613
-                        new EE_Restriction_Generator_Protected(),
614
-                        $cap_context,
615
-                        $this
616
-                    );
617
-                }
618
-            }
619
-        }
620
-        //if there are cap restriction generators, use them to make the default cap restrictions
621
-        if ($this->_cap_restriction_generators !== false) {
622
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
623
-                if ( ! $generator_object) {
624
-                    continue;
625
-                }
626
-                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
627
-                    throw new EE_Error(
628
-                        sprintf(
629
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
630
-                                'event_espresso'),
631
-                            $context,
632
-                            $this->get_this_model_name()
633
-                        )
634
-                    );
635
-                }
636
-                $action = $this->cap_action_for_context($context);
637
-                if ( ! $generator_object->construction_finalized()) {
638
-                    $generator_object->_construct_finalize($this, $action);
639
-                }
640
-            }
641
-        }
642
-        do_action('AHEE__' . get_class($this) . '__construct__end');
643
-    }
644
-
645
-
646
-
647
-    /**
648
-     * Generates the cap restrictions for the given context, or if they were
649
-     * already generated just gets what's cached
650
-     *
651
-     * @param string $context one of EEM_Base::valid_cap_contexts()
652
-     * @return EE_Default_Where_Conditions[]
653
-     */
654
-    protected function _generate_cap_restrictions($context)
655
-    {
656
-        if (isset($this->_cap_restriction_generators[$context])
657
-            && $this->_cap_restriction_generators[$context]
658
-               instanceof
659
-               EE_Restriction_Generator_Base
660
-        ) {
661
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
662
-        } else {
663
-            return array();
664
-        }
665
-    }
666
-
667
-
668
-
669
-    /**
670
-     * Used to set the $_model_query_blog_id static property.
671
-     *
672
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
673
-     *                      value for get_current_blog_id() will be used.
674
-     */
675
-    public static function set_model_query_blog_id($blog_id = 0)
676
-    {
677
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
678
-    }
679
-
680
-
681
-
682
-    /**
683
-     * Returns whatever is set as the internal $model_query_blog_id.
684
-     *
685
-     * @return int
686
-     */
687
-    public static function get_model_query_blog_id()
688
-    {
689
-        return EEM_Base::$_model_query_blog_id;
690
-    }
691
-
692
-
693
-
694
-    /**
695
-     *        This function is a singleton method used to instantiate the Espresso_model object
696
-     *
697
-     * @access public
698
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
699
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
700
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
701
-     *                         timezone in the 'timezone_string' wp option)
702
-     * @return static (as in the concrete child class)
703
-     */
704
-    public static function instance($timezone = null)
705
-    {
706
-        // check if instance of Espresso_model already exists
707
-        if ( ! static::$_instance instanceof static) {
708
-            // instantiate Espresso_model
709
-            static::$_instance = new static($timezone);
710
-        }
711
-        //we might have a timezone set, let set_timezone decide what to do with it
712
-        static::$_instance->set_timezone($timezone);
713
-        // Espresso_model object
714
-        return static::$_instance;
715
-    }
716
-
717
-
718
-
719
-    /**
720
-     * resets the model and returns it
721
-     *
722
-     * @param null | string $timezone
723
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
724
-     * all its properties reset; if it wasn't instantiated, returns null)
725
-     */
726
-    public static function reset($timezone = null)
727
-    {
728
-        if (static::$_instance instanceof EEM_Base) {
729
-            //let's try to NOT swap out the current instance for a new one
730
-            //because if someone has a reference to it, we can't remove their reference
731
-            //so it's best to keep using the same reference, but change the original object
732
-            //reset all its properties to their original values as defined in the class
733
-            $r = new ReflectionClass(get_class(static::$_instance));
734
-            $static_properties = $r->getStaticProperties();
735
-            foreach ($r->getDefaultProperties() as $property => $value) {
736
-                //don't set instance to null like it was originally,
737
-                //but it's static anyways, and we're ignoring static properties (for now at least)
738
-                if ( ! isset($static_properties[$property])) {
739
-                    static::$_instance->{$property} = $value;
740
-                }
741
-            }
742
-            //and then directly call its constructor again, like we would if we
743
-            //were creating a new one
744
-            static::$_instance->__construct($timezone);
745
-            return self::instance();
746
-        }
747
-        return null;
748
-    }
749
-
750
-
751
-
752
-    /**
753
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
754
-     *
755
-     * @param  boolean $translated return localized strings or JUST the array.
756
-     * @return array
757
-     * @throws \EE_Error
758
-     */
759
-    public function status_array($translated = false)
760
-    {
761
-        if ( ! array_key_exists('Status', $this->_model_relations)) {
762
-            return array();
763
-        }
764
-        $model_name = $this->get_this_model_name();
765
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
766
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
767
-        $status_array = array();
768
-        foreach ($stati as $status) {
769
-            $status_array[$status->ID()] = $status->get('STS_code');
770
-        }
771
-        return $translated
772
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
773
-            : $status_array;
774
-    }
775
-
776
-
777
-
778
-    /**
779
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
780
-     *
781
-     * @param array $query_params             {
782
-     * @var array $0 (where) array {
783
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
784
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
785
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
786
-     *                                        conditions based on related models (and even
787
-     *                                        models-related-to-related-models) prepend the model's name onto the field
788
-     *                                        name. Eg,
789
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
790
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
791
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
792
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
793
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE Venue_CPT.ID = 12 Notice that automatically
794
-     *                                        took care of joining Events to Venues (even when each of those models actually consisted of two tables). Also, you may chain the model relations together. Eg instead of just having
795
-     *                                        "Venue.VNU_ID", you could have
796
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
797
-     *                                        events are related to Registrations, which are related to Attendees). You
798
-     *                                        can take it even further with
799
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
800
-     *                                        (from the default of '='), change the value to an numerically-indexed
801
-     *                                        array, where the first item in the list is the operator. eg: array(
802
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
803
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
804
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
805
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
806
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL Values can be a string, int, or float. They can
807
-     *                                        also be arrays IFF the operator is IN. Also, values can actually be field names. To indicate the value is a field, simply provide a third array item (true) to the operator-value array like so:
808
-     *                                        eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold" Note: you can also use related model field names like you would any other field
809
-     *                                        name. eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default
810
-     *                                        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__>' =>
811
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...". Also, to negate an entire set of conditions, use 'NOT' as an array key. eg: array('NOT'=>array('TXN_total' =>
812
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND TXN_paid =23) Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default,
813
-     *                                        but if you had previously specified to use ORs to join, ORs will continue to be used. So, if you specify to use an "OR" to join conditions, it will continue to "stick" until you specify an AND.
814
-     *                                        eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
815
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg: array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes
816
-     *                                        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
817
-     *                                        place two or more where conditions applying to the same field. eg:
818
-     *                                        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
819
-     *                                        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 '*'
820
-     *                                        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
821
-     *                                        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 >>
822
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123" This can be applied to condition operators too, eg:
823
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
824
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
825
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL "...LIMIT 23", "...LIMIT 25,50",
826
-     *                                        and "...LIMIT 23,42" respectively. Remember when you provide two numbers for the limit, the 1st number is
827
-     *                                        the OFFSET, the 2nd is the LIMIT
828
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
829
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the following format array('on_join_limit'
830
-     *                                        => array( 'table_alias', array(1,2) ) ).
831
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
832
-     *                                        values are either 'ASC' or 'DESC'. 'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
833
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively. Like the
834
-     *                                        'where' conditions, these fields can be on related models. Eg
835
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related
836
-     *                                        to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
837
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
838
-     *                                        'order' specifies whether to order the field specified in 'order_by' in ascending or descending order.
839
-     *                                        Acceptable values are 'ASC' or 'DESC'. If, 'order_by' isn't used, but 'order' is, then it is assumed you
840
-     *                                        want to order by the primary key. Eg,
841
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC'); //(will join
842
-     *                                        with the Datetime model's table(s) and order by its field DTT_EVT_start) or
843
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM
844
-     *                                        wp_esp_registration ORDER BY REG_ID ASC"
845
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
846
-     *                                        'group_by'=>'VNU_ID', or 'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note: if no
847
-     *                                        $group_by is specified, and a limit is set, automatically groups by the model's primary key (or combined
848
-     *                                        primary keys). This avoids some weirdness that results when using limits, tons of joins, and no group by,
849
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
850
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
851
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped results)
852
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
853
-     *                                        array where values are models to be joined in the query.Eg array('Attendee','Payment','Datetime'). You may
854
-     *                                        join with transient models using period, eg "Registration.Transaction.Payment". You will probably only want
855
-     *                                        to do this in hopes of increasing efficiency, as related models which belongs to the current model
856
-     *                                        (ie, the current model has a foreign key to them, like how Registration
857
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
858
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
859
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually soft-deleted objects are
860
-     *                                        filtered-out if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS
861
-     *                                        model's default where conditions set it to 'other_models_only'. If you only want this model's default where
862
-     *                                        conditions added to the query, use 'this_model_only'. If you want to use all default where conditions
863
-     *                                        (default), set to 'all'.
864
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
865
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return everything? Or should we only show
866
-     *                                        the current user items they should be able to view on the frontend, backend, edit, or delete? can be set to
867
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
868
-     *                                        }
869
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
870
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public again. Array keys
871
-     *                                        are object IDs (if there is a primary key on the model. if not, numerically indexed)
872
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
873
-     *                                        EEM_Transaction::instance()->get_all( array( array(
874
-     *                                        'OR'=>array(
875
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
876
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
877
-     *                                        )
878
-     *                                        ),
879
-     *                                        'limit'=>10,
880
-     *                                        'group_by'=>'TXN_ID'
881
-     *                                        ));
882
-     *                                        get all the answers to the question titled "shirt size" for event with id
883
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
884
-     *                                        'Question.QST_display_text'=>'shirt size',
885
-     *                                        'Registration.Event.EVT_ID'=>12
886
-     *                                        ),
887
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
888
-     *                                        ));
889
-     * @throws \EE_Error
890
-     */
891
-    public function get_all($query_params = array())
892
-    {
893
-        if (isset($query_params['limit'])
894
-            && ! isset($query_params['group_by'])
895
-        ) {
896
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
897
-        }
898
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
899
-    }
900
-
901
-
902
-
903
-    /**
904
-     * Modifies the query parameters so we only get back model objects
905
-     * that "belong" to the current user
906
-     *
907
-     * @param array $query_params @see EEM_Base::get_all()
908
-     * @return array like EEM_Base::get_all
909
-     */
910
-    public function alter_query_params_to_only_include_mine($query_params = array())
911
-    {
912
-        $wp_user_field_name = $this->wp_user_field_name();
913
-        if ($wp_user_field_name) {
914
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
915
-        }
916
-        return $query_params;
917
-    }
918
-
919
-
920
-
921
-    /**
922
-     * Returns the name of the field's name that points to the WP_User table
923
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
924
-     * foreign key to the WP_User table)
925
-     *
926
-     * @return string|boolean string on success, boolean false when there is no
927
-     * foreign key to the WP_User table
928
-     */
929
-    public function wp_user_field_name()
930
-    {
931
-        try {
932
-            if ( ! empty($this->_model_chain_to_wp_user)) {
933
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
934
-                $last_model_name = end($models_to_follow_to_wp_users);
935
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
936
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
937
-            } else {
938
-                $model_with_fk_to_wp_users = $this;
939
-                $model_chain_to_wp_user = '';
940
-            }
941
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
942
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
943
-        } catch (EE_Error $e) {
944
-            return false;
945
-        }
946
-    }
947
-
948
-
949
-
950
-    /**
951
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
952
-     * (or transiently-related model) has a foreign key to the wp_users table;
953
-     * useful for finding if model objects of this type are 'owned' by the current user.
954
-     * This is an empty string when the foreign key is on this model and when it isn't,
955
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
956
-     * (or transiently-related model)
957
-     *
958
-     * @return string
959
-     */
960
-    public function model_chain_to_wp_user()
961
-    {
962
-        return $this->_model_chain_to_wp_user;
963
-    }
964
-
965
-
966
-
967
-    /**
968
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
969
-     * like how registrations don't have a foreign key to wp_users, but the
970
-     * events they are for are), or is unrelated to wp users.
971
-     * generally available
972
-     *
973
-     * @return boolean
974
-     */
975
-    public function is_owned()
976
-    {
977
-        if ($this->model_chain_to_wp_user()) {
978
-            return true;
979
-        } else {
980
-            try {
981
-                $this->get_foreign_key_to('WP_User');
982
-                return true;
983
-            } catch (EE_Error $e) {
984
-                return false;
985
-            }
986
-        }
987
-    }
988
-
989
-
990
-
991
-    /**
992
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
993
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
994
-     * the model)
995
-     *
996
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
997
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
998
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
999
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1000
-     *                                  override this and set the select to "*", or a specific column name, like
1001
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1002
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1003
-     *                                  the aliases used to refer to this selection, and values are to be
1004
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1005
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1006
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1007
-     * @throws \EE_Error
1008
-     */
1009
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1010
-    {
1011
-        // remember the custom selections, if any, and type cast as array
1012
-        // (unless $columns_to_select is an object, then just set as an empty array)
1013
-        // Note: (array) 'some string' === array( 'some string' )
1014
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1015
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1016
-        $select_expressions = $columns_to_select !== null
1017
-            ? $this->_construct_select_from_input($columns_to_select)
1018
-            : $this->_construct_default_select_sql($model_query_info);
1019
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1020
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1021
-    }
1022
-
1023
-
1024
-
1025
-    /**
1026
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1027
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1028
-     * take care of joins, field preparation etc.
1029
-     *
1030
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1031
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1032
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1033
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1034
-     *                                  override this and set the select to "*", or a specific column name, like
1035
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1036
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1037
-     *                                  the aliases used to refer to this selection, and values are to be
1038
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1039
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1040
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1041
-     * @throws \EE_Error
1042
-     */
1043
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1044
-    {
1045
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1046
-    }
1047
-
1048
-
1049
-
1050
-    /**
1051
-     * For creating a custom select statement
1052
-     *
1053
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1054
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1055
-     *                                 SQL, and 1=>is the datatype
1056
-     * @throws EE_Error
1057
-     * @return string
1058
-     */
1059
-    private function _construct_select_from_input($columns_to_select)
1060
-    {
1061
-        if (is_array($columns_to_select)) {
1062
-            $select_sql_array = array();
1063
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1064
-                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1065
-                    throw new EE_Error(
1066
-                        sprintf(
1067
-                            __(
1068
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1069
-                                "event_espresso"
1070
-                            ),
1071
-                            $selection_and_datatype,
1072
-                            $alias
1073
-                        )
1074
-                    );
1075
-                }
1076
-                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1077
-                    throw new EE_Error(
1078
-                        sprintf(
1079
-                            __(
1080
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1081
-                                "event_espresso"
1082
-                            ),
1083
-                            $selection_and_datatype[1],
1084
-                            $selection_and_datatype[0],
1085
-                            $alias,
1086
-                            implode(",", $this->_valid_wpdb_data_types)
1087
-                        )
1088
-                    );
1089
-                }
1090
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1091
-            }
1092
-            $columns_to_select_string = implode(", ", $select_sql_array);
1093
-        } else {
1094
-            $columns_to_select_string = $columns_to_select;
1095
-        }
1096
-        return $columns_to_select_string;
1097
-    }
1098
-
1099
-
1100
-
1101
-    /**
1102
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1103
-     *
1104
-     * @return string
1105
-     * @throws \EE_Error
1106
-     */
1107
-    public function primary_key_name()
1108
-    {
1109
-        return $this->get_primary_key_field()->get_name();
1110
-    }
1111
-
1112
-
1113
-
1114
-    /**
1115
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1116
-     * If there is no primary key on this model, $id is treated as primary key string
1117
-     *
1118
-     * @param mixed $id int or string, depending on the type of the model's primary key
1119
-     * @return EE_Base_Class
1120
-     */
1121
-    public function get_one_by_ID($id)
1122
-    {
1123
-        if ($this->get_from_entity_map($id)) {
1124
-            return $this->get_from_entity_map($id);
1125
-        }
1126
-        return $this->get_one(
1127
-            $this->alter_query_params_to_restrict_by_ID(
1128
-                $id,
1129
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1130
-            )
1131
-        );
1132
-    }
1133
-
1134
-
1135
-
1136
-    /**
1137
-     * Alters query parameters to only get items with this ID are returned.
1138
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1139
-     * or could just be a simple primary key ID
1140
-     *
1141
-     * @param int   $id
1142
-     * @param array $query_params
1143
-     * @return array of normal query params, @see EEM_Base::get_all
1144
-     * @throws \EE_Error
1145
-     */
1146
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1147
-    {
1148
-        if ( ! isset($query_params[0])) {
1149
-            $query_params[0] = array();
1150
-        }
1151
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1152
-        if ($conditions_from_id === null) {
1153
-            $query_params[0][$this->primary_key_name()] = $id;
1154
-        } else {
1155
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1156
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1157
-        }
1158
-        return $query_params;
1159
-    }
1160
-
1161
-
1162
-
1163
-    /**
1164
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1165
-     * array. If no item is found, null is returned.
1166
-     *
1167
-     * @param array $query_params like EEM_Base's $query_params variable.
1168
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1169
-     * @throws \EE_Error
1170
-     */
1171
-    public function get_one($query_params = array())
1172
-    {
1173
-        if ( ! is_array($query_params)) {
1174
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1175
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1176
-                    gettype($query_params)), '4.6.0');
1177
-            $query_params = array();
1178
-        }
1179
-        $query_params['limit'] = 1;
1180
-        $items = $this->get_all($query_params);
1181
-        if (empty($items)) {
1182
-            return null;
1183
-        } else {
1184
-            return array_shift($items);
1185
-        }
1186
-    }
1187
-
1188
-
1189
-
1190
-    /**
1191
-     * Returns the next x number of items in sequence from the given value as
1192
-     * found in the database matching the given query conditions.
1193
-     *
1194
-     * @param mixed $current_field_value    Value used for the reference point.
1195
-     * @param null  $field_to_order_by      What field is used for the
1196
-     *                                      reference point.
1197
-     * @param int   $limit                  How many to return.
1198
-     * @param array $query_params           Extra conditions on the query.
1199
-     * @param null  $columns_to_select      If left null, then an array of
1200
-     *                                      EE_Base_Class objects is returned,
1201
-     *                                      otherwise you can indicate just the
1202
-     *                                      columns you want returned.
1203
-     * @return EE_Base_Class[]|array
1204
-     * @throws \EE_Error
1205
-     */
1206
-    public function next_x(
1207
-        $current_field_value,
1208
-        $field_to_order_by = null,
1209
-        $limit = 1,
1210
-        $query_params = array(),
1211
-        $columns_to_select = null
1212
-    ) {
1213
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1214
-            $columns_to_select);
1215
-    }
1216
-
1217
-
1218
-
1219
-    /**
1220
-     * Returns the previous x number of items in sequence from the given value
1221
-     * as found in the database matching the given query conditions.
1222
-     *
1223
-     * @param mixed $current_field_value    Value used for the reference point.
1224
-     * @param null  $field_to_order_by      What field is used for the
1225
-     *                                      reference point.
1226
-     * @param int   $limit                  How many to return.
1227
-     * @param array $query_params           Extra conditions on the query.
1228
-     * @param null  $columns_to_select      If left null, then an array of
1229
-     *                                      EE_Base_Class objects is returned,
1230
-     *                                      otherwise you can indicate just the
1231
-     *                                      columns you want returned.
1232
-     * @return EE_Base_Class[]|array
1233
-     * @throws \EE_Error
1234
-     */
1235
-    public function previous_x(
1236
-        $current_field_value,
1237
-        $field_to_order_by = null,
1238
-        $limit = 1,
1239
-        $query_params = array(),
1240
-        $columns_to_select = null
1241
-    ) {
1242
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1243
-            $columns_to_select);
1244
-    }
1245
-
1246
-
1247
-
1248
-    /**
1249
-     * Returns the next item in sequence from the given value as found in the
1250
-     * database matching the given query conditions.
1251
-     *
1252
-     * @param mixed $current_field_value    Value used for the reference point.
1253
-     * @param null  $field_to_order_by      What field is used for the
1254
-     *                                      reference point.
1255
-     * @param array $query_params           Extra conditions on the query.
1256
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1257
-     *                                      object is returned, otherwise you
1258
-     *                                      can indicate just the columns you
1259
-     *                                      want and a single array indexed by
1260
-     *                                      the columns will be returned.
1261
-     * @return EE_Base_Class|null|array()
1262
-     * @throws \EE_Error
1263
-     */
1264
-    public function next(
1265
-        $current_field_value,
1266
-        $field_to_order_by = null,
1267
-        $query_params = array(),
1268
-        $columns_to_select = null
1269
-    ) {
1270
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1271
-            $columns_to_select);
1272
-        return empty($results) ? null : reset($results);
1273
-    }
1274
-
1275
-
1276
-
1277
-    /**
1278
-     * Returns the previous item in sequence from the given value as found in
1279
-     * the database matching the given query conditions.
1280
-     *
1281
-     * @param mixed $current_field_value    Value used for the reference point.
1282
-     * @param null  $field_to_order_by      What field is used for the
1283
-     *                                      reference point.
1284
-     * @param array $query_params           Extra conditions on the query.
1285
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1286
-     *                                      object is returned, otherwise you
1287
-     *                                      can indicate just the columns you
1288
-     *                                      want and a single array indexed by
1289
-     *                                      the columns will be returned.
1290
-     * @return EE_Base_Class|null|array()
1291
-     * @throws EE_Error
1292
-     */
1293
-    public function previous(
1294
-        $current_field_value,
1295
-        $field_to_order_by = null,
1296
-        $query_params = array(),
1297
-        $columns_to_select = null
1298
-    ) {
1299
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1300
-            $columns_to_select);
1301
-        return empty($results) ? null : reset($results);
1302
-    }
1303
-
1304
-
1305
-
1306
-    /**
1307
-     * Returns the a consecutive number of items in sequence from the given
1308
-     * value as found in the database matching the given query conditions.
1309
-     *
1310
-     * @param mixed  $current_field_value   Value used for the reference point.
1311
-     * @param string $operand               What operand is used for the sequence.
1312
-     * @param string $field_to_order_by     What field is used for the reference point.
1313
-     * @param int    $limit                 How many to return.
1314
-     * @param array  $query_params          Extra conditions on the query.
1315
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1316
-     *                                      otherwise you can indicate just the columns you want returned.
1317
-     * @return EE_Base_Class[]|array
1318
-     * @throws EE_Error
1319
-     */
1320
-    protected function _get_consecutive(
1321
-        $current_field_value,
1322
-        $operand = '>',
1323
-        $field_to_order_by = null,
1324
-        $limit = 1,
1325
-        $query_params = array(),
1326
-        $columns_to_select = null
1327
-    ) {
1328
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1329
-        if (empty($field_to_order_by)) {
1330
-            if ($this->has_primary_key_field()) {
1331
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1332
-            } else {
1333
-                if (WP_DEBUG) {
1334
-                    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).',
1335
-                        'event_espresso'));
1336
-                }
1337
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1338
-                return array();
1339
-            }
1340
-        }
1341
-        if ( ! is_array($query_params)) {
1342
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1343
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1344
-                    gettype($query_params)), '4.6.0');
1345
-            $query_params = array();
1346
-        }
1347
-        //let's add the where query param for consecutive look up.
1348
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1349
-        $query_params['limit'] = $limit;
1350
-        //set direction
1351
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1352
-        $query_params['order_by'] = $operand === '>'
1353
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1354
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1355
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1356
-        if (empty($columns_to_select)) {
1357
-            return $this->get_all($query_params);
1358
-        } else {
1359
-            //getting just the fields
1360
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1361
-        }
1362
-    }
1363
-
1364
-
1365
-
1366
-    /**
1367
-     * This sets the _timezone property after model object has been instantiated.
1368
-     *
1369
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1370
-     */
1371
-    public function set_timezone($timezone)
1372
-    {
1373
-        if ($timezone !== null) {
1374
-            $this->_timezone = $timezone;
1375
-        }
1376
-        //note we need to loop through relations and set the timezone on those objects as well.
1377
-        foreach ($this->_model_relations as $relation) {
1378
-            $relation->set_timezone($timezone);
1379
-        }
1380
-        //and finally we do the same for any datetime fields
1381
-        foreach ($this->_fields as $field) {
1382
-            if ($field instanceof EE_Datetime_Field) {
1383
-                $field->set_timezone($timezone);
1384
-            }
1385
-        }
1386
-    }
1387
-
1388
-
1389
-
1390
-    /**
1391
-     * This just returns whatever is set for the current timezone.
1392
-     *
1393
-     * @access public
1394
-     * @return string
1395
-     */
1396
-    public function get_timezone()
1397
-    {
1398
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1399
-        if (empty($this->_timezone)) {
1400
-            foreach ($this->_fields as $field) {
1401
-                if ($field instanceof EE_Datetime_Field) {
1402
-                    $this->set_timezone($field->get_timezone());
1403
-                    break;
1404
-                }
1405
-            }
1406
-        }
1407
-        //if timezone STILL empty then return the default timezone for the site.
1408
-        if (empty($this->_timezone)) {
1409
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1410
-        }
1411
-        return $this->_timezone;
1412
-    }
1413
-
1414
-
1415
-
1416
-    /**
1417
-     * This returns the date formats set for the given field name and also ensures that
1418
-     * $this->_timezone property is set correctly.
1419
-     *
1420
-     * @since 4.6.x
1421
-     * @param string $field_name The name of the field the formats are being retrieved for.
1422
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1423
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1424
-     * @return array formats in an array with the date format first, and the time format last.
1425
-     */
1426
-    public function get_formats_for($field_name, $pretty = false)
1427
-    {
1428
-        $field_settings = $this->field_settings_for($field_name);
1429
-        //if not a valid EE_Datetime_Field then throw error
1430
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1431
-            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.',
1432
-                'event_espresso'), $field_name));
1433
-        }
1434
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1435
-        //the field.
1436
-        $this->_timezone = $field_settings->get_timezone();
1437
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1438
-    }
1439
-
1440
-
1441
-
1442
-    /**
1443
-     * This returns the current time in a format setup for a query on this model.
1444
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1445
-     * it will return:
1446
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1447
-     *  NOW
1448
-     *  - or a unix timestamp (equivalent to time())
1449
-     *
1450
-     * @since 4.6.x
1451
-     * @param string $field_name       The field the current time is needed for.
1452
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1453
-     *                                 formatted string matching the set format for the field in the set timezone will
1454
-     *                                 be returned.
1455
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1456
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1457
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1458
-     *                                 exception is triggered.
1459
-     */
1460
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1461
-    {
1462
-        $formats = $this->get_formats_for($field_name);
1463
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1464
-        if ($timestamp) {
1465
-            return $DateTime->format('U');
1466
-        }
1467
-        //not returning timestamp, so return formatted string in timezone.
1468
-        switch ($what) {
1469
-            case 'time' :
1470
-                return $DateTime->format($formats[1]);
1471
-                break;
1472
-            case 'date' :
1473
-                return $DateTime->format($formats[0]);
1474
-                break;
1475
-            default :
1476
-                return $DateTime->format(implode(' ', $formats));
1477
-                break;
1478
-        }
1479
-    }
1480
-
1481
-
1482
-
1483
-    /**
1484
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1485
-     * for the model are.  Returns a DateTime object.
1486
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1487
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1488
-     * ignored.
1489
-     *
1490
-     * @param string $field_name      The field being setup.
1491
-     * @param string $timestring      The date time string being used.
1492
-     * @param string $incoming_format The format for the time string.
1493
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1494
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1495
-     *                                format is
1496
-     *                                'U', this is ignored.
1497
-     * @return DateTime
1498
-     * @throws \EE_Error
1499
-     */
1500
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1501
-    {
1502
-        //just using this to ensure the timezone is set correctly internally
1503
-        $this->get_formats_for($field_name);
1504
-        //load EEH_DTT_Helper
1505
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1506
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1507
-        return $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1508
-    }
1509
-
1510
-
1511
-
1512
-    /**
1513
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1514
-     *
1515
-     * @return EE_Table_Base[]
1516
-     */
1517
-    public function get_tables()
1518
-    {
1519
-        return $this->_tables;
1520
-    }
1521
-
1522
-
1523
-
1524
-    /**
1525
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1526
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1527
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1528
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1529
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1530
-     * model object with EVT_ID = 1
1531
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1532
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1533
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1534
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1535
-     * are not specified)
1536
-     *
1537
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1538
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1539
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1540
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1541
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1542
-     *                                         ID=34, we'd use this method as follows:
1543
-     *                                         EEM_Transaction::instance()->update(
1544
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1545
-     *                                         array(array('TXN_ID'=>34)));
1546
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1547
-     *                                         in client code into what's expected to be stored on each field. Eg,
1548
-     *                                         consider updating Question's QST_admin_label field is of type
1549
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1550
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1551
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1552
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1553
-     *                                         TRUE, it is assumed that you've already called
1554
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1555
-     *                                         malicious javascript. However, if
1556
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1557
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it, and every other field, before insertion. We provide this parameter because model objects perform their prepare_for_set
1558
-     *                                         function on all their values, and so don't need to be called again (and in many cases, shouldn't be called again. Eg: if we escape HTML characters in the prepare_for_set method...)
1559
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1560
-     *                                         in this model's entity map according to $fields_n_values that match
1561
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1562
-     *                                         by setting this to FALSE, but be aware that model objects being used
1563
-     *                                         could get out-of-sync with the database
1564
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1565
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was bad)
1566
-     * @throws \EE_Error
1567
-     */
1568
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1569
-    {
1570
-        if ( ! is_array($query_params)) {
1571
-            EE_Error::doing_it_wrong('EEM_Base::update',
1572
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1573
-                    gettype($query_params)), '4.6.0');
1574
-            $query_params = array();
1575
-        }
1576
-        /**
1577
-         * Action called before a model update call has been made.
1578
-         *
1579
-         * @param EEM_Base $model
1580
-         * @param array    $fields_n_values the updated fields and their new values
1581
-         * @param array    $query_params    @see EEM_Base::get_all()
1582
-         */
1583
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1584
-        /**
1585
-         * Filters the fields about to be updated given the query parameters. You can provide the
1586
-         * $query_params to $this->get_all() to find exactly which records will be updated
1587
-         *
1588
-         * @param array    $fields_n_values fields and their new values
1589
-         * @param EEM_Base $model           the model being queried
1590
-         * @param array    $query_params    see EEM_Base::get_all()
1591
-         */
1592
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1593
-            $query_params);
1594
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1595
-        //to do that, for each table, verify that it's PK isn't null.
1596
-        $tables = $this->get_tables();
1597
-        //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
1598
-        //NOTE: we should make this code more efficient by NOT querying twice
1599
-        //before the real update, but that needs to first go through ALPHA testing
1600
-        //as it's dangerous. says Mike August 8 2014
1601
-        //we want to make sure the default_where strategy is ignored
1602
-        $this->_ignore_where_strategy = true;
1603
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1604
-        foreach ($wpdb_select_results as $wpdb_result) {
1605
-            // type cast stdClass as array
1606
-            $wpdb_result = (array)$wpdb_result;
1607
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1608
-            if ($this->has_primary_key_field()) {
1609
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1610
-            } else {
1611
-                //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)
1612
-                $main_table_pk_value = null;
1613
-            }
1614
-            //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
1615
-            //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
1616
-            if (count($tables) > 1) {
1617
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1618
-                //in that table, and so we'll want to insert one
1619
-                foreach ($tables as $table_obj) {
1620
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1621
-                    //if there is no private key for this table on the results, it means there's no entry
1622
-                    //in this table, right? so insert a row in the current table, using any fields available
1623
-                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1624
-                            && $wpdb_result[$this_table_pk_column])
1625
-                    ) {
1626
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1627
-                            $main_table_pk_value);
1628
-                        //if we died here, report the error
1629
-                        if ( ! $success) {
1630
-                            return false;
1631
-                        }
1632
-                    }
1633
-                }
1634
-            }
1635
-            //				//and now check that if we have cached any models by that ID on the model, that
1636
-            //				//they also get updated properly
1637
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1638
-            //				if( $model_object ){
1639
-            //					foreach( $fields_n_values as $field => $value ){
1640
-            //						$model_object->set($field, $value);
1641
-            //let's make sure default_where strategy is followed now
1642
-            $this->_ignore_where_strategy = false;
1643
-        }
1644
-        //if we want to keep model objects in sync, AND
1645
-        //if this wasn't called from a model object (to update itself)
1646
-        //then we want to make sure we keep all the existing
1647
-        //model objects in sync with the db
1648
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1649
-            if ($this->has_primary_key_field()) {
1650
-                $model_objs_affected_ids = $this->get_col($query_params);
1651
-            } else {
1652
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1653
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1654
-                $model_objs_affected_ids = array();
1655
-                foreach ($models_affected_key_columns as $row) {
1656
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1657
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1658
-                }
1659
-            }
1660
-            if ( ! $model_objs_affected_ids) {
1661
-                //wait wait wait- if nothing was affected let's stop here
1662
-                return 0;
1663
-            }
1664
-            foreach ($model_objs_affected_ids as $id) {
1665
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1666
-                if ($model_obj_in_entity_map) {
1667
-                    foreach ($fields_n_values as $field => $new_value) {
1668
-                        $model_obj_in_entity_map->set($field, $new_value);
1669
-                    }
1670
-                }
1671
-            }
1672
-            //if there is a primary key on this model, we can now do a slight optimization
1673
-            if ($this->has_primary_key_field()) {
1674
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1675
-                $query_params = array(
1676
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1677
-                    'limit'                    => count($model_objs_affected_ids),
1678
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1679
-                );
1680
-            }
1681
-        }
1682
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1683
-        $SQL = "UPDATE "
1684
-               . $model_query_info->get_full_join_sql()
1685
-               . " SET "
1686
-               . $this->_construct_update_sql($fields_n_values)
1687
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1688
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1689
-        /**
1690
-         * Action called after a model update call has been made.
1691
-         *
1692
-         * @param EEM_Base $model
1693
-         * @param array    $fields_n_values the updated fields and their new values
1694
-         * @param array    $query_params    @see EEM_Base::get_all()
1695
-         * @param int      $rows_affected
1696
-         */
1697
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1698
-        return $rows_affected;//how many supposedly got updated
1699
-    }
1700
-
1701
-
1702
-
1703
-    /**
1704
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1705
-     * are teh values of the field specified (or by default the primary key field)
1706
-     * that matched the query params. Note that you should pass the name of the
1707
-     * model FIELD, not the database table's column name.
1708
-     *
1709
-     * @param array  $query_params @see EEM_Base::get_all()
1710
-     * @param string $field_to_select
1711
-     * @return array just like $wpdb->get_col()
1712
-     * @throws \EE_Error
1713
-     */
1714
-    public function get_col($query_params = array(), $field_to_select = null)
1715
-    {
1716
-        if ($field_to_select) {
1717
-            $field = $this->field_settings_for($field_to_select);
1718
-        } elseif ($this->has_primary_key_field()) {
1719
-            $field = $this->get_primary_key_field();
1720
-        } else {
1721
-            //no primary key, just grab the first column
1722
-            $field = reset($this->field_settings());
1723
-        }
1724
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1725
-        $select_expressions = $field->get_qualified_column();
1726
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1727
-        return $this->_do_wpdb_query('get_col', array($SQL));
1728
-    }
1729
-
1730
-
1731
-
1732
-    /**
1733
-     * Returns a single column value for a single row from the database
1734
-     *
1735
-     * @param array  $query_params    @see EEM_Base::get_all()
1736
-     * @param string $field_to_select @see EEM_Base::get_col()
1737
-     * @return string
1738
-     * @throws \EE_Error
1739
-     */
1740
-    public function get_var($query_params = array(), $field_to_select = null)
1741
-    {
1742
-        $query_params['limit'] = 1;
1743
-        $col = $this->get_col($query_params, $field_to_select);
1744
-        if ( ! empty($col)) {
1745
-            return reset($col);
1746
-        } else {
1747
-            return null;
1748
-        }
1749
-    }
1750
-
1751
-
1752
-
1753
-    /**
1754
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1755
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1756
-     * injection, but currently no further filtering is done
1757
-     *
1758
-     * @global      $wpdb
1759
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1760
-     *                               be updated to in the DB
1761
-     * @return string of SQL
1762
-     * @throws \EE_Error
1763
-     */
1764
-    public function _construct_update_sql($fields_n_values)
1765
-    {
1766
-        /** @type WPDB $wpdb */
1767
-        global $wpdb;
1768
-        $cols_n_values = array();
1769
-        foreach ($fields_n_values as $field_name => $value) {
1770
-            $field_obj = $this->field_settings_for($field_name);
1771
-            //if the value is NULL, we want to assign the value to that.
1772
-            //wpdb->prepare doesn't really handle that properly
1773
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1774
-            $value_sql = $prepared_value === null ? 'NULL'
1775
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1776
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1777
-        }
1778
-        return implode(",", $cols_n_values);
1779
-    }
1780
-
1781
-
1782
-
1783
-    /**
1784
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1785
-     * Performs a HARD delete, meaning the database row should always be removed,
1786
-     * not just have a flag field on it switched
1787
-     * Wrapper for EEM_Base::delete_permanently()
1788
-     *
1789
-     * @param mixed $id
1790
-     * @return boolean whether the row got deleted or not
1791
-     * @throws \EE_Error
1792
-     */
1793
-    public function delete_permanently_by_ID($id)
1794
-    {
1795
-        return $this->delete_permanently(
1796
-            array(
1797
-                array($this->get_primary_key_field()->get_name() => $id),
1798
-                'limit' => 1,
1799
-            )
1800
-        );
1801
-    }
1802
-
1803
-
1804
-
1805
-    /**
1806
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1807
-     * Wrapper for EEM_Base::delete()
1808
-     *
1809
-     * @param mixed $id
1810
-     * @return boolean whether the row got deleted or not
1811
-     * @throws \EE_Error
1812
-     */
1813
-    public function delete_by_ID($id)
1814
-    {
1815
-        return $this->delete(
1816
-            array(
1817
-                array($this->get_primary_key_field()->get_name() => $id),
1818
-                'limit' => 1,
1819
-            )
1820
-        );
1821
-    }
1822
-
1823
-
1824
-
1825
-    /**
1826
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1827
-     * meaning if the model has a field that indicates its been "trashed" or
1828
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1829
-     *
1830
-     * @see EEM_Base::delete_permanently
1831
-     * @param array   $query_params
1832
-     * @param boolean $allow_blocking
1833
-     * @return int how many rows got deleted
1834
-     * @throws \EE_Error
1835
-     */
1836
-    public function delete($query_params, $allow_blocking = true)
1837
-    {
1838
-        return $this->delete_permanently($query_params, $allow_blocking);
1839
-    }
1840
-
1841
-
1842
-
1843
-    /**
1844
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1845
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1846
-     * as archived, not actually deleted
1847
-     *
1848
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1849
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1850
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1851
-     *                                deletes regardless of other objects which may depend on it. Its generally
1852
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1853
-     *                                DB
1854
-     * @return int how many rows got deleted
1855
-     * @throws \EE_Error
1856
-     */
1857
-    public function delete_permanently($query_params, $allow_blocking = true)
1858
-    {
1859
-        /**
1860
-         * Action called just before performing a real deletion query. You can use the
1861
-         * model and its $query_params to find exactly which items will be deleted
1862
-         *
1863
-         * @param EEM_Base $model
1864
-         * @param array    $query_params   @see EEM_Base::get_all()
1865
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1866
-         *                                 to block (prevent) this deletion
1867
-         */
1868
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1869
-        //some MySQL databases may be running safe mode, which may restrict
1870
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1871
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1872
-        //to delete them
1873
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1874
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1875
-        if ($deletion_where) {
1876
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1877
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1878
-            $table_aliases = array_keys($this->_tables);
1879
-            $SQL = "DELETE "
1880
-                   . implode(", ", $table_aliases)
1881
-                   . " FROM "
1882
-                   . $model_query_info->get_full_join_sql()
1883
-                   . " WHERE "
1884
-                   . $deletion_where;
1885
-            //		/echo "delete sql:$SQL";
1886
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1887
-        } else {
1888
-            $rows_deleted = 0;
1889
-        }
1890
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1891
-        if ($this->has_primary_key_field()) {
1892
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1893
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1894
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1895
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1896
-                }
1897
-            }
1898
-        }
1899
-        /**
1900
-         * Action called just after performing a real deletion query. Although at this point the
1901
-         * items should have been deleted
1902
-         *
1903
-         * @param EEM_Base $model
1904
-         * @param array    $query_params @see EEM_Base::get_all()
1905
-         * @param int      $rows_deleted
1906
-         */
1907
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1908
-        return $rows_deleted;//how many supposedly got deleted
1909
-    }
1910
-
1911
-
1912
-
1913
-    /**
1914
-     * Checks all the relations that throw error messages when there are blocking related objects
1915
-     * for related model objects. If there are any related model objects on those relations,
1916
-     * adds an EE_Error, and return true
1917
-     *
1918
-     * @param EE_Base_Class|int $this_model_obj_or_id
1919
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1920
-     *                                                 should be ignored when determining whether there are related
1921
-     *                                                 model objects which block this model object's deletion. Useful
1922
-     *                                                 if you know A is related to B and are considering deleting A,
1923
-     *                                                 but want to see if A has any other objects blocking its deletion
1924
-     *                                                 before removing the relation between A and B
1925
-     * @return boolean
1926
-     * @throws \EE_Error
1927
-     */
1928
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1929
-    {
1930
-        //first, if $ignore_this_model_obj was supplied, get its model
1931
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1932
-            $ignored_model = $ignore_this_model_obj->get_model();
1933
-        } else {
1934
-            $ignored_model = null;
1935
-        }
1936
-        //now check all the relations of $this_model_obj_or_id and see if there
1937
-        //are any related model objects blocking it?
1938
-        $is_blocked = false;
1939
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1940
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1941
-                //if $ignore_this_model_obj was supplied, then for the query
1942
-                //on that model needs to be told to ignore $ignore_this_model_obj
1943
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1944
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1945
-                        array(
1946
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1947
-                                '!=',
1948
-                                $ignore_this_model_obj->ID(),
1949
-                            ),
1950
-                        ),
1951
-                    ));
1952
-                } else {
1953
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1954
-                }
1955
-                if ($related_model_objects) {
1956
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1957
-                    $is_blocked = true;
1958
-                }
1959
-            }
1960
-        }
1961
-        return $is_blocked;
1962
-    }
1963
-
1964
-
1965
-
1966
-    /**
1967
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1968
-     * well.
1969
-     *
1970
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1971
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1972
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
1973
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
1974
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
1975
-     *                                      easily corrupt your DB
1976
-     * @throws EE_Error
1977
-     * @return string    everything that comes after the WHERE statement.
1978
-     */
1979
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
1980
-    {
1981
-        if ($this->has_primary_key_field()) {
1982
-            $primary_table = $this->_get_main_table();
1983
-            $other_tables = $this->_get_other_tables();
1984
-            $deletes = $query = array();
1985
-            foreach ($objects_for_deletion as $delete_object) {
1986
-                //before we mark this object for deletion,
1987
-                //make sure there's no related objects blocking its deletion (if we're checking)
1988
-                if (
1989
-                    $allow_blocking
1990
-                    && $this->delete_is_blocked_by_related_models(
1991
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
1992
-                    )
1993
-                ) {
1994
-                    continue;
1995
-                }
1996
-                //primary table deletes
1997
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
1998
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
1999
-                }
2000
-                //other tables
2001
-                if ( ! empty($other_tables)) {
2002
-                    foreach ($other_tables as $ot) {
2003
-                        //first check if we've got the foreign key column here.
2004
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2005
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2006
-                        }
2007
-                        // wait! it's entirely possible that we'll have a the primary key
2008
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2009
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2010
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2011
-                        }
2012
-                        // finally, it is possible that the fk for this table is found
2013
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2014
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2015
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2016
-                        }
2017
-                    }
2018
-                }
2019
-            }
2020
-            //we should have deletes now, so let's just go through and setup the where statement
2021
-            foreach ($deletes as $column => $values) {
2022
-                //make sure we have unique $values;
2023
-                $values = array_unique($values);
2024
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2025
-            }
2026
-            return ! empty($query) ? implode(' AND ', $query) : '';
2027
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2028
-            $ways_to_identify_a_row = array();
2029
-            $fields = $this->get_combined_primary_key_fields();
2030
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2031
-            foreach ($objects_for_deletion as $delete_object) {
2032
-                $values_for_each_cpk_for_a_row = array();
2033
-                foreach ($fields as $cpk_field) {
2034
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2035
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2036
-                                                           . "="
2037
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
2038
-                    }
2039
-                }
2040
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2041
-            }
2042
-            return implode(" OR ", $ways_to_identify_a_row);
2043
-        } else {
2044
-            //so there's no primary key and no combined key...
2045
-            //sorry, can't help you
2046
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2047
-                "event_espresso"), get_class($this)));
2048
-        }
2049
-    }
2050
-
2051
-
2052
-
2053
-    /**
2054
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2055
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2056
-     * column
2057
-     *
2058
-     * @param array  $query_params   like EEM_Base::get_all's
2059
-     * @param string $field_to_count field on model to count by (not column name)
2060
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2061
-     *                               that by the setting $distinct to TRUE;
2062
-     * @return int
2063
-     * @throws \EE_Error
2064
-     */
2065
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2066
-    {
2067
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2068
-        if ($field_to_count) {
2069
-            $field_obj = $this->field_settings_for($field_to_count);
2070
-            $column_to_count = $field_obj->get_qualified_column();
2071
-        } elseif ($this->has_primary_key_field()) {
2072
-            $pk_field_obj = $this->get_primary_key_field();
2073
-            $column_to_count = $pk_field_obj->get_qualified_column();
2074
-        } else {
2075
-            //there's no primary key
2076
-            //if we're counting distinct items, and there's no primary key,
2077
-            //we need to list out the columns for distinction;
2078
-            //otherwise we can just use star
2079
-            if ($distinct) {
2080
-                $columns_to_use = array();
2081
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2082
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2083
-                }
2084
-                $column_to_count = implode(',', $columns_to_use);
2085
-            } else {
2086
-                $column_to_count = '*';
2087
-            }
2088
-        }
2089
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2090
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2091
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2092
-    }
2093
-
2094
-
2095
-
2096
-    /**
2097
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2098
-     *
2099
-     * @param array  $query_params like EEM_Base::get_all
2100
-     * @param string $field_to_sum name of field (array key in $_fields array)
2101
-     * @return float
2102
-     * @throws \EE_Error
2103
-     */
2104
-    public function sum($query_params, $field_to_sum = null)
2105
-    {
2106
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2107
-        if ($field_to_sum) {
2108
-            $field_obj = $this->field_settings_for($field_to_sum);
2109
-        } else {
2110
-            $field_obj = $this->get_primary_key_field();
2111
-        }
2112
-        $column_to_count = $field_obj->get_qualified_column();
2113
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2114
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2115
-        $data_type = $field_obj->get_wpdb_data_type();
2116
-        if ($data_type === '%d' || $data_type === '%s') {
2117
-            return (float)$return_value;
2118
-        } else {//must be %f
2119
-            return (float)$return_value;
2120
-        }
2121
-    }
2122
-
2123
-
2124
-
2125
-    /**
2126
-     * Just calls the specified method on $wpdb with the given arguments
2127
-     * Consolidates a little extra error handling code
2128
-     *
2129
-     * @param string $wpdb_method
2130
-     * @param array  $arguments_to_provide
2131
-     * @throws EE_Error
2132
-     * @global wpdb  $wpdb
2133
-     * @return mixed
2134
-     */
2135
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2136
-    {
2137
-        //if we're in maintenance mode level 2, DON'T run any queries
2138
-        //because level 2 indicates the database needs updating and
2139
-        //is probably out of sync with the code
2140
-        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2141
-            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.",
2142
-                "event_espresso")));
2143
-        }
2144
-        /** @type WPDB $wpdb */
2145
-        global $wpdb;
2146
-        if ( ! method_exists($wpdb, $wpdb_method)) {
2147
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2148
-                'event_espresso'), $wpdb_method));
2149
-        }
2150
-        if (WP_DEBUG) {
2151
-            $old_show_errors_value = $wpdb->show_errors;
2152
-            $wpdb->show_errors(false);
2153
-        }
2154
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2155
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2156
-        if (WP_DEBUG) {
2157
-            $wpdb->show_errors($old_show_errors_value);
2158
-            if ( ! empty($wpdb->last_error)) {
2159
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2160
-            } elseif ($result === false) {
2161
-                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"',
2162
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2163
-            }
2164
-        } elseif ($result === false) {
2165
-            EE_Error::add_error(
2166
-                sprintf(
2167
-                    __('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"',
2168
-                        'event_espresso'),
2169
-                    $wpdb_method,
2170
-                    var_export($arguments_to_provide, true),
2171
-                    $wpdb->last_error
2172
-                ),
2173
-                __FILE__,
2174
-                __FUNCTION__,
2175
-                __LINE__
2176
-            );
2177
-        }
2178
-        return $result;
2179
-    }
2180
-
2181
-
2182
-
2183
-    /**
2184
-     * Attempts to run the indicated WPDB method with the provided arguments,
2185
-     * and if there's an error tries to verify the DB is correct. Uses
2186
-     * the static property EEM_Base::$_db_verification_level to determine whether
2187
-     * we should try to fix the EE core db, the addons, or just give up
2188
-     *
2189
-     * @param string $wpdb_method
2190
-     * @param array  $arguments_to_provide
2191
-     * @return mixed
2192
-     */
2193
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2194
-    {
2195
-        /** @type WPDB $wpdb */
2196
-        global $wpdb;
2197
-        $wpdb->last_error = null;
2198
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2199
-        // was there an error running the query? but we don't care on new activations
2200
-        // (we're going to setup the DB anyway on new activations)
2201
-        if (($result === false || ! empty($wpdb->last_error))
2202
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2203
-        ) {
2204
-            switch (EEM_Base::$_db_verification_level) {
2205
-                case EEM_Base::db_verified_none :
2206
-                    // let's double-check core's DB
2207
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2208
-                    break;
2209
-                case EEM_Base::db_verified_core :
2210
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2211
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2212
-                    break;
2213
-                case EEM_Base::db_verified_addons :
2214
-                    // ummmm... you in trouble
2215
-                    return $result;
2216
-                    break;
2217
-            }
2218
-            if ( ! empty($error_message)) {
2219
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2220
-                trigger_error($error_message);
2221
-            }
2222
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2223
-        }
2224
-        return $result;
2225
-    }
2226
-
2227
-
2228
-
2229
-    /**
2230
-     * Verifies the EE core database is up-to-date and records that we've done it on
2231
-     * EEM_Base::$_db_verification_level
2232
-     *
2233
-     * @param string $wpdb_method
2234
-     * @param array  $arguments_to_provide
2235
-     * @return string
2236
-     */
2237
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2238
-    {
2239
-        /** @type WPDB $wpdb */
2240
-        global $wpdb;
2241
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2242
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2243
-        $error_message = sprintf(
2244
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2245
-                'event_espresso'),
2246
-            $wpdb->last_error,
2247
-            $wpdb_method,
2248
-            wp_json_encode($arguments_to_provide)
2249
-        );
2250
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2251
-        return $error_message;
2252
-    }
2253
-
2254
-
2255
-
2256
-    /**
2257
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2258
-     * EEM_Base::$_db_verification_level
2259
-     *
2260
-     * @param $wpdb_method
2261
-     * @param $arguments_to_provide
2262
-     * @return string
2263
-     */
2264
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2265
-    {
2266
-        /** @type WPDB $wpdb */
2267
-        global $wpdb;
2268
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2269
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2270
-        $error_message = sprintf(
2271
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2272
-                'event_espresso'),
2273
-            $wpdb->last_error,
2274
-            $wpdb_method,
2275
-            wp_json_encode($arguments_to_provide)
2276
-        );
2277
-        EE_System::instance()->initialize_addons();
2278
-        return $error_message;
2279
-    }
2280
-
2281
-
2282
-
2283
-    /**
2284
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2285
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2286
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2287
-     * ..."
2288
-     *
2289
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2290
-     * @return string
2291
-     */
2292
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2293
-    {
2294
-        return " FROM " . $model_query_info->get_full_join_sql() .
2295
-               $model_query_info->get_where_sql() .
2296
-               $model_query_info->get_group_by_sql() .
2297
-               $model_query_info->get_having_sql() .
2298
-               $model_query_info->get_order_by_sql() .
2299
-               $model_query_info->get_limit_sql();
2300
-    }
2301
-
2302
-
2303
-
2304
-    /**
2305
-     * Set to easily debug the next X queries ran from this model.
2306
-     *
2307
-     * @param int $count
2308
-     */
2309
-    public function show_next_x_db_queries($count = 1)
2310
-    {
2311
-        $this->_show_next_x_db_queries = $count;
2312
-    }
2313
-
2314
-
2315
-
2316
-    /**
2317
-     * @param $sql_query
2318
-     */
2319
-    public function show_db_query_if_previously_requested($sql_query)
2320
-    {
2321
-        if ($this->_show_next_x_db_queries > 0) {
2322
-            echo $sql_query;
2323
-            $this->_show_next_x_db_queries--;
2324
-        }
2325
-    }
2326
-
2327
-
2328
-
2329
-    /**
2330
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2331
-     * There are the 3 cases:
2332
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2333
-     * $otherModelObject has no ID, it is first saved.
2334
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2335
-     * has no ID, it is first saved.
2336
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2337
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2338
-     * join table
2339
-     *
2340
-     * @param        EE_Base_Class                     /int $thisModelObject
2341
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2342
-     * @param string $relationName                     , key in EEM_Base::_relations
2343
-     *                                                 an attendee to a group, you also want to specify which role they
2344
-     *                                                 will have in that group. So you would use this parameter to
2345
-     *                                                 specify array('role-column-name'=>'role-id')
2346
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2347
-     *                                                 to for relation to methods that allow you to further specify
2348
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2349
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2350
-     *                                                 because these will be inserted in any new rows created as well.
2351
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2352
-     * @throws \EE_Error
2353
-     */
2354
-    public function add_relationship_to(
2355
-        $id_or_obj,
2356
-        $other_model_id_or_obj,
2357
-        $relationName,
2358
-        $extra_join_model_fields_n_values = array()
2359
-    ) {
2360
-        $relation_obj = $this->related_settings_for($relationName);
2361
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2362
-    }
2363
-
2364
-
2365
-
2366
-    /**
2367
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2368
-     * There are the 3 cases:
2369
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2370
-     * error
2371
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2372
-     * an error
2373
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2374
-     *
2375
-     * @param        EE_Base_Class /int $id_or_obj
2376
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2377
-     * @param string $relationName key in EEM_Base::_relations
2378
-     * @return boolean of success
2379
-     * @throws \EE_Error
2380
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2381
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2382
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2383
-     *                             because these will be inserted in any new rows created as well.
2384
-     */
2385
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2386
-    {
2387
-        $relation_obj = $this->related_settings_for($relationName);
2388
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2389
-    }
2390
-
2391
-
2392
-
2393
-    /**
2394
-     * @param mixed           $id_or_obj
2395
-     * @param string          $relationName
2396
-     * @param array           $where_query_params
2397
-     * @param EE_Base_Class[] objects to which relations were removed
2398
-     * @return \EE_Base_Class[]
2399
-     * @throws \EE_Error
2400
-     */
2401
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2402
-    {
2403
-        $relation_obj = $this->related_settings_for($relationName);
2404
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2405
-    }
2406
-
2407
-
2408
-
2409
-    /**
2410
-     * Gets all the related items of the specified $model_name, using $query_params.
2411
-     * Note: by default, we remove the "default query params"
2412
-     * because we want to get even deleted items etc.
2413
-     *
2414
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2415
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2416
-     * @param array  $query_params like EEM_Base::get_all
2417
-     * @return EE_Base_Class[]
2418
-     * @throws \EE_Error
2419
-     */
2420
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2421
-    {
2422
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2423
-        $relation_settings = $this->related_settings_for($model_name);
2424
-        return $relation_settings->get_all_related($model_obj, $query_params);
2425
-    }
2426
-
2427
-
2428
-
2429
-    /**
2430
-     * Deletes all the model objects across the relation indicated by $model_name
2431
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2432
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2433
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2434
-     *
2435
-     * @param EE_Base_Class|int|string $id_or_obj
2436
-     * @param string                   $model_name
2437
-     * @param array                    $query_params
2438
-     * @return int how many deleted
2439
-     * @throws \EE_Error
2440
-     */
2441
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2442
-    {
2443
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2444
-        $relation_settings = $this->related_settings_for($model_name);
2445
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2446
-    }
2447
-
2448
-
2449
-
2450
-    /**
2451
-     * Hard deletes all the model objects across the relation indicated by $model_name
2452
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2453
-     * the model objects can't be hard deleted because of blocking related model objects,
2454
-     * just does a soft-delete on them instead.
2455
-     *
2456
-     * @param EE_Base_Class|int|string $id_or_obj
2457
-     * @param string                   $model_name
2458
-     * @param array                    $query_params
2459
-     * @return int how many deleted
2460
-     * @throws \EE_Error
2461
-     */
2462
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2463
-    {
2464
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2465
-        $relation_settings = $this->related_settings_for($model_name);
2466
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2467
-    }
2468
-
2469
-
2470
-
2471
-    /**
2472
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2473
-     * unless otherwise specified in the $query_params
2474
-     *
2475
-     * @param        int             /EE_Base_Class $id_or_obj
2476
-     * @param string $model_name     like 'Event', or 'Registration'
2477
-     * @param array  $query_params   like EEM_Base::get_all's
2478
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2479
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2480
-     *                               that by the setting $distinct to TRUE;
2481
-     * @return int
2482
-     * @throws \EE_Error
2483
-     */
2484
-    public function count_related(
2485
-        $id_or_obj,
2486
-        $model_name,
2487
-        $query_params = array(),
2488
-        $field_to_count = null,
2489
-        $distinct = false
2490
-    ) {
2491
-        $related_model = $this->get_related_model_obj($model_name);
2492
-        //we're just going to use the query params on the related model's normal get_all query,
2493
-        //except add a condition to say to match the current mod
2494
-        if ( ! isset($query_params['default_where_conditions'])) {
2495
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2496
-        }
2497
-        $this_model_name = $this->get_this_model_name();
2498
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2499
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2500
-        return $related_model->count($query_params, $field_to_count, $distinct);
2501
-    }
2502
-
2503
-
2504
-
2505
-    /**
2506
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2507
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2508
-     *
2509
-     * @param        int           /EE_Base_Class $id_or_obj
2510
-     * @param string $model_name   like 'Event', or 'Registration'
2511
-     * @param array  $query_params like EEM_Base::get_all's
2512
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2513
-     * @return float
2514
-     * @throws \EE_Error
2515
-     */
2516
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2517
-    {
2518
-        $related_model = $this->get_related_model_obj($model_name);
2519
-        if ( ! is_array($query_params)) {
2520
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2521
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2522
-                    gettype($query_params)), '4.6.0');
2523
-            $query_params = array();
2524
-        }
2525
-        //we're just going to use the query params on the related model's normal get_all query,
2526
-        //except add a condition to say to match the current mod
2527
-        if ( ! isset($query_params['default_where_conditions'])) {
2528
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2529
-        }
2530
-        $this_model_name = $this->get_this_model_name();
2531
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2532
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2533
-        return $related_model->sum($query_params, $field_to_sum);
2534
-    }
2535
-
2536
-
2537
-
2538
-    /**
2539
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2540
-     * $modelObject
2541
-     *
2542
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2543
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2544
-     * @param array               $query_params     like EEM_Base::get_all's
2545
-     * @return EE_Base_Class
2546
-     * @throws \EE_Error
2547
-     */
2548
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2549
-    {
2550
-        $query_params['limit'] = 1;
2551
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2552
-        if ($results) {
2553
-            return array_shift($results);
2554
-        } else {
2555
-            return null;
2556
-        }
2557
-    }
2558
-
2559
-
2560
-
2561
-    /**
2562
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2563
-     *
2564
-     * @return string
2565
-     */
2566
-    public function get_this_model_name()
2567
-    {
2568
-        return str_replace("EEM_", "", get_class($this));
2569
-    }
2570
-
2571
-
2572
-
2573
-    /**
2574
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2575
-     *
2576
-     * @return EE_Any_Foreign_Model_Name_Field
2577
-     * @throws EE_Error
2578
-     */
2579
-    public function get_field_containing_related_model_name()
2580
-    {
2581
-        foreach ($this->field_settings(true) as $field) {
2582
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2583
-                $field_with_model_name = $field;
2584
-            }
2585
-        }
2586
-        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2587
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2588
-                $this->get_this_model_name()));
2589
-        }
2590
-        return $field_with_model_name;
2591
-    }
2592
-
2593
-
2594
-
2595
-    /**
2596
-     * Inserts a new entry into the database, for each table.
2597
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2598
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2599
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2600
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2601
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2602
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2603
-     *
2604
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2605
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2606
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2607
-     *                              of EEM_Base)
2608
-     * @return int new primary key on main table that got inserted
2609
-     * @throws EE_Error
2610
-     */
2611
-    public function insert($field_n_values)
2612
-    {
2613
-        /**
2614
-         * Filters the fields and their values before inserting an item using the models
2615
-         *
2616
-         * @param array    $fields_n_values keys are the fields and values are their new values
2617
-         * @param EEM_Base $model           the model used
2618
-         */
2619
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2620
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2621
-            $main_table = $this->_get_main_table();
2622
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2623
-            if ($new_id !== false) {
2624
-                foreach ($this->_get_other_tables() as $other_table) {
2625
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2626
-                }
2627
-            }
2628
-            /**
2629
-             * Done just after attempting to insert a new model object
2630
-             *
2631
-             * @param EEM_Base   $model           used
2632
-             * @param array      $fields_n_values fields and their values
2633
-             * @param int|string the              ID of the newly-inserted model object
2634
-             */
2635
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2636
-            return $new_id;
2637
-        } else {
2638
-            return false;
2639
-        }
2640
-    }
2641
-
2642
-
2643
-
2644
-    /**
2645
-     * Checks that the result would satisfy the unique indexes on this model
2646
-     *
2647
-     * @param array  $field_n_values
2648
-     * @param string $action
2649
-     * @return boolean
2650
-     * @throws \EE_Error
2651
-     */
2652
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2653
-    {
2654
-        foreach ($this->unique_indexes() as $index_name => $index) {
2655
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2656
-            if ($this->exists(array($uniqueness_where_params))) {
2657
-                EE_Error::add_error(
2658
-                    sprintf(
2659
-                        __(
2660
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2661
-                            "event_espresso"
2662
-                        ),
2663
-                        $action,
2664
-                        $this->_get_class_name(),
2665
-                        $index_name,
2666
-                        implode(",", $index->field_names()),
2667
-                        http_build_query($uniqueness_where_params)
2668
-                    ),
2669
-                    __FILE__,
2670
-                    __FUNCTION__,
2671
-                    __LINE__
2672
-                );
2673
-                return false;
2674
-            }
2675
-        }
2676
-        return true;
2677
-    }
2678
-
2679
-
2680
-
2681
-    /**
2682
-     * Checks the database for an item that conflicts (ie, if this item were
2683
-     * saved to the DB would break some uniqueness requirement, like a primary key
2684
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2685
-     * can be either an EE_Base_Class or an array of fields n values
2686
-     *
2687
-     * @param EE_Base_Class|array $obj_or_fields_array
2688
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2689
-     *                                                 when looking for conflicts
2690
-     *                                                 (ie, if false, we ignore the model object's primary key
2691
-     *                                                 when finding "conflicts". If true, it's also considered).
2692
-     *                                                 Only works for INT primary key,
2693
-     *                                                 STRING primary keys cannot be ignored
2694
-     * @throws EE_Error
2695
-     * @return EE_Base_Class|array
2696
-     */
2697
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2698
-    {
2699
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2700
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2701
-        } elseif (is_array($obj_or_fields_array)) {
2702
-            $fields_n_values = $obj_or_fields_array;
2703
-        } else {
2704
-            throw new EE_Error(
2705
-                sprintf(
2706
-                    __(
2707
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2708
-                        "event_espresso"
2709
-                    ),
2710
-                    get_class($this),
2711
-                    $obj_or_fields_array
2712
-                )
2713
-            );
2714
-        }
2715
-        $query_params = array();
2716
-        if ($this->has_primary_key_field()
2717
-            && ($include_primary_key
2718
-                || $this->get_primary_key_field()
2719
-                   instanceof
2720
-                   EE_Primary_Key_String_Field)
2721
-            && isset($fields_n_values[$this->primary_key_name()])
2722
-        ) {
2723
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2724
-        }
2725
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2726
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2727
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2728
-        }
2729
-        //if there is nothing to base this search on, then we shouldn't find anything
2730
-        if (empty($query_params)) {
2731
-            return array();
2732
-        } else {
2733
-            return $this->get_one($query_params);
2734
-        }
2735
-    }
2736
-
2737
-
2738
-
2739
-    /**
2740
-     * Like count, but is optimized and returns a boolean instead of an int
2741
-     *
2742
-     * @param array $query_params
2743
-     * @return boolean
2744
-     * @throws \EE_Error
2745
-     */
2746
-    public function exists($query_params)
2747
-    {
2748
-        $query_params['limit'] = 1;
2749
-        return $this->count($query_params) > 0;
2750
-    }
2751
-
2752
-
2753
-
2754
-    /**
2755
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2756
-     *
2757
-     * @param int|string $id
2758
-     * @return boolean
2759
-     * @throws \EE_Error
2760
-     */
2761
-    public function exists_by_ID($id)
2762
-    {
2763
-        return $this->exists(
2764
-            array(
2765
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2766
-                array(
2767
-                    $this->primary_key_name() => $id
2768
-                )
2769
-            )
2770
-        );
2771
-    }
2772
-
2773
-
2774
-
2775
-    /**
2776
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2777
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2778
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2779
-     * on the main table)
2780
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2781
-     * cases where we want to call it directly rather than via insert().
2782
-     *
2783
-     * @access   protected
2784
-     * @param EE_Table_Base $table
2785
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2786
-     *                                       float
2787
-     * @param int           $new_id          for now we assume only int keys
2788
-     * @throws EE_Error
2789
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2790
-     * @return int ID of new row inserted, or FALSE on failure
2791
-     */
2792
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2793
-    {
2794
-        global $wpdb;
2795
-        $insertion_col_n_values = array();
2796
-        $format_for_insertion = array();
2797
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2798
-        foreach ($fields_on_table as $field_name => $field_obj) {
2799
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2800
-            if ($field_obj->is_auto_increment()) {
2801
-                continue;
2802
-            }
2803
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2804
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2805
-            if ($prepared_value !== null) {
2806
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2807
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2808
-            }
2809
-        }
2810
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2811
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2812
-            //so add the fk to the main table as a column
2813
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2814
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2815
-        }
2816
-        //insert the new entry
2817
-        $result = $this->_do_wpdb_query('insert',
2818
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2819
-        if ($result === false) {
2820
-            return false;
2821
-        }
2822
-        //ok, now what do we return for the ID of the newly-inserted thing?
2823
-        if ($this->has_primary_key_field()) {
2824
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2825
-                return $wpdb->insert_id;
2826
-            } else {
2827
-                //it's not an auto-increment primary key, so
2828
-                //it must have been supplied
2829
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2830
-            }
2831
-        } else {
2832
-            //we can't return a  primary key because there is none. instead return
2833
-            //a unique string indicating this model
2834
-            return $this->get_index_primary_key_string($fields_n_values);
2835
-        }
2836
-    }
2837
-
2838
-
2839
-
2840
-    /**
2841
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2842
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2843
-     * and there is no default, we pass it along. WPDB will take care of it)
2844
-     *
2845
-     * @param EE_Model_Field_Base $field_obj
2846
-     * @param array               $fields_n_values
2847
-     * @return mixed string|int|float depending on what the table column will be expecting
2848
-     * @throws \EE_Error
2849
-     */
2850
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2851
-    {
2852
-        //if this field doesn't allow nullable, don't allow it
2853
-        if ( ! $field_obj->is_nullable()
2854
-             && (
2855
-                 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2856
-        ) {
2857
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2858
-        }
2859
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2860
-            : null;
2861
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2862
-    }
2863
-
2864
-
2865
-
2866
-    /**
2867
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2868
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2869
-     * the field's prepare_for_set() method.
2870
-     *
2871
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2872
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2873
-     *                                   top of file)
2874
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2875
-     *                                   $value is a custom selection
2876
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2877
-     */
2878
-    private function _prepare_value_for_use_in_db($value, $field)
2879
-    {
2880
-        if ($field && $field instanceof EE_Model_Field_Base) {
2881
-            switch ($this->_values_already_prepared_by_model_object) {
2882
-                /** @noinspection PhpMissingBreakStatementInspection */
2883
-                case self::not_prepared_by_model_object:
2884
-                    $value = $field->prepare_for_set($value);
2885
-                //purposefully left out "return"
2886
-                case self::prepared_by_model_object:
2887
-                    $value = $field->prepare_for_use_in_db($value);
2888
-                case self::prepared_for_use_in_db:
2889
-                    //leave the value alone
2890
-            }
2891
-            return $value;
2892
-        } else {
2893
-            return $value;
2894
-        }
2895
-    }
2896
-
2897
-
2898
-
2899
-    /**
2900
-     * Returns the main table on this model
2901
-     *
2902
-     * @return EE_Primary_Table
2903
-     * @throws EE_Error
2904
-     */
2905
-    protected function _get_main_table()
2906
-    {
2907
-        foreach ($this->_tables as $table) {
2908
-            if ($table instanceof EE_Primary_Table) {
2909
-                return $table;
2910
-            }
2911
-        }
2912
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2913
-            'event_espresso'), get_class($this)));
2914
-    }
2915
-
2916
-
2917
-
2918
-    /**
2919
-     * table
2920
-     * returns EE_Primary_Table table name
2921
-     *
2922
-     * @return string
2923
-     * @throws \EE_Error
2924
-     */
2925
-    public function table()
2926
-    {
2927
-        return $this->_get_main_table()->get_table_name();
2928
-    }
2929
-
2930
-
2931
-
2932
-    /**
2933
-     * table
2934
-     * returns first EE_Secondary_Table table name
2935
-     *
2936
-     * @return string
2937
-     */
2938
-    public function second_table()
2939
-    {
2940
-        // grab second table from tables array
2941
-        $second_table = end($this->_tables);
2942
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2943
-    }
2944
-
2945
-
2946
-
2947
-    /**
2948
-     * get_table_obj_by_alias
2949
-     * returns table name given it's alias
2950
-     *
2951
-     * @param string $table_alias
2952
-     * @return EE_Primary_Table | EE_Secondary_Table
2953
-     */
2954
-    public function get_table_obj_by_alias($table_alias = '')
2955
-    {
2956
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2957
-    }
2958
-
2959
-
2960
-
2961
-    /**
2962
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2963
-     *
2964
-     * @return EE_Secondary_Table[]
2965
-     */
2966
-    protected function _get_other_tables()
2967
-    {
2968
-        $other_tables = array();
2969
-        foreach ($this->_tables as $table_alias => $table) {
2970
-            if ($table instanceof EE_Secondary_Table) {
2971
-                $other_tables[$table_alias] = $table;
2972
-            }
2973
-        }
2974
-        return $other_tables;
2975
-    }
2976
-
2977
-
2978
-
2979
-    /**
2980
-     * Finds all the fields that correspond to the given table
2981
-     *
2982
-     * @param string $table_alias , array key in EEM_Base::_tables
2983
-     * @return EE_Model_Field_Base[]
2984
-     */
2985
-    public function _get_fields_for_table($table_alias)
2986
-    {
2987
-        return $this->_fields[$table_alias];
2988
-    }
2989
-
2990
-
2991
-
2992
-    /**
2993
-     * Recurses through all the where parameters, and finds all the related models we'll need
2994
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
2995
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
2996
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
2997
-     * related Registration, Transaction, and Payment models.
2998
-     *
2999
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3000
-     * @return EE_Model_Query_Info_Carrier
3001
-     * @throws \EE_Error
3002
-     */
3003
-    public function _extract_related_models_from_query($query_params)
3004
-    {
3005
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3006
-        if (array_key_exists(0, $query_params)) {
3007
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3008
-        }
3009
-        if (array_key_exists('group_by', $query_params)) {
3010
-            if (is_array($query_params['group_by'])) {
3011
-                $this->_extract_related_models_from_sub_params_array_values(
3012
-                    $query_params['group_by'],
3013
-                    $query_info_carrier,
3014
-                    'group_by'
3015
-                );
3016
-            } elseif ( ! empty ($query_params['group_by'])) {
3017
-                $this->_extract_related_model_info_from_query_param(
3018
-                    $query_params['group_by'],
3019
-                    $query_info_carrier,
3020
-                    'group_by'
3021
-                );
3022
-            }
3023
-        }
3024
-        if (array_key_exists('having', $query_params)) {
3025
-            $this->_extract_related_models_from_sub_params_array_keys(
3026
-                $query_params[0],
3027
-                $query_info_carrier,
3028
-                'having'
3029
-            );
3030
-        }
3031
-        if (array_key_exists('order_by', $query_params)) {
3032
-            if (is_array($query_params['order_by'])) {
3033
-                $this->_extract_related_models_from_sub_params_array_keys(
3034
-                    $query_params['order_by'],
3035
-                    $query_info_carrier,
3036
-                    'order_by'
3037
-                );
3038
-            } elseif ( ! empty($query_params['order_by'])) {
3039
-                $this->_extract_related_model_info_from_query_param(
3040
-                    $query_params['order_by'],
3041
-                    $query_info_carrier,
3042
-                    'order_by'
3043
-                );
3044
-            }
3045
-        }
3046
-        if (array_key_exists('force_join', $query_params)) {
3047
-            $this->_extract_related_models_from_sub_params_array_values(
3048
-                $query_params['force_join'],
3049
-                $query_info_carrier,
3050
-                'force_join'
3051
-            );
3052
-        }
3053
-        return $query_info_carrier;
3054
-    }
3055
-
3056
-
3057
-
3058
-    /**
3059
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3060
-     *
3061
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3062
-     *                                                      $query_params['having']
3063
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3064
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3065
-     * @throws EE_Error
3066
-     * @return \EE_Model_Query_Info_Carrier
3067
-     */
3068
-    private function _extract_related_models_from_sub_params_array_keys(
3069
-        $sub_query_params,
3070
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3071
-        $query_param_type
3072
-    ) {
3073
-        if ( ! empty($sub_query_params)) {
3074
-            $sub_query_params = (array)$sub_query_params;
3075
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3076
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3077
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3078
-                    $query_param_type);
3079
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3080
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3081
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3082
-                //of array('Registration.TXN_ID'=>23)
3083
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3084
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3085
-                    if ( ! is_array($possibly_array_of_params)) {
3086
-                        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'))",
3087
-                            "event_espresso"),
3088
-                            $param, $possibly_array_of_params));
3089
-                    } else {
3090
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3091
-                            $model_query_info_carrier, $query_param_type);
3092
-                    }
3093
-                } elseif ($query_param_type === 0 //ie WHERE
3094
-                          && is_array($possibly_array_of_params)
3095
-                          && isset($possibly_array_of_params[2])
3096
-                          && $possibly_array_of_params[2] == true
3097
-                ) {
3098
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3099
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3100
-                    //from which we should extract query parameters!
3101
-                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3102
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3103
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3104
-                    }
3105
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3106
-                        $model_query_info_carrier, $query_param_type);
3107
-                }
3108
-            }
3109
-        }
3110
-        return $model_query_info_carrier;
3111
-    }
3112
-
3113
-
3114
-
3115
-    /**
3116
-     * For extracting related models from forced_joins, where the array values contain the info about what
3117
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3118
-     *
3119
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3120
-     *                                                      $query_params['having']
3121
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3122
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3123
-     * @throws EE_Error
3124
-     * @return \EE_Model_Query_Info_Carrier
3125
-     */
3126
-    private function _extract_related_models_from_sub_params_array_values(
3127
-        $sub_query_params,
3128
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3129
-        $query_param_type
3130
-    ) {
3131
-        if ( ! empty($sub_query_params)) {
3132
-            if ( ! is_array($sub_query_params)) {
3133
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3134
-                    $sub_query_params));
3135
-            }
3136
-            foreach ($sub_query_params as $param) {
3137
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3138
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3139
-                    $query_param_type);
3140
-            }
3141
-        }
3142
-        return $model_query_info_carrier;
3143
-    }
3144
-
3145
-
3146
-
3147
-    /**
3148
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3149
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3150
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3151
-     * but use them in a different order. Eg, we need to know what models we are querying
3152
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3153
-     * other models before we can finalize the where clause SQL.
3154
-     *
3155
-     * @param array $query_params
3156
-     * @throws EE_Error
3157
-     * @return EE_Model_Query_Info_Carrier
3158
-     */
3159
-    public function _create_model_query_info_carrier($query_params)
3160
-    {
3161
-        if ( ! is_array($query_params)) {
3162
-            EE_Error::doing_it_wrong(
3163
-                'EEM_Base::_create_model_query_info_carrier',
3164
-                sprintf(
3165
-                    __(
3166
-                        '$query_params should be an array, you passed a variable of type %s',
3167
-                        'event_espresso'
3168
-                    ),
3169
-                    gettype($query_params)
3170
-                ),
3171
-                '4.6.0'
3172
-            );
3173
-            $query_params = array();
3174
-        }
3175
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3176
-        //first check if we should alter the query to account for caps or not
3177
-        //because the caps might require us to do extra joins
3178
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3179
-            $query_params[0] = $where_query_params = array_replace_recursive(
3180
-                $where_query_params,
3181
-                $this->caps_where_conditions(
3182
-                    $query_params['caps']
3183
-                )
3184
-            );
3185
-        }
3186
-        $query_object = $this->_extract_related_models_from_query($query_params);
3187
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3188
-        foreach ($where_query_params as $key => $value) {
3189
-            if (is_int($key)) {
3190
-                throw new EE_Error(
3191
-                    sprintf(
3192
-                        __(
3193
-                            "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.",
3194
-                            "event_espresso"
3195
-                        ),
3196
-                        $key,
3197
-                        var_export($value, true),
3198
-                        var_export($query_params, true),
3199
-                        get_class($this)
3200
-                    )
3201
-                );
3202
-            }
3203
-        }
3204
-        if (
3205
-            array_key_exists('default_where_conditions', $query_params)
3206
-            && ! empty($query_params['default_where_conditions'])
3207
-        ) {
3208
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3209
-        } else {
3210
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3211
-        }
3212
-        $where_query_params = array_merge(
3213
-            $this->_get_default_where_conditions_for_models_in_query(
3214
-                $query_object,
3215
-                $use_default_where_conditions,
3216
-                $where_query_params
3217
-            ),
3218
-            $where_query_params
3219
-        );
3220
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3221
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3222
-        // So we need to setup a subquery and use that for the main join.
3223
-        // Note for now this only works on the primary table for the model.
3224
-        // So for instance, you could set the limit array like this:
3225
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3226
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3227
-            $query_object->set_main_model_join_sql(
3228
-                $this->_construct_limit_join_select(
3229
-                    $query_params['on_join_limit'][0],
3230
-                    $query_params['on_join_limit'][1]
3231
-                )
3232
-            );
3233
-        }
3234
-        //set limit
3235
-        if (array_key_exists('limit', $query_params)) {
3236
-            if (is_array($query_params['limit'])) {
3237
-                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3238
-                    $e = sprintf(
3239
-                        __(
3240
-                            "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)",
3241
-                            "event_espresso"
3242
-                        ),
3243
-                        http_build_query($query_params['limit'])
3244
-                    );
3245
-                    throw new EE_Error($e . "|" . $e);
3246
-                }
3247
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3248
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3249
-            } elseif ( ! empty ($query_params['limit'])) {
3250
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3251
-            }
3252
-        }
3253
-        //set order by
3254
-        if (array_key_exists('order_by', $query_params)) {
3255
-            if (is_array($query_params['order_by'])) {
3256
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3257
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3258
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3259
-                if (array_key_exists('order', $query_params)) {
3260
-                    throw new EE_Error(
3261
-                        sprintf(
3262
-                            __(
3263
-                                "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 ",
3264
-                                "event_espresso"
3265
-                            ),
3266
-                            get_class($this),
3267
-                            implode(", ", array_keys($query_params['order_by'])),
3268
-                            implode(", ", $query_params['order_by']),
3269
-                            $query_params['order']
3270
-                        )
3271
-                    );
3272
-                }
3273
-                $this->_extract_related_models_from_sub_params_array_keys(
3274
-                    $query_params['order_by'],
3275
-                    $query_object,
3276
-                    'order_by'
3277
-                );
3278
-                //assume it's an array of fields to order by
3279
-                $order_array = array();
3280
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3281
-                    $order = $this->_extract_order($order);
3282
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3283
-                }
3284
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3285
-            } elseif ( ! empty ($query_params['order_by'])) {
3286
-                $this->_extract_related_model_info_from_query_param(
3287
-                    $query_params['order_by'],
3288
-                    $query_object,
3289
-                    'order',
3290
-                    $query_params['order_by']
3291
-                );
3292
-                $order = isset($query_params['order'])
3293
-                    ? $this->_extract_order($query_params['order'])
3294
-                    : 'DESC';
3295
-                $query_object->set_order_by_sql(
3296
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3297
-                );
3298
-            }
3299
-        }
3300
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3301
-        if ( ! array_key_exists('order_by', $query_params)
3302
-             && array_key_exists('order', $query_params)
3303
-             && ! empty($query_params['order'])
3304
-        ) {
3305
-            $pk_field = $this->get_primary_key_field();
3306
-            $order = $this->_extract_order($query_params['order']);
3307
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3308
-        }
3309
-        //set group by
3310
-        if (array_key_exists('group_by', $query_params)) {
3311
-            if (is_array($query_params['group_by'])) {
3312
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3313
-                $group_by_array = array();
3314
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3315
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3316
-                }
3317
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3318
-            } elseif ( ! empty ($query_params['group_by'])) {
3319
-                $query_object->set_group_by_sql(
3320
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3321
-                );
3322
-            }
3323
-        }
3324
-        //set having
3325
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3326
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3327
-        }
3328
-        //now, just verify they didn't pass anything wack
3329
-        foreach ($query_params as $query_key => $query_value) {
3330
-            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3331
-                throw new EE_Error(
3332
-                    sprintf(
3333
-                        __(
3334
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3335
-                            'event_espresso'
3336
-                        ),
3337
-                        $query_key,
3338
-                        get_class($this),
3339
-                        //						print_r( $this->_allowed_query_params, TRUE )
3340
-                        implode(',', $this->_allowed_query_params)
3341
-                    )
3342
-                );
3343
-            }
3344
-        }
3345
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3346
-        if (empty($main_model_join_sql)) {
3347
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3348
-        }
3349
-        return $query_object;
3350
-    }
3351
-
3352
-
3353
-
3354
-    /**
3355
-     * Gets the where conditions that should be imposed on the query based on the
3356
-     * context (eg reading frontend, backend, edit or delete).
3357
-     *
3358
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3359
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3360
-     * @throws \EE_Error
3361
-     */
3362
-    public function caps_where_conditions($context = self::caps_read)
3363
-    {
3364
-        EEM_Base::verify_is_valid_cap_context($context);
3365
-        $cap_where_conditions = array();
3366
-        $cap_restrictions = $this->caps_missing($context);
3367
-        /**
3368
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3369
-         */
3370
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3371
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3372
-                $restriction_if_no_cap->get_default_where_conditions());
3373
-        }
3374
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3375
-            $cap_restrictions);
3376
-    }
3377
-
3378
-
3379
-
3380
-    /**
3381
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3382
-     * otherwise throws an exception
3383
-     *
3384
-     * @param string $should_be_order_string
3385
-     * @return string either ASC, asc, DESC or desc
3386
-     * @throws EE_Error
3387
-     */
3388
-    private function _extract_order($should_be_order_string)
3389
-    {
3390
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3391
-            return $should_be_order_string;
3392
-        } else {
3393
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3394
-                "event_espresso"), get_class($this), $should_be_order_string));
3395
-        }
3396
-    }
3397
-
3398
-
3399
-
3400
-    /**
3401
-     * Looks at all the models which are included in this query, and asks each
3402
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3403
-     * so they can be merged
3404
-     *
3405
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3406
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3407
-     *                                                                  'none' means NO default where conditions will
3408
-     *                                                                  be used AT ALL during this query.
3409
-     *                                                                  'other_models_only' means default where
3410
-     *                                                                  conditions from other models will be used, but
3411
-     *                                                                  not for this primary model. 'all', the default,
3412
-     *                                                                  means default where conditions will apply as
3413
-     *                                                                  normal
3414
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3415
-     * @throws EE_Error
3416
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3417
-     */
3418
-    private function _get_default_where_conditions_for_models_in_query(
3419
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3420
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3421
-        $where_query_params = array()
3422
-    ) {
3423
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3424
-        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3425
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3426
-                "event_espresso"), $use_default_where_conditions,
3427
-                implode(", ", $allowed_used_default_where_conditions_values)));
3428
-        }
3429
-        $universal_query_params = array();
3430
-        if (
3431
-            in_array(
3432
-                $use_default_where_conditions,
3433
-                array(
3434
-                    EEM_Base::default_where_conditions_all,
3435
-                    EEM_Base::default_where_conditions_this_only,
3436
-                    EEM_Base::default_where_conditions_minimum_others
3437
-                ),
3438
-                true
3439
-            )
3440
-        ) {
3441
-            $universal_query_params = $this->_get_default_where_conditions();
3442
-        } else if ($use_default_where_conditions === EEM_Base::default_where_conditions_minimum_all) {
3443
-            $universal_query_params = $this->_get_minimum_where_conditions();
3444
-        }
3445
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3446
-
3447
-            $related_model = $this->get_related_model_obj($model_name);
3448
-            if (
3449
-                in_array(
3450
-                    $use_default_where_conditions,
3451
-                    array(
3452
-                        EEM_Base::default_where_conditions_all,
3453
-                        EEM_Base::default_where_conditions_others_only
3454
-                    ),
3455
-                    true
3456
-                )
3457
-            ) {
3458
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3459
-            } elseif(
3460
-                in_array(
3461
-                    $use_default_where_conditions,
3462
-                    array(
3463
-                        EEM_Base::default_where_conditions_minimum_others,
3464
-                        EEM_Base::default_where_conditions_minimum_all
3465
-                    ),
3466
-                    true
3467
-                )
3468
-            ) {
3469
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3470
-            } else {
3471
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3472
-                continue;
3473
-            }
3474
-
3475
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3476
-                $related_model_universal_where_params,
3477
-                $where_query_params,
3478
-                $related_model,
3479
-                $model_relation_path
3480
-            );
3481
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3482
-                $universal_query_params,
3483
-                $overrides
3484
-            );
3485
-        }
3486
-        return $universal_query_params;
3487
-    }
3488
-
3489
-
3490
-
3491
-    /**
3492
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3493
-     * then we also add a special where condition which allows for that model's primary key
3494
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3495
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3496
-     *
3497
-     * @param array    $default_where_conditions
3498
-     * @param array    $provided_where_conditions
3499
-     * @param EEM_Base $model
3500
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3501
-     * @return array like EEM_Base::get_all's $query_params[0]
3502
-     * @throws \EE_Error
3503
-     */
3504
-    private function _override_defaults_or_make_null_friendly(
3505
-        $default_where_conditions,
3506
-        $provided_where_conditions,
3507
-        $model,
3508
-        $model_relation_path
3509
-    ) {
3510
-        $null_friendly_where_conditions = array();
3511
-        $none_overridden = true;
3512
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3513
-        foreach ($default_where_conditions as $key => $val) {
3514
-            if (isset($provided_where_conditions[$key])) {
3515
-                $none_overridden = false;
3516
-            } else {
3517
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3518
-            }
3519
-        }
3520
-        if ($none_overridden && $default_where_conditions) {
3521
-            if ($model->has_primary_key_field()) {
3522
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3523
-                                                                                . "."
3524
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3525
-            }/*else{
32
+	//admin posty
33
+	//basic -> grants access to mine -> if they don't have it, select none
34
+	//*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
+	//*_published -> grants access to published -> if they dont have it, select non-published
37
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
39
+	//frontend posty
40
+	//by default has access to published
41
+	//basic -> grants access to mine that arent published, and all published
42
+	//*_others ->grants access to others that arent private, all mine
43
+	//*_private -> grants full access
44
+	//frontend non-posty
45
+	//like admin posty
46
+	//category-y
47
+	//assign -> grants access to join-table
48
+	//(delete, edit)
49
+	//payment-method-y
50
+	//for each registered payment method,
51
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
+	/**
53
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
56
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
+	 *
58
+	 * @var boolean
59
+	 */
60
+	private $_values_already_prepared_by_model_object = 0;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the data is just like form input that needs to have the model fields'
65
+	 * prepare_for_set and prepare_for_use_in_db called on it
66
+	 */
67
+	const not_prepared_by_model_object = 0;
68
+
69
+	/**
70
+	 * when $_values_already_prepared_by_model_object equals this, we
71
+	 * assume this value is coming from a model object and doesn't need to have
72
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
73
+	 */
74
+	const prepared_by_model_object = 1;
75
+
76
+	/**
77
+	 * when $_values_already_prepared_by_model_object equals this, we assume
78
+	 * the values are already to be used in the database (ie no processing is done
79
+	 * on them by the model's fields)
80
+	 */
81
+	const prepared_for_use_in_db = 2;
82
+
83
+
84
+	protected $singular_item = 'Item';
85
+
86
+	protected $plural_item   = 'Items';
87
+
88
+	/**
89
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
+	 */
91
+	protected $_tables;
92
+
93
+	/**
94
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
+	 *
98
+	 * @var \EE_Model_Field_Base[] $_fields
99
+	 */
100
+	protected $_fields;
101
+
102
+	/**
103
+	 * array of different kinds of relations
104
+	 *
105
+	 * @var \EE_Model_Relation_Base[] $_model_relations
106
+	 */
107
+	protected $_model_relations;
108
+
109
+	/**
110
+	 * @var \EE_Index[] $_indexes
111
+	 */
112
+	protected $_indexes = array();
113
+
114
+	/**
115
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
116
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
+	 * by setting the same columns as used in these queries in the query yourself.
118
+	 *
119
+	 * @var EE_Default_Where_Conditions
120
+	 */
121
+	protected $_default_where_conditions_strategy;
122
+
123
+	/**
124
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
+	 * This is particularly useful when you want something between 'none' and 'default'
126
+	 *
127
+	 * @var EE_Default_Where_Conditions
128
+	 */
129
+	protected $_minimum_where_conditions_strategy;
130
+
131
+	/**
132
+	 * String describing how to find the "owner" of this model's objects.
133
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
+	 * But when there isn't, this indicates which related model, or transiently-related model,
135
+	 * has the foreign key to the wp_users table.
136
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
+	 * related to events, and events have a foreign key to wp_users.
138
+	 * On EEM_Transaction, this would be 'Transaction.Event'
139
+	 *
140
+	 * @var string
141
+	 */
142
+	protected $_model_chain_to_wp_user = '';
143
+
144
+	/**
145
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
+	 * don't need it (particularly CPT models)
147
+	 *
148
+	 * @var bool
149
+	 */
150
+	protected $_ignore_where_strategy = false;
151
+
152
+	/**
153
+	 * String used in caps relating to this model. Eg, if the caps relating to this
154
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
+	 *
156
+	 * @var string. If null it hasn't been initialized yet. If false then we
157
+	 * have indicated capabilities don't apply to this
158
+	 */
159
+	protected $_caps_slug = null;
160
+
161
+	/**
162
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
+	 * and next-level keys are capability names, and each's value is a
164
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
166
+	 * and then each capability in the corresponding sub-array that they're missing
167
+	 * adds the where conditions onto the query.
168
+	 *
169
+	 * @var array
170
+	 */
171
+	protected $_cap_restrictions = array(
172
+		self::caps_read       => array(),
173
+		self::caps_read_admin => array(),
174
+		self::caps_edit       => array(),
175
+		self::caps_delete     => array(),
176
+	);
177
+
178
+	/**
179
+	 * Array defining which cap restriction generators to use to create default
180
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
181
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
+	 * automatically set this to false (not just null).
184
+	 *
185
+	 * @var EE_Restriction_Generator_Base[]
186
+	 */
187
+	protected $_cap_restriction_generators = array();
188
+
189
+	/**
190
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
+	 */
192
+	const caps_read       = 'read';
193
+
194
+	const caps_read_admin = 'read_admin';
195
+
196
+	const caps_edit       = 'edit';
197
+
198
+	const caps_delete     = 'delete';
199
+
200
+	/**
201
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
+	 * maps to 'read' because when looking for relevant permissions we're going to use
204
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
205
+	 *
206
+	 * @var array
207
+	 */
208
+	protected $_cap_contexts_to_cap_action_map = array(
209
+		self::caps_read       => 'read',
210
+		self::caps_read_admin => 'read',
211
+		self::caps_edit       => 'edit',
212
+		self::caps_delete     => 'delete',
213
+	);
214
+
215
+	/**
216
+	 * Timezone
217
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
+	 * EE_Datetime_Field data type will have access to it.
221
+	 *
222
+	 * @var string
223
+	 */
224
+	protected $_timezone;
225
+
226
+
227
+	/**
228
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
+	 * multisite.
230
+	 *
231
+	 * @var int
232
+	 */
233
+	protected static $_model_query_blog_id;
234
+
235
+	/**
236
+	 * A copy of _fields, except the array keys are the model names pointed to by
237
+	 * the field
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cache_foreign_key_to_fields = array();
242
+
243
+	/**
244
+	 * Cached list of all the fields on the model, indexed by their name
245
+	 *
246
+	 * @var EE_Model_Field_Base[]
247
+	 */
248
+	private $_cached_fields = null;
249
+
250
+	/**
251
+	 * Cached list of all the fields on the model, except those that are
252
+	 * marked as only pertinent to the database
253
+	 *
254
+	 * @var EE_Model_Field_Base[]
255
+	 */
256
+	private $_cached_fields_non_db_only = null;
257
+
258
+	/**
259
+	 * A cached reference to the primary key for quick lookup
260
+	 *
261
+	 * @var EE_Model_Field_Base
262
+	 */
263
+	private $_primary_key_field = null;
264
+
265
+	/**
266
+	 * Flag indicating whether this model has a primary key or not
267
+	 *
268
+	 * @var boolean
269
+	 */
270
+	protected $_has_primary_key_field = null;
271
+
272
+	/**
273
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
274
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
+	 *
276
+	 * @var boolean
277
+	 */
278
+	protected $_wp_core_model = false;
279
+
280
+	/**
281
+	 *    List of valid operators that can be used for querying.
282
+	 * The keys are all operators we'll accept, the values are the real SQL
283
+	 * operators used
284
+	 *
285
+	 * @var array
286
+	 */
287
+	protected $_valid_operators = array(
288
+		'='           => '=',
289
+		'<='          => '<=',
290
+		'<'           => '<',
291
+		'>='          => '>=',
292
+		'>'           => '>',
293
+		'!='          => '!=',
294
+		'LIKE'        => 'LIKE',
295
+		'like'        => 'LIKE',
296
+		'NOT_LIKE'    => 'NOT LIKE',
297
+		'not_like'    => 'NOT LIKE',
298
+		'NOT LIKE'    => 'NOT LIKE',
299
+		'not like'    => 'NOT LIKE',
300
+		'IN'          => 'IN',
301
+		'in'          => 'IN',
302
+		'NOT_IN'      => 'NOT IN',
303
+		'not_in'      => 'NOT IN',
304
+		'NOT IN'      => 'NOT IN',
305
+		'not in'      => 'NOT IN',
306
+		'between'     => 'BETWEEN',
307
+		'BETWEEN'     => 'BETWEEN',
308
+		'IS_NOT_NULL' => 'IS NOT NULL',
309
+		'is_not_null' => 'IS NOT NULL',
310
+		'IS NOT NULL' => 'IS NOT NULL',
311
+		'is not null' => 'IS NOT NULL',
312
+		'IS_NULL'     => 'IS NULL',
313
+		'is_null'     => 'IS NULL',
314
+		'IS NULL'     => 'IS NULL',
315
+		'is null'     => 'IS NULL',
316
+		'REGEXP'      => 'REGEXP',
317
+		'regexp'      => 'REGEXP',
318
+		'NOT_REGEXP'  => 'NOT REGEXP',
319
+		'not_regexp'  => 'NOT REGEXP',
320
+		'NOT REGEXP'  => 'NOT REGEXP',
321
+		'not regexp'  => 'NOT REGEXP',
322
+	);
323
+
324
+	/**
325
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
+	 *
327
+	 * @var array
328
+	 */
329
+	protected $_in_style_operators = array('IN', 'NOT IN');
330
+
331
+	/**
332
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
+	 * '12-31-2012'"
334
+	 *
335
+	 * @var array
336
+	 */
337
+	protected $_between_style_operators = array('BETWEEN');
338
+
339
+	/**
340
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
+	 * on a join table.
342
+	 *
343
+	 * @var array
344
+	 */
345
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
+
347
+	/**
348
+	 * Allowed values for $query_params['order'] for ordering in queries
349
+	 *
350
+	 * @var array
351
+	 */
352
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
+
354
+	/**
355
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
357
+	 *
358
+	 * @var array
359
+	 */
360
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
+
362
+	/**
363
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
365
+	 *
366
+	 * @var array
367
+	 */
368
+	private $_allowed_query_params = array(
369
+		0,
370
+		'limit',
371
+		'order_by',
372
+		'group_by',
373
+		'having',
374
+		'force_join',
375
+		'order',
376
+		'on_join_limit',
377
+		'default_where_conditions',
378
+		'caps',
379
+	);
380
+
381
+	/**
382
+	 * All the data types that can be used in $wpdb->prepare statements.
383
+	 *
384
+	 * @var array
385
+	 */
386
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
+
388
+	/**
389
+	 *    EE_Registry Object
390
+	 *
391
+	 * @var    object
392
+	 * @access    protected
393
+	 */
394
+	protected $EE = null;
395
+
396
+
397
+	/**
398
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
+	 *
400
+	 * @var int
401
+	 */
402
+	protected $_show_next_x_db_queries = 0;
403
+
404
+	/**
405
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
+	 *
408
+	 * @var array
409
+	 */
410
+	protected $_custom_selections = array();
411
+
412
+	/**
413
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
+	 * caches every model object we've fetched from the DB on this request
415
+	 *
416
+	 * @var array
417
+	 */
418
+	protected $_entity_map;
419
+
420
+	/**
421
+	 * constant used to show EEM_Base has not yet verified the db on this http request
422
+	 */
423
+	const db_verified_none = 0;
424
+
425
+	/**
426
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
427
+	 * but not the addons' dbs
428
+	 */
429
+	const db_verified_core = 1;
430
+
431
+	/**
432
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
+	 * the EE core db too)
434
+	 */
435
+	const db_verified_addons = 2;
436
+
437
+	/**
438
+	 * indicates whether an EEM_Base child has already re-verified the DB
439
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
440
+	 * looking like EEM_Base::db_verified_*
441
+	 *
442
+	 * @var int - 0 = none, 1 = core, 2 = addons
443
+	 */
444
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
445
+
446
+	/**
447
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
448
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed registrations
449
+	 *        for non-trashed tickets for non-trashed datetimes)
450
+	 */
451
+	const default_where_conditions_all = 'all';
452
+
453
+	/**
454
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
455
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
456
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
457
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
458
+	 *        models which share tables with other models, this can return data for the wrong model.
459
+	 */
460
+	const default_where_conditions_this_only = 'this_model_only';
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
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
469
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
470
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
471
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
472
+	 *        (regardless of whether those events and venues are trashed)
473
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE events.
474
+	 */
475
+	const default_where_conditions_minimum_all = 'minimum';
476
+	/**
477
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
478
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will return
479
+	 *        non-trashed events for any venues, regardless of whether those associated venues are trashed or not)
480
+	 */
481
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
482
+	/**
483
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be used,
484
+	 *        because when querying from a model which shares its table with another model (eg Events and Venues)
485
+	 *        it's possible it will return table entries for other models. You should use EEM_Base::default_where_conditions_minimum_all
486
+	 *        instead.
487
+	 */
488
+	const default_where_conditions_none = 'none';
489
+
490
+
491
+
492
+	/**
493
+	 * About all child constructors:
494
+	 * they should define the _tables, _fields and _model_relations arrays.
495
+	 * Should ALWAYS be called after child constructor.
496
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
497
+	 * finalizes constructing all the object's attributes.
498
+	 * Generally, rather than requiring a child to code
499
+	 * $this->_tables = array(
500
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
501
+	 *        ...);
502
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
503
+	 * each EE_Table has a function to set the table's alias after the constructor, using
504
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
505
+	 * do something similar.
506
+	 *
507
+	 * @param null $timezone
508
+	 * @throws \EE_Error
509
+	 */
510
+	protected function __construct($timezone = null)
511
+	{
512
+		// check that the model has not been loaded too soon
513
+		if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
514
+			throw new EE_Error (
515
+				sprintf(
516
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
517
+						'event_espresso'),
518
+					get_class($this)
519
+				)
520
+			);
521
+		}
522
+		/**
523
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
524
+		 */
525
+		if (empty(EEM_Base::$_model_query_blog_id)) {
526
+			EEM_Base::set_model_query_blog_id();
527
+		}
528
+		/**
529
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
530
+		 * just use EE_Register_Model_Extension
531
+		 *
532
+		 * @var EE_Table_Base[] $_tables
533
+		 */
534
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
535
+		foreach ($this->_tables as $table_alias => $table_obj) {
536
+			/** @var $table_obj EE_Table_Base */
537
+			$table_obj->_construct_finalize_with_alias($table_alias);
538
+			if ($table_obj instanceof EE_Secondary_Table) {
539
+				/** @var $table_obj EE_Secondary_Table */
540
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
541
+			}
542
+		}
543
+		/**
544
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
545
+		 * EE_Register_Model_Extension
546
+		 *
547
+		 * @param EE_Model_Field_Base[] $_fields
548
+		 */
549
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
550
+		$this->_invalidate_field_caches();
551
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
552
+			if ( ! array_key_exists($table_alias, $this->_tables)) {
553
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
554
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
555
+			}
556
+			foreach ($fields_for_table as $field_name => $field_obj) {
557
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
558
+				//primary key field base has a slightly different _construct_finalize
559
+				/** @var $field_obj EE_Model_Field_Base */
560
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
561
+			}
562
+		}
563
+		// everything is related to Extra_Meta
564
+		if (get_class($this) !== 'EEM_Extra_Meta') {
565
+			//make extra meta related to everything, but don't block deleting things just
566
+			//because they have related extra meta info. For now just orphan those extra meta
567
+			//in the future we should automatically delete them
568
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
569
+		}
570
+		//and change logs
571
+		if (get_class($this) !== 'EEM_Change_Log') {
572
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
573
+		}
574
+		/**
575
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
576
+		 * EE_Register_Model_Extension
577
+		 *
578
+		 * @param EE_Model_Relation_Base[] $_model_relations
579
+		 */
580
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
581
+			$this->_model_relations);
582
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
583
+			/** @var $relation_obj EE_Model_Relation_Base */
584
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
585
+		}
586
+		foreach ($this->_indexes as $index_name => $index_obj) {
587
+			/** @var $index_obj EE_Index */
588
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
589
+		}
590
+		$this->set_timezone($timezone);
591
+		//finalize default where condition strategy, or set default
592
+		if ( ! $this->_default_where_conditions_strategy) {
593
+			//nothing was set during child constructor, so set default
594
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
595
+		}
596
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
597
+		if ( ! $this->_minimum_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
602
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
603
+		//to indicate to NOT set it, set it to the logical default
604
+		if ($this->_caps_slug === null) {
605
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
606
+		}
607
+		//initialize the standard cap restriction generators if none were specified by the child constructor
608
+		if ($this->_cap_restriction_generators !== false) {
609
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
610
+				if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
611
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
612
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
613
+						new EE_Restriction_Generator_Protected(),
614
+						$cap_context,
615
+						$this
616
+					);
617
+				}
618
+			}
619
+		}
620
+		//if there are cap restriction generators, use them to make the default cap restrictions
621
+		if ($this->_cap_restriction_generators !== false) {
622
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
623
+				if ( ! $generator_object) {
624
+					continue;
625
+				}
626
+				if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
627
+					throw new EE_Error(
628
+						sprintf(
629
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
630
+								'event_espresso'),
631
+							$context,
632
+							$this->get_this_model_name()
633
+						)
634
+					);
635
+				}
636
+				$action = $this->cap_action_for_context($context);
637
+				if ( ! $generator_object->construction_finalized()) {
638
+					$generator_object->_construct_finalize($this, $action);
639
+				}
640
+			}
641
+		}
642
+		do_action('AHEE__' . get_class($this) . '__construct__end');
643
+	}
644
+
645
+
646
+
647
+	/**
648
+	 * Generates the cap restrictions for the given context, or if they were
649
+	 * already generated just gets what's cached
650
+	 *
651
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
652
+	 * @return EE_Default_Where_Conditions[]
653
+	 */
654
+	protected function _generate_cap_restrictions($context)
655
+	{
656
+		if (isset($this->_cap_restriction_generators[$context])
657
+			&& $this->_cap_restriction_generators[$context]
658
+			   instanceof
659
+			   EE_Restriction_Generator_Base
660
+		) {
661
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
662
+		} else {
663
+			return array();
664
+		}
665
+	}
666
+
667
+
668
+
669
+	/**
670
+	 * Used to set the $_model_query_blog_id static property.
671
+	 *
672
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
673
+	 *                      value for get_current_blog_id() will be used.
674
+	 */
675
+	public static function set_model_query_blog_id($blog_id = 0)
676
+	{
677
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
678
+	}
679
+
680
+
681
+
682
+	/**
683
+	 * Returns whatever is set as the internal $model_query_blog_id.
684
+	 *
685
+	 * @return int
686
+	 */
687
+	public static function get_model_query_blog_id()
688
+	{
689
+		return EEM_Base::$_model_query_blog_id;
690
+	}
691
+
692
+
693
+
694
+	/**
695
+	 *        This function is a singleton method used to instantiate the Espresso_model object
696
+	 *
697
+	 * @access public
698
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
699
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
700
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
701
+	 *                         timezone in the 'timezone_string' wp option)
702
+	 * @return static (as in the concrete child class)
703
+	 */
704
+	public static function instance($timezone = null)
705
+	{
706
+		// check if instance of Espresso_model already exists
707
+		if ( ! static::$_instance instanceof static) {
708
+			// instantiate Espresso_model
709
+			static::$_instance = new static($timezone);
710
+		}
711
+		//we might have a timezone set, let set_timezone decide what to do with it
712
+		static::$_instance->set_timezone($timezone);
713
+		// Espresso_model object
714
+		return static::$_instance;
715
+	}
716
+
717
+
718
+
719
+	/**
720
+	 * resets the model and returns it
721
+	 *
722
+	 * @param null | string $timezone
723
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
724
+	 * all its properties reset; if it wasn't instantiated, returns null)
725
+	 */
726
+	public static function reset($timezone = null)
727
+	{
728
+		if (static::$_instance instanceof EEM_Base) {
729
+			//let's try to NOT swap out the current instance for a new one
730
+			//because if someone has a reference to it, we can't remove their reference
731
+			//so it's best to keep using the same reference, but change the original object
732
+			//reset all its properties to their original values as defined in the class
733
+			$r = new ReflectionClass(get_class(static::$_instance));
734
+			$static_properties = $r->getStaticProperties();
735
+			foreach ($r->getDefaultProperties() as $property => $value) {
736
+				//don't set instance to null like it was originally,
737
+				//but it's static anyways, and we're ignoring static properties (for now at least)
738
+				if ( ! isset($static_properties[$property])) {
739
+					static::$_instance->{$property} = $value;
740
+				}
741
+			}
742
+			//and then directly call its constructor again, like we would if we
743
+			//were creating a new one
744
+			static::$_instance->__construct($timezone);
745
+			return self::instance();
746
+		}
747
+		return null;
748
+	}
749
+
750
+
751
+
752
+	/**
753
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
754
+	 *
755
+	 * @param  boolean $translated return localized strings or JUST the array.
756
+	 * @return array
757
+	 * @throws \EE_Error
758
+	 */
759
+	public function status_array($translated = false)
760
+	{
761
+		if ( ! array_key_exists('Status', $this->_model_relations)) {
762
+			return array();
763
+		}
764
+		$model_name = $this->get_this_model_name();
765
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
766
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
767
+		$status_array = array();
768
+		foreach ($stati as $status) {
769
+			$status_array[$status->ID()] = $status->get('STS_code');
770
+		}
771
+		return $translated
772
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
773
+			: $status_array;
774
+	}
775
+
776
+
777
+
778
+	/**
779
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
780
+	 *
781
+	 * @param array $query_params             {
782
+	 * @var array $0 (where) array {
783
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
784
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
785
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
786
+	 *                                        conditions based on related models (and even
787
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
788
+	 *                                        name. Eg,
789
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
790
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
791
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
792
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
793
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE Venue_CPT.ID = 12 Notice that automatically
794
+	 *                                        took care of joining Events to Venues (even when each of those models actually consisted of two tables). Also, you may chain the model relations together. Eg instead of just having
795
+	 *                                        "Venue.VNU_ID", you could have
796
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
797
+	 *                                        events are related to Registrations, which are related to Attendees). You
798
+	 *                                        can take it even further with
799
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
800
+	 *                                        (from the default of '='), change the value to an numerically-indexed
801
+	 *                                        array, where the first item in the list is the operator. eg: array(
802
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
803
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
804
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
805
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
806
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL Values can be a string, int, or float. They can
807
+	 *                                        also be arrays IFF the operator is IN. Also, values can actually be field names. To indicate the value is a field, simply provide a third array item (true) to the operator-value array like so:
808
+	 *                                        eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold" Note: you can also use related model field names like you would any other field
809
+	 *                                        name. eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default
810
+	 *                                        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__>' =>
811
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...". Also, to negate an entire set of conditions, use 'NOT' as an array key. eg: array('NOT'=>array('TXN_total' =>
812
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND TXN_paid =23) Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default,
813
+	 *                                        but if you had previously specified to use ORs to join, ORs will continue to be used. So, if you specify to use an "OR" to join conditions, it will continue to "stick" until you specify an AND.
814
+	 *                                        eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
815
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg: array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes
816
+	 *                                        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
817
+	 *                                        place two or more where conditions applying to the same field. eg:
818
+	 *                                        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
819
+	 *                                        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 '*'
820
+	 *                                        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
821
+	 *                                        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 >>
822
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123" This can be applied to condition operators too, eg:
823
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
824
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
825
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL "...LIMIT 23", "...LIMIT 25,50",
826
+	 *                                        and "...LIMIT 23,42" respectively. Remember when you provide two numbers for the limit, the 1st number is
827
+	 *                                        the OFFSET, the 2nd is the LIMIT
828
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
829
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the following format array('on_join_limit'
830
+	 *                                        => array( 'table_alias', array(1,2) ) ).
831
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
832
+	 *                                        values are either 'ASC' or 'DESC'. 'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
833
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively. Like the
834
+	 *                                        'where' conditions, these fields can be on related models. Eg
835
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related
836
+	 *                                        to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
837
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
838
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in ascending or descending order.
839
+	 *                                        Acceptable values are 'ASC' or 'DESC'. If, 'order_by' isn't used, but 'order' is, then it is assumed you
840
+	 *                                        want to order by the primary key. Eg,
841
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC'); //(will join
842
+	 *                                        with the Datetime model's table(s) and order by its field DTT_EVT_start) or
843
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM
844
+	 *                                        wp_esp_registration ORDER BY REG_ID ASC"
845
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
846
+	 *                                        'group_by'=>'VNU_ID', or 'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note: if no
847
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the model's primary key (or combined
848
+	 *                                        primary keys). This avoids some weirdness that results when using limits, tons of joins, and no group by,
849
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
850
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
851
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped results)
852
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
853
+	 *                                        array where values are models to be joined in the query.Eg array('Attendee','Payment','Datetime'). You may
854
+	 *                                        join with transient models using period, eg "Registration.Transaction.Payment". You will probably only want
855
+	 *                                        to do this in hopes of increasing efficiency, as related models which belongs to the current model
856
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
857
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
858
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
859
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually soft-deleted objects are
860
+	 *                                        filtered-out if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS
861
+	 *                                        model's default where conditions set it to 'other_models_only'. If you only want this model's default where
862
+	 *                                        conditions added to the query, use 'this_model_only'. If you want to use all default where conditions
863
+	 *                                        (default), set to 'all'.
864
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
865
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return everything? Or should we only show
866
+	 *                                        the current user items they should be able to view on the frontend, backend, edit, or delete? can be set to
867
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
868
+	 *                                        }
869
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
870
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public again. Array keys
871
+	 *                                        are object IDs (if there is a primary key on the model. if not, numerically indexed)
872
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
873
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
874
+	 *                                        'OR'=>array(
875
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
876
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
877
+	 *                                        )
878
+	 *                                        ),
879
+	 *                                        'limit'=>10,
880
+	 *                                        'group_by'=>'TXN_ID'
881
+	 *                                        ));
882
+	 *                                        get all the answers to the question titled "shirt size" for event with id
883
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
884
+	 *                                        'Question.QST_display_text'=>'shirt size',
885
+	 *                                        'Registration.Event.EVT_ID'=>12
886
+	 *                                        ),
887
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
888
+	 *                                        ));
889
+	 * @throws \EE_Error
890
+	 */
891
+	public function get_all($query_params = array())
892
+	{
893
+		if (isset($query_params['limit'])
894
+			&& ! isset($query_params['group_by'])
895
+		) {
896
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
897
+		}
898
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
899
+	}
900
+
901
+
902
+
903
+	/**
904
+	 * Modifies the query parameters so we only get back model objects
905
+	 * that "belong" to the current user
906
+	 *
907
+	 * @param array $query_params @see EEM_Base::get_all()
908
+	 * @return array like EEM_Base::get_all
909
+	 */
910
+	public function alter_query_params_to_only_include_mine($query_params = array())
911
+	{
912
+		$wp_user_field_name = $this->wp_user_field_name();
913
+		if ($wp_user_field_name) {
914
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
915
+		}
916
+		return $query_params;
917
+	}
918
+
919
+
920
+
921
+	/**
922
+	 * Returns the name of the field's name that points to the WP_User table
923
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
924
+	 * foreign key to the WP_User table)
925
+	 *
926
+	 * @return string|boolean string on success, boolean false when there is no
927
+	 * foreign key to the WP_User table
928
+	 */
929
+	public function wp_user_field_name()
930
+	{
931
+		try {
932
+			if ( ! empty($this->_model_chain_to_wp_user)) {
933
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
934
+				$last_model_name = end($models_to_follow_to_wp_users);
935
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
936
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
937
+			} else {
938
+				$model_with_fk_to_wp_users = $this;
939
+				$model_chain_to_wp_user = '';
940
+			}
941
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
942
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
943
+		} catch (EE_Error $e) {
944
+			return false;
945
+		}
946
+	}
947
+
948
+
949
+
950
+	/**
951
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
952
+	 * (or transiently-related model) has a foreign key to the wp_users table;
953
+	 * useful for finding if model objects of this type are 'owned' by the current user.
954
+	 * This is an empty string when the foreign key is on this model and when it isn't,
955
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
956
+	 * (or transiently-related model)
957
+	 *
958
+	 * @return string
959
+	 */
960
+	public function model_chain_to_wp_user()
961
+	{
962
+		return $this->_model_chain_to_wp_user;
963
+	}
964
+
965
+
966
+
967
+	/**
968
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
969
+	 * like how registrations don't have a foreign key to wp_users, but the
970
+	 * events they are for are), or is unrelated to wp users.
971
+	 * generally available
972
+	 *
973
+	 * @return boolean
974
+	 */
975
+	public function is_owned()
976
+	{
977
+		if ($this->model_chain_to_wp_user()) {
978
+			return true;
979
+		} else {
980
+			try {
981
+				$this->get_foreign_key_to('WP_User');
982
+				return true;
983
+			} catch (EE_Error $e) {
984
+				return false;
985
+			}
986
+		}
987
+	}
988
+
989
+
990
+
991
+	/**
992
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
993
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
994
+	 * the model)
995
+	 *
996
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
997
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
998
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
999
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1000
+	 *                                  override this and set the select to "*", or a specific column name, like
1001
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1002
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1003
+	 *                                  the aliases used to refer to this selection, and values are to be
1004
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1005
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1006
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1007
+	 * @throws \EE_Error
1008
+	 */
1009
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1010
+	{
1011
+		// remember the custom selections, if any, and type cast as array
1012
+		// (unless $columns_to_select is an object, then just set as an empty array)
1013
+		// Note: (array) 'some string' === array( 'some string' )
1014
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1015
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1016
+		$select_expressions = $columns_to_select !== null
1017
+			? $this->_construct_select_from_input($columns_to_select)
1018
+			: $this->_construct_default_select_sql($model_query_info);
1019
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1020
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1021
+	}
1022
+
1023
+
1024
+
1025
+	/**
1026
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1027
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1028
+	 * take care of joins, field preparation etc.
1029
+	 *
1030
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1031
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1032
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1033
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1034
+	 *                                  override this and set the select to "*", or a specific column name, like
1035
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1036
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1037
+	 *                                  the aliases used to refer to this selection, and values are to be
1038
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1039
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1040
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1041
+	 * @throws \EE_Error
1042
+	 */
1043
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1044
+	{
1045
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1046
+	}
1047
+
1048
+
1049
+
1050
+	/**
1051
+	 * For creating a custom select statement
1052
+	 *
1053
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1054
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1055
+	 *                                 SQL, and 1=>is the datatype
1056
+	 * @throws EE_Error
1057
+	 * @return string
1058
+	 */
1059
+	private function _construct_select_from_input($columns_to_select)
1060
+	{
1061
+		if (is_array($columns_to_select)) {
1062
+			$select_sql_array = array();
1063
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1064
+				if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1065
+					throw new EE_Error(
1066
+						sprintf(
1067
+							__(
1068
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1069
+								"event_espresso"
1070
+							),
1071
+							$selection_and_datatype,
1072
+							$alias
1073
+						)
1074
+					);
1075
+				}
1076
+				if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1077
+					throw new EE_Error(
1078
+						sprintf(
1079
+							__(
1080
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1081
+								"event_espresso"
1082
+							),
1083
+							$selection_and_datatype[1],
1084
+							$selection_and_datatype[0],
1085
+							$alias,
1086
+							implode(",", $this->_valid_wpdb_data_types)
1087
+						)
1088
+					);
1089
+				}
1090
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1091
+			}
1092
+			$columns_to_select_string = implode(", ", $select_sql_array);
1093
+		} else {
1094
+			$columns_to_select_string = $columns_to_select;
1095
+		}
1096
+		return $columns_to_select_string;
1097
+	}
1098
+
1099
+
1100
+
1101
+	/**
1102
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1103
+	 *
1104
+	 * @return string
1105
+	 * @throws \EE_Error
1106
+	 */
1107
+	public function primary_key_name()
1108
+	{
1109
+		return $this->get_primary_key_field()->get_name();
1110
+	}
1111
+
1112
+
1113
+
1114
+	/**
1115
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1116
+	 * If there is no primary key on this model, $id is treated as primary key string
1117
+	 *
1118
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1119
+	 * @return EE_Base_Class
1120
+	 */
1121
+	public function get_one_by_ID($id)
1122
+	{
1123
+		if ($this->get_from_entity_map($id)) {
1124
+			return $this->get_from_entity_map($id);
1125
+		}
1126
+		return $this->get_one(
1127
+			$this->alter_query_params_to_restrict_by_ID(
1128
+				$id,
1129
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1130
+			)
1131
+		);
1132
+	}
1133
+
1134
+
1135
+
1136
+	/**
1137
+	 * Alters query parameters to only get items with this ID are returned.
1138
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1139
+	 * or could just be a simple primary key ID
1140
+	 *
1141
+	 * @param int   $id
1142
+	 * @param array $query_params
1143
+	 * @return array of normal query params, @see EEM_Base::get_all
1144
+	 * @throws \EE_Error
1145
+	 */
1146
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1147
+	{
1148
+		if ( ! isset($query_params[0])) {
1149
+			$query_params[0] = array();
1150
+		}
1151
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1152
+		if ($conditions_from_id === null) {
1153
+			$query_params[0][$this->primary_key_name()] = $id;
1154
+		} else {
1155
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1156
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1157
+		}
1158
+		return $query_params;
1159
+	}
1160
+
1161
+
1162
+
1163
+	/**
1164
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1165
+	 * array. If no item is found, null is returned.
1166
+	 *
1167
+	 * @param array $query_params like EEM_Base's $query_params variable.
1168
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1169
+	 * @throws \EE_Error
1170
+	 */
1171
+	public function get_one($query_params = array())
1172
+	{
1173
+		if ( ! is_array($query_params)) {
1174
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1175
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1176
+					gettype($query_params)), '4.6.0');
1177
+			$query_params = array();
1178
+		}
1179
+		$query_params['limit'] = 1;
1180
+		$items = $this->get_all($query_params);
1181
+		if (empty($items)) {
1182
+			return null;
1183
+		} else {
1184
+			return array_shift($items);
1185
+		}
1186
+	}
1187
+
1188
+
1189
+
1190
+	/**
1191
+	 * Returns the next x number of items in sequence from the given value as
1192
+	 * found in the database matching the given query conditions.
1193
+	 *
1194
+	 * @param mixed $current_field_value    Value used for the reference point.
1195
+	 * @param null  $field_to_order_by      What field is used for the
1196
+	 *                                      reference point.
1197
+	 * @param int   $limit                  How many to return.
1198
+	 * @param array $query_params           Extra conditions on the query.
1199
+	 * @param null  $columns_to_select      If left null, then an array of
1200
+	 *                                      EE_Base_Class objects is returned,
1201
+	 *                                      otherwise you can indicate just the
1202
+	 *                                      columns you want returned.
1203
+	 * @return EE_Base_Class[]|array
1204
+	 * @throws \EE_Error
1205
+	 */
1206
+	public function next_x(
1207
+		$current_field_value,
1208
+		$field_to_order_by = null,
1209
+		$limit = 1,
1210
+		$query_params = array(),
1211
+		$columns_to_select = null
1212
+	) {
1213
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1214
+			$columns_to_select);
1215
+	}
1216
+
1217
+
1218
+
1219
+	/**
1220
+	 * Returns the previous x number of items in sequence from the given value
1221
+	 * as found in the database matching the given query conditions.
1222
+	 *
1223
+	 * @param mixed $current_field_value    Value used for the reference point.
1224
+	 * @param null  $field_to_order_by      What field is used for the
1225
+	 *                                      reference point.
1226
+	 * @param int   $limit                  How many to return.
1227
+	 * @param array $query_params           Extra conditions on the query.
1228
+	 * @param null  $columns_to_select      If left null, then an array of
1229
+	 *                                      EE_Base_Class objects is returned,
1230
+	 *                                      otherwise you can indicate just the
1231
+	 *                                      columns you want returned.
1232
+	 * @return EE_Base_Class[]|array
1233
+	 * @throws \EE_Error
1234
+	 */
1235
+	public function previous_x(
1236
+		$current_field_value,
1237
+		$field_to_order_by = null,
1238
+		$limit = 1,
1239
+		$query_params = array(),
1240
+		$columns_to_select = null
1241
+	) {
1242
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1243
+			$columns_to_select);
1244
+	}
1245
+
1246
+
1247
+
1248
+	/**
1249
+	 * Returns the next item in sequence from the given value as found in the
1250
+	 * database matching the given query conditions.
1251
+	 *
1252
+	 * @param mixed $current_field_value    Value used for the reference point.
1253
+	 * @param null  $field_to_order_by      What field is used for the
1254
+	 *                                      reference point.
1255
+	 * @param array $query_params           Extra conditions on the query.
1256
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1257
+	 *                                      object is returned, otherwise you
1258
+	 *                                      can indicate just the columns you
1259
+	 *                                      want and a single array indexed by
1260
+	 *                                      the columns will be returned.
1261
+	 * @return EE_Base_Class|null|array()
1262
+	 * @throws \EE_Error
1263
+	 */
1264
+	public function next(
1265
+		$current_field_value,
1266
+		$field_to_order_by = null,
1267
+		$query_params = array(),
1268
+		$columns_to_select = null
1269
+	) {
1270
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1271
+			$columns_to_select);
1272
+		return empty($results) ? null : reset($results);
1273
+	}
1274
+
1275
+
1276
+
1277
+	/**
1278
+	 * Returns the previous item in sequence from the given value as found in
1279
+	 * the database matching the given query conditions.
1280
+	 *
1281
+	 * @param mixed $current_field_value    Value used for the reference point.
1282
+	 * @param null  $field_to_order_by      What field is used for the
1283
+	 *                                      reference point.
1284
+	 * @param array $query_params           Extra conditions on the query.
1285
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1286
+	 *                                      object is returned, otherwise you
1287
+	 *                                      can indicate just the columns you
1288
+	 *                                      want and a single array indexed by
1289
+	 *                                      the columns will be returned.
1290
+	 * @return EE_Base_Class|null|array()
1291
+	 * @throws EE_Error
1292
+	 */
1293
+	public function previous(
1294
+		$current_field_value,
1295
+		$field_to_order_by = null,
1296
+		$query_params = array(),
1297
+		$columns_to_select = null
1298
+	) {
1299
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1300
+			$columns_to_select);
1301
+		return empty($results) ? null : reset($results);
1302
+	}
1303
+
1304
+
1305
+
1306
+	/**
1307
+	 * Returns the a consecutive number of items in sequence from the given
1308
+	 * value as found in the database matching the given query conditions.
1309
+	 *
1310
+	 * @param mixed  $current_field_value   Value used for the reference point.
1311
+	 * @param string $operand               What operand is used for the sequence.
1312
+	 * @param string $field_to_order_by     What field is used for the reference point.
1313
+	 * @param int    $limit                 How many to return.
1314
+	 * @param array  $query_params          Extra conditions on the query.
1315
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1316
+	 *                                      otherwise you can indicate just the columns you want returned.
1317
+	 * @return EE_Base_Class[]|array
1318
+	 * @throws EE_Error
1319
+	 */
1320
+	protected function _get_consecutive(
1321
+		$current_field_value,
1322
+		$operand = '>',
1323
+		$field_to_order_by = null,
1324
+		$limit = 1,
1325
+		$query_params = array(),
1326
+		$columns_to_select = null
1327
+	) {
1328
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1329
+		if (empty($field_to_order_by)) {
1330
+			if ($this->has_primary_key_field()) {
1331
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1332
+			} else {
1333
+				if (WP_DEBUG) {
1334
+					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).',
1335
+						'event_espresso'));
1336
+				}
1337
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1338
+				return array();
1339
+			}
1340
+		}
1341
+		if ( ! is_array($query_params)) {
1342
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1343
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1344
+					gettype($query_params)), '4.6.0');
1345
+			$query_params = array();
1346
+		}
1347
+		//let's add the where query param for consecutive look up.
1348
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1349
+		$query_params['limit'] = $limit;
1350
+		//set direction
1351
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1352
+		$query_params['order_by'] = $operand === '>'
1353
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1354
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1355
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1356
+		if (empty($columns_to_select)) {
1357
+			return $this->get_all($query_params);
1358
+		} else {
1359
+			//getting just the fields
1360
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1361
+		}
1362
+	}
1363
+
1364
+
1365
+
1366
+	/**
1367
+	 * This sets the _timezone property after model object has been instantiated.
1368
+	 *
1369
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1370
+	 */
1371
+	public function set_timezone($timezone)
1372
+	{
1373
+		if ($timezone !== null) {
1374
+			$this->_timezone = $timezone;
1375
+		}
1376
+		//note we need to loop through relations and set the timezone on those objects as well.
1377
+		foreach ($this->_model_relations as $relation) {
1378
+			$relation->set_timezone($timezone);
1379
+		}
1380
+		//and finally we do the same for any datetime fields
1381
+		foreach ($this->_fields as $field) {
1382
+			if ($field instanceof EE_Datetime_Field) {
1383
+				$field->set_timezone($timezone);
1384
+			}
1385
+		}
1386
+	}
1387
+
1388
+
1389
+
1390
+	/**
1391
+	 * This just returns whatever is set for the current timezone.
1392
+	 *
1393
+	 * @access public
1394
+	 * @return string
1395
+	 */
1396
+	public function get_timezone()
1397
+	{
1398
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1399
+		if (empty($this->_timezone)) {
1400
+			foreach ($this->_fields as $field) {
1401
+				if ($field instanceof EE_Datetime_Field) {
1402
+					$this->set_timezone($field->get_timezone());
1403
+					break;
1404
+				}
1405
+			}
1406
+		}
1407
+		//if timezone STILL empty then return the default timezone for the site.
1408
+		if (empty($this->_timezone)) {
1409
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1410
+		}
1411
+		return $this->_timezone;
1412
+	}
1413
+
1414
+
1415
+
1416
+	/**
1417
+	 * This returns the date formats set for the given field name and also ensures that
1418
+	 * $this->_timezone property is set correctly.
1419
+	 *
1420
+	 * @since 4.6.x
1421
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1422
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1423
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1424
+	 * @return array formats in an array with the date format first, and the time format last.
1425
+	 */
1426
+	public function get_formats_for($field_name, $pretty = false)
1427
+	{
1428
+		$field_settings = $this->field_settings_for($field_name);
1429
+		//if not a valid EE_Datetime_Field then throw error
1430
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1431
+			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.',
1432
+				'event_espresso'), $field_name));
1433
+		}
1434
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1435
+		//the field.
1436
+		$this->_timezone = $field_settings->get_timezone();
1437
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1438
+	}
1439
+
1440
+
1441
+
1442
+	/**
1443
+	 * This returns the current time in a format setup for a query on this model.
1444
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1445
+	 * it will return:
1446
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1447
+	 *  NOW
1448
+	 *  - or a unix timestamp (equivalent to time())
1449
+	 *
1450
+	 * @since 4.6.x
1451
+	 * @param string $field_name       The field the current time is needed for.
1452
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1453
+	 *                                 formatted string matching the set format for the field in the set timezone will
1454
+	 *                                 be returned.
1455
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1456
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1457
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1458
+	 *                                 exception is triggered.
1459
+	 */
1460
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1461
+	{
1462
+		$formats = $this->get_formats_for($field_name);
1463
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1464
+		if ($timestamp) {
1465
+			return $DateTime->format('U');
1466
+		}
1467
+		//not returning timestamp, so return formatted string in timezone.
1468
+		switch ($what) {
1469
+			case 'time' :
1470
+				return $DateTime->format($formats[1]);
1471
+				break;
1472
+			case 'date' :
1473
+				return $DateTime->format($formats[0]);
1474
+				break;
1475
+			default :
1476
+				return $DateTime->format(implode(' ', $formats));
1477
+				break;
1478
+		}
1479
+	}
1480
+
1481
+
1482
+
1483
+	/**
1484
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1485
+	 * for the model are.  Returns a DateTime object.
1486
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1487
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1488
+	 * ignored.
1489
+	 *
1490
+	 * @param string $field_name      The field being setup.
1491
+	 * @param string $timestring      The date time string being used.
1492
+	 * @param string $incoming_format The format for the time string.
1493
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1494
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1495
+	 *                                format is
1496
+	 *                                'U', this is ignored.
1497
+	 * @return DateTime
1498
+	 * @throws \EE_Error
1499
+	 */
1500
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1501
+	{
1502
+		//just using this to ensure the timezone is set correctly internally
1503
+		$this->get_formats_for($field_name);
1504
+		//load EEH_DTT_Helper
1505
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1506
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1507
+		return $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1508
+	}
1509
+
1510
+
1511
+
1512
+	/**
1513
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1514
+	 *
1515
+	 * @return EE_Table_Base[]
1516
+	 */
1517
+	public function get_tables()
1518
+	{
1519
+		return $this->_tables;
1520
+	}
1521
+
1522
+
1523
+
1524
+	/**
1525
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1526
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1527
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1528
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1529
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1530
+	 * model object with EVT_ID = 1
1531
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1532
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1533
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1534
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1535
+	 * are not specified)
1536
+	 *
1537
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1538
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1539
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1540
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1541
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1542
+	 *                                         ID=34, we'd use this method as follows:
1543
+	 *                                         EEM_Transaction::instance()->update(
1544
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1545
+	 *                                         array(array('TXN_ID'=>34)));
1546
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1547
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1548
+	 *                                         consider updating Question's QST_admin_label field is of type
1549
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1550
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1551
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1552
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1553
+	 *                                         TRUE, it is assumed that you've already called
1554
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1555
+	 *                                         malicious javascript. However, if
1556
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1557
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it, and every other field, before insertion. We provide this parameter because model objects perform their prepare_for_set
1558
+	 *                                         function on all their values, and so don't need to be called again (and in many cases, shouldn't be called again. Eg: if we escape HTML characters in the prepare_for_set method...)
1559
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1560
+	 *                                         in this model's entity map according to $fields_n_values that match
1561
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1562
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1563
+	 *                                         could get out-of-sync with the database
1564
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1565
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was bad)
1566
+	 * @throws \EE_Error
1567
+	 */
1568
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1569
+	{
1570
+		if ( ! is_array($query_params)) {
1571
+			EE_Error::doing_it_wrong('EEM_Base::update',
1572
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1573
+					gettype($query_params)), '4.6.0');
1574
+			$query_params = array();
1575
+		}
1576
+		/**
1577
+		 * Action called before a model update call has been made.
1578
+		 *
1579
+		 * @param EEM_Base $model
1580
+		 * @param array    $fields_n_values the updated fields and their new values
1581
+		 * @param array    $query_params    @see EEM_Base::get_all()
1582
+		 */
1583
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1584
+		/**
1585
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1586
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1587
+		 *
1588
+		 * @param array    $fields_n_values fields and their new values
1589
+		 * @param EEM_Base $model           the model being queried
1590
+		 * @param array    $query_params    see EEM_Base::get_all()
1591
+		 */
1592
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1593
+			$query_params);
1594
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1595
+		//to do that, for each table, verify that it's PK isn't null.
1596
+		$tables = $this->get_tables();
1597
+		//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
1598
+		//NOTE: we should make this code more efficient by NOT querying twice
1599
+		//before the real update, but that needs to first go through ALPHA testing
1600
+		//as it's dangerous. says Mike August 8 2014
1601
+		//we want to make sure the default_where strategy is ignored
1602
+		$this->_ignore_where_strategy = true;
1603
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1604
+		foreach ($wpdb_select_results as $wpdb_result) {
1605
+			// type cast stdClass as array
1606
+			$wpdb_result = (array)$wpdb_result;
1607
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1608
+			if ($this->has_primary_key_field()) {
1609
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1610
+			} else {
1611
+				//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)
1612
+				$main_table_pk_value = null;
1613
+			}
1614
+			//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
1615
+			//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
1616
+			if (count($tables) > 1) {
1617
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1618
+				//in that table, and so we'll want to insert one
1619
+				foreach ($tables as $table_obj) {
1620
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1621
+					//if there is no private key for this table on the results, it means there's no entry
1622
+					//in this table, right? so insert a row in the current table, using any fields available
1623
+					if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1624
+							&& $wpdb_result[$this_table_pk_column])
1625
+					) {
1626
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1627
+							$main_table_pk_value);
1628
+						//if we died here, report the error
1629
+						if ( ! $success) {
1630
+							return false;
1631
+						}
1632
+					}
1633
+				}
1634
+			}
1635
+			//				//and now check that if we have cached any models by that ID on the model, that
1636
+			//				//they also get updated properly
1637
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1638
+			//				if( $model_object ){
1639
+			//					foreach( $fields_n_values as $field => $value ){
1640
+			//						$model_object->set($field, $value);
1641
+			//let's make sure default_where strategy is followed now
1642
+			$this->_ignore_where_strategy = false;
1643
+		}
1644
+		//if we want to keep model objects in sync, AND
1645
+		//if this wasn't called from a model object (to update itself)
1646
+		//then we want to make sure we keep all the existing
1647
+		//model objects in sync with the db
1648
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1649
+			if ($this->has_primary_key_field()) {
1650
+				$model_objs_affected_ids = $this->get_col($query_params);
1651
+			} else {
1652
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1653
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1654
+				$model_objs_affected_ids = array();
1655
+				foreach ($models_affected_key_columns as $row) {
1656
+					$combined_index_key = $this->get_index_primary_key_string($row);
1657
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1658
+				}
1659
+			}
1660
+			if ( ! $model_objs_affected_ids) {
1661
+				//wait wait wait- if nothing was affected let's stop here
1662
+				return 0;
1663
+			}
1664
+			foreach ($model_objs_affected_ids as $id) {
1665
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1666
+				if ($model_obj_in_entity_map) {
1667
+					foreach ($fields_n_values as $field => $new_value) {
1668
+						$model_obj_in_entity_map->set($field, $new_value);
1669
+					}
1670
+				}
1671
+			}
1672
+			//if there is a primary key on this model, we can now do a slight optimization
1673
+			if ($this->has_primary_key_field()) {
1674
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1675
+				$query_params = array(
1676
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1677
+					'limit'                    => count($model_objs_affected_ids),
1678
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1679
+				);
1680
+			}
1681
+		}
1682
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1683
+		$SQL = "UPDATE "
1684
+			   . $model_query_info->get_full_join_sql()
1685
+			   . " SET "
1686
+			   . $this->_construct_update_sql($fields_n_values)
1687
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1688
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1689
+		/**
1690
+		 * Action called after a model update call has been made.
1691
+		 *
1692
+		 * @param EEM_Base $model
1693
+		 * @param array    $fields_n_values the updated fields and their new values
1694
+		 * @param array    $query_params    @see EEM_Base::get_all()
1695
+		 * @param int      $rows_affected
1696
+		 */
1697
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1698
+		return $rows_affected;//how many supposedly got updated
1699
+	}
1700
+
1701
+
1702
+
1703
+	/**
1704
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1705
+	 * are teh values of the field specified (or by default the primary key field)
1706
+	 * that matched the query params. Note that you should pass the name of the
1707
+	 * model FIELD, not the database table's column name.
1708
+	 *
1709
+	 * @param array  $query_params @see EEM_Base::get_all()
1710
+	 * @param string $field_to_select
1711
+	 * @return array just like $wpdb->get_col()
1712
+	 * @throws \EE_Error
1713
+	 */
1714
+	public function get_col($query_params = array(), $field_to_select = null)
1715
+	{
1716
+		if ($field_to_select) {
1717
+			$field = $this->field_settings_for($field_to_select);
1718
+		} elseif ($this->has_primary_key_field()) {
1719
+			$field = $this->get_primary_key_field();
1720
+		} else {
1721
+			//no primary key, just grab the first column
1722
+			$field = reset($this->field_settings());
1723
+		}
1724
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1725
+		$select_expressions = $field->get_qualified_column();
1726
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1727
+		return $this->_do_wpdb_query('get_col', array($SQL));
1728
+	}
1729
+
1730
+
1731
+
1732
+	/**
1733
+	 * Returns a single column value for a single row from the database
1734
+	 *
1735
+	 * @param array  $query_params    @see EEM_Base::get_all()
1736
+	 * @param string $field_to_select @see EEM_Base::get_col()
1737
+	 * @return string
1738
+	 * @throws \EE_Error
1739
+	 */
1740
+	public function get_var($query_params = array(), $field_to_select = null)
1741
+	{
1742
+		$query_params['limit'] = 1;
1743
+		$col = $this->get_col($query_params, $field_to_select);
1744
+		if ( ! empty($col)) {
1745
+			return reset($col);
1746
+		} else {
1747
+			return null;
1748
+		}
1749
+	}
1750
+
1751
+
1752
+
1753
+	/**
1754
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1755
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1756
+	 * injection, but currently no further filtering is done
1757
+	 *
1758
+	 * @global      $wpdb
1759
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1760
+	 *                               be updated to in the DB
1761
+	 * @return string of SQL
1762
+	 * @throws \EE_Error
1763
+	 */
1764
+	public function _construct_update_sql($fields_n_values)
1765
+	{
1766
+		/** @type WPDB $wpdb */
1767
+		global $wpdb;
1768
+		$cols_n_values = array();
1769
+		foreach ($fields_n_values as $field_name => $value) {
1770
+			$field_obj = $this->field_settings_for($field_name);
1771
+			//if the value is NULL, we want to assign the value to that.
1772
+			//wpdb->prepare doesn't really handle that properly
1773
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1774
+			$value_sql = $prepared_value === null ? 'NULL'
1775
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1776
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1777
+		}
1778
+		return implode(",", $cols_n_values);
1779
+	}
1780
+
1781
+
1782
+
1783
+	/**
1784
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1785
+	 * Performs a HARD delete, meaning the database row should always be removed,
1786
+	 * not just have a flag field on it switched
1787
+	 * Wrapper for EEM_Base::delete_permanently()
1788
+	 *
1789
+	 * @param mixed $id
1790
+	 * @return boolean whether the row got deleted or not
1791
+	 * @throws \EE_Error
1792
+	 */
1793
+	public function delete_permanently_by_ID($id)
1794
+	{
1795
+		return $this->delete_permanently(
1796
+			array(
1797
+				array($this->get_primary_key_field()->get_name() => $id),
1798
+				'limit' => 1,
1799
+			)
1800
+		);
1801
+	}
1802
+
1803
+
1804
+
1805
+	/**
1806
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1807
+	 * Wrapper for EEM_Base::delete()
1808
+	 *
1809
+	 * @param mixed $id
1810
+	 * @return boolean whether the row got deleted or not
1811
+	 * @throws \EE_Error
1812
+	 */
1813
+	public function delete_by_ID($id)
1814
+	{
1815
+		return $this->delete(
1816
+			array(
1817
+				array($this->get_primary_key_field()->get_name() => $id),
1818
+				'limit' => 1,
1819
+			)
1820
+		);
1821
+	}
1822
+
1823
+
1824
+
1825
+	/**
1826
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1827
+	 * meaning if the model has a field that indicates its been "trashed" or
1828
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1829
+	 *
1830
+	 * @see EEM_Base::delete_permanently
1831
+	 * @param array   $query_params
1832
+	 * @param boolean $allow_blocking
1833
+	 * @return int how many rows got deleted
1834
+	 * @throws \EE_Error
1835
+	 */
1836
+	public function delete($query_params, $allow_blocking = true)
1837
+	{
1838
+		return $this->delete_permanently($query_params, $allow_blocking);
1839
+	}
1840
+
1841
+
1842
+
1843
+	/**
1844
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1845
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1846
+	 * as archived, not actually deleted
1847
+	 *
1848
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1849
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1850
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1851
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1852
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1853
+	 *                                DB
1854
+	 * @return int how many rows got deleted
1855
+	 * @throws \EE_Error
1856
+	 */
1857
+	public function delete_permanently($query_params, $allow_blocking = true)
1858
+	{
1859
+		/**
1860
+		 * Action called just before performing a real deletion query. You can use the
1861
+		 * model and its $query_params to find exactly which items will be deleted
1862
+		 *
1863
+		 * @param EEM_Base $model
1864
+		 * @param array    $query_params   @see EEM_Base::get_all()
1865
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1866
+		 *                                 to block (prevent) this deletion
1867
+		 */
1868
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1869
+		//some MySQL databases may be running safe mode, which may restrict
1870
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1871
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1872
+		//to delete them
1873
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1874
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1875
+		if ($deletion_where) {
1876
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1877
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1878
+			$table_aliases = array_keys($this->_tables);
1879
+			$SQL = "DELETE "
1880
+				   . implode(", ", $table_aliases)
1881
+				   . " FROM "
1882
+				   . $model_query_info->get_full_join_sql()
1883
+				   . " WHERE "
1884
+				   . $deletion_where;
1885
+			//		/echo "delete sql:$SQL";
1886
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1887
+		} else {
1888
+			$rows_deleted = 0;
1889
+		}
1890
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1891
+		if ($this->has_primary_key_field()) {
1892
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1893
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1894
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1895
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1896
+				}
1897
+			}
1898
+		}
1899
+		/**
1900
+		 * Action called just after performing a real deletion query. Although at this point the
1901
+		 * items should have been deleted
1902
+		 *
1903
+		 * @param EEM_Base $model
1904
+		 * @param array    $query_params @see EEM_Base::get_all()
1905
+		 * @param int      $rows_deleted
1906
+		 */
1907
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1908
+		return $rows_deleted;//how many supposedly got deleted
1909
+	}
1910
+
1911
+
1912
+
1913
+	/**
1914
+	 * Checks all the relations that throw error messages when there are blocking related objects
1915
+	 * for related model objects. If there are any related model objects on those relations,
1916
+	 * adds an EE_Error, and return true
1917
+	 *
1918
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1919
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1920
+	 *                                                 should be ignored when determining whether there are related
1921
+	 *                                                 model objects which block this model object's deletion. Useful
1922
+	 *                                                 if you know A is related to B and are considering deleting A,
1923
+	 *                                                 but want to see if A has any other objects blocking its deletion
1924
+	 *                                                 before removing the relation between A and B
1925
+	 * @return boolean
1926
+	 * @throws \EE_Error
1927
+	 */
1928
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1929
+	{
1930
+		//first, if $ignore_this_model_obj was supplied, get its model
1931
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1932
+			$ignored_model = $ignore_this_model_obj->get_model();
1933
+		} else {
1934
+			$ignored_model = null;
1935
+		}
1936
+		//now check all the relations of $this_model_obj_or_id and see if there
1937
+		//are any related model objects blocking it?
1938
+		$is_blocked = false;
1939
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1940
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1941
+				//if $ignore_this_model_obj was supplied, then for the query
1942
+				//on that model needs to be told to ignore $ignore_this_model_obj
1943
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1944
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1945
+						array(
1946
+							$ignored_model->get_primary_key_field()->get_name() => array(
1947
+								'!=',
1948
+								$ignore_this_model_obj->ID(),
1949
+							),
1950
+						),
1951
+					));
1952
+				} else {
1953
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1954
+				}
1955
+				if ($related_model_objects) {
1956
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1957
+					$is_blocked = true;
1958
+				}
1959
+			}
1960
+		}
1961
+		return $is_blocked;
1962
+	}
1963
+
1964
+
1965
+
1966
+	/**
1967
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1968
+	 * well.
1969
+	 *
1970
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1971
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1972
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
1973
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
1974
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
1975
+	 *                                      easily corrupt your DB
1976
+	 * @throws EE_Error
1977
+	 * @return string    everything that comes after the WHERE statement.
1978
+	 */
1979
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
1980
+	{
1981
+		if ($this->has_primary_key_field()) {
1982
+			$primary_table = $this->_get_main_table();
1983
+			$other_tables = $this->_get_other_tables();
1984
+			$deletes = $query = array();
1985
+			foreach ($objects_for_deletion as $delete_object) {
1986
+				//before we mark this object for deletion,
1987
+				//make sure there's no related objects blocking its deletion (if we're checking)
1988
+				if (
1989
+					$allow_blocking
1990
+					&& $this->delete_is_blocked_by_related_models(
1991
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
1992
+					)
1993
+				) {
1994
+					continue;
1995
+				}
1996
+				//primary table deletes
1997
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
1998
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
1999
+				}
2000
+				//other tables
2001
+				if ( ! empty($other_tables)) {
2002
+					foreach ($other_tables as $ot) {
2003
+						//first check if we've got the foreign key column here.
2004
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2005
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2006
+						}
2007
+						// wait! it's entirely possible that we'll have a the primary key
2008
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2009
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2010
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2011
+						}
2012
+						// finally, it is possible that the fk for this table is found
2013
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2014
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2015
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2016
+						}
2017
+					}
2018
+				}
2019
+			}
2020
+			//we should have deletes now, so let's just go through and setup the where statement
2021
+			foreach ($deletes as $column => $values) {
2022
+				//make sure we have unique $values;
2023
+				$values = array_unique($values);
2024
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2025
+			}
2026
+			return ! empty($query) ? implode(' AND ', $query) : '';
2027
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2028
+			$ways_to_identify_a_row = array();
2029
+			$fields = $this->get_combined_primary_key_fields();
2030
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2031
+			foreach ($objects_for_deletion as $delete_object) {
2032
+				$values_for_each_cpk_for_a_row = array();
2033
+				foreach ($fields as $cpk_field) {
2034
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2035
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2036
+														   . "="
2037
+														   . $delete_object[$cpk_field->get_qualified_column()];
2038
+					}
2039
+				}
2040
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2041
+			}
2042
+			return implode(" OR ", $ways_to_identify_a_row);
2043
+		} else {
2044
+			//so there's no primary key and no combined key...
2045
+			//sorry, can't help you
2046
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2047
+				"event_espresso"), get_class($this)));
2048
+		}
2049
+	}
2050
+
2051
+
2052
+
2053
+	/**
2054
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2055
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2056
+	 * column
2057
+	 *
2058
+	 * @param array  $query_params   like EEM_Base::get_all's
2059
+	 * @param string $field_to_count field on model to count by (not column name)
2060
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2061
+	 *                               that by the setting $distinct to TRUE;
2062
+	 * @return int
2063
+	 * @throws \EE_Error
2064
+	 */
2065
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2066
+	{
2067
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2068
+		if ($field_to_count) {
2069
+			$field_obj = $this->field_settings_for($field_to_count);
2070
+			$column_to_count = $field_obj->get_qualified_column();
2071
+		} elseif ($this->has_primary_key_field()) {
2072
+			$pk_field_obj = $this->get_primary_key_field();
2073
+			$column_to_count = $pk_field_obj->get_qualified_column();
2074
+		} else {
2075
+			//there's no primary key
2076
+			//if we're counting distinct items, and there's no primary key,
2077
+			//we need to list out the columns for distinction;
2078
+			//otherwise we can just use star
2079
+			if ($distinct) {
2080
+				$columns_to_use = array();
2081
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2082
+					$columns_to_use[] = $field_obj->get_qualified_column();
2083
+				}
2084
+				$column_to_count = implode(',', $columns_to_use);
2085
+			} else {
2086
+				$column_to_count = '*';
2087
+			}
2088
+		}
2089
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2090
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2091
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2092
+	}
2093
+
2094
+
2095
+
2096
+	/**
2097
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2098
+	 *
2099
+	 * @param array  $query_params like EEM_Base::get_all
2100
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2101
+	 * @return float
2102
+	 * @throws \EE_Error
2103
+	 */
2104
+	public function sum($query_params, $field_to_sum = null)
2105
+	{
2106
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2107
+		if ($field_to_sum) {
2108
+			$field_obj = $this->field_settings_for($field_to_sum);
2109
+		} else {
2110
+			$field_obj = $this->get_primary_key_field();
2111
+		}
2112
+		$column_to_count = $field_obj->get_qualified_column();
2113
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2114
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2115
+		$data_type = $field_obj->get_wpdb_data_type();
2116
+		if ($data_type === '%d' || $data_type === '%s') {
2117
+			return (float)$return_value;
2118
+		} else {//must be %f
2119
+			return (float)$return_value;
2120
+		}
2121
+	}
2122
+
2123
+
2124
+
2125
+	/**
2126
+	 * Just calls the specified method on $wpdb with the given arguments
2127
+	 * Consolidates a little extra error handling code
2128
+	 *
2129
+	 * @param string $wpdb_method
2130
+	 * @param array  $arguments_to_provide
2131
+	 * @throws EE_Error
2132
+	 * @global wpdb  $wpdb
2133
+	 * @return mixed
2134
+	 */
2135
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2136
+	{
2137
+		//if we're in maintenance mode level 2, DON'T run any queries
2138
+		//because level 2 indicates the database needs updating and
2139
+		//is probably out of sync with the code
2140
+		if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2141
+			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.",
2142
+				"event_espresso")));
2143
+		}
2144
+		/** @type WPDB $wpdb */
2145
+		global $wpdb;
2146
+		if ( ! method_exists($wpdb, $wpdb_method)) {
2147
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2148
+				'event_espresso'), $wpdb_method));
2149
+		}
2150
+		if (WP_DEBUG) {
2151
+			$old_show_errors_value = $wpdb->show_errors;
2152
+			$wpdb->show_errors(false);
2153
+		}
2154
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2155
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2156
+		if (WP_DEBUG) {
2157
+			$wpdb->show_errors($old_show_errors_value);
2158
+			if ( ! empty($wpdb->last_error)) {
2159
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2160
+			} elseif ($result === false) {
2161
+				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"',
2162
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2163
+			}
2164
+		} elseif ($result === false) {
2165
+			EE_Error::add_error(
2166
+				sprintf(
2167
+					__('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"',
2168
+						'event_espresso'),
2169
+					$wpdb_method,
2170
+					var_export($arguments_to_provide, true),
2171
+					$wpdb->last_error
2172
+				),
2173
+				__FILE__,
2174
+				__FUNCTION__,
2175
+				__LINE__
2176
+			);
2177
+		}
2178
+		return $result;
2179
+	}
2180
+
2181
+
2182
+
2183
+	/**
2184
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2185
+	 * and if there's an error tries to verify the DB is correct. Uses
2186
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2187
+	 * we should try to fix the EE core db, the addons, or just give up
2188
+	 *
2189
+	 * @param string $wpdb_method
2190
+	 * @param array  $arguments_to_provide
2191
+	 * @return mixed
2192
+	 */
2193
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2194
+	{
2195
+		/** @type WPDB $wpdb */
2196
+		global $wpdb;
2197
+		$wpdb->last_error = null;
2198
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2199
+		// was there an error running the query? but we don't care on new activations
2200
+		// (we're going to setup the DB anyway on new activations)
2201
+		if (($result === false || ! empty($wpdb->last_error))
2202
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2203
+		) {
2204
+			switch (EEM_Base::$_db_verification_level) {
2205
+				case EEM_Base::db_verified_none :
2206
+					// let's double-check core's DB
2207
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2208
+					break;
2209
+				case EEM_Base::db_verified_core :
2210
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2211
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2212
+					break;
2213
+				case EEM_Base::db_verified_addons :
2214
+					// ummmm... you in trouble
2215
+					return $result;
2216
+					break;
2217
+			}
2218
+			if ( ! empty($error_message)) {
2219
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2220
+				trigger_error($error_message);
2221
+			}
2222
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2223
+		}
2224
+		return $result;
2225
+	}
2226
+
2227
+
2228
+
2229
+	/**
2230
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2231
+	 * EEM_Base::$_db_verification_level
2232
+	 *
2233
+	 * @param string $wpdb_method
2234
+	 * @param array  $arguments_to_provide
2235
+	 * @return string
2236
+	 */
2237
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2238
+	{
2239
+		/** @type WPDB $wpdb */
2240
+		global $wpdb;
2241
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2242
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2243
+		$error_message = sprintf(
2244
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2245
+				'event_espresso'),
2246
+			$wpdb->last_error,
2247
+			$wpdb_method,
2248
+			wp_json_encode($arguments_to_provide)
2249
+		);
2250
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2251
+		return $error_message;
2252
+	}
2253
+
2254
+
2255
+
2256
+	/**
2257
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2258
+	 * EEM_Base::$_db_verification_level
2259
+	 *
2260
+	 * @param $wpdb_method
2261
+	 * @param $arguments_to_provide
2262
+	 * @return string
2263
+	 */
2264
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2265
+	{
2266
+		/** @type WPDB $wpdb */
2267
+		global $wpdb;
2268
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2269
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2270
+		$error_message = sprintf(
2271
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2272
+				'event_espresso'),
2273
+			$wpdb->last_error,
2274
+			$wpdb_method,
2275
+			wp_json_encode($arguments_to_provide)
2276
+		);
2277
+		EE_System::instance()->initialize_addons();
2278
+		return $error_message;
2279
+	}
2280
+
2281
+
2282
+
2283
+	/**
2284
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2285
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2286
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2287
+	 * ..."
2288
+	 *
2289
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2290
+	 * @return string
2291
+	 */
2292
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2293
+	{
2294
+		return " FROM " . $model_query_info->get_full_join_sql() .
2295
+			   $model_query_info->get_where_sql() .
2296
+			   $model_query_info->get_group_by_sql() .
2297
+			   $model_query_info->get_having_sql() .
2298
+			   $model_query_info->get_order_by_sql() .
2299
+			   $model_query_info->get_limit_sql();
2300
+	}
2301
+
2302
+
2303
+
2304
+	/**
2305
+	 * Set to easily debug the next X queries ran from this model.
2306
+	 *
2307
+	 * @param int $count
2308
+	 */
2309
+	public function show_next_x_db_queries($count = 1)
2310
+	{
2311
+		$this->_show_next_x_db_queries = $count;
2312
+	}
2313
+
2314
+
2315
+
2316
+	/**
2317
+	 * @param $sql_query
2318
+	 */
2319
+	public function show_db_query_if_previously_requested($sql_query)
2320
+	{
2321
+		if ($this->_show_next_x_db_queries > 0) {
2322
+			echo $sql_query;
2323
+			$this->_show_next_x_db_queries--;
2324
+		}
2325
+	}
2326
+
2327
+
2328
+
2329
+	/**
2330
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2331
+	 * There are the 3 cases:
2332
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2333
+	 * $otherModelObject has no ID, it is first saved.
2334
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2335
+	 * has no ID, it is first saved.
2336
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2337
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2338
+	 * join table
2339
+	 *
2340
+	 * @param        EE_Base_Class                     /int $thisModelObject
2341
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2342
+	 * @param string $relationName                     , key in EEM_Base::_relations
2343
+	 *                                                 an attendee to a group, you also want to specify which role they
2344
+	 *                                                 will have in that group. So you would use this parameter to
2345
+	 *                                                 specify array('role-column-name'=>'role-id')
2346
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2347
+	 *                                                 to for relation to methods that allow you to further specify
2348
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2349
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2350
+	 *                                                 because these will be inserted in any new rows created as well.
2351
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2352
+	 * @throws \EE_Error
2353
+	 */
2354
+	public function add_relationship_to(
2355
+		$id_or_obj,
2356
+		$other_model_id_or_obj,
2357
+		$relationName,
2358
+		$extra_join_model_fields_n_values = array()
2359
+	) {
2360
+		$relation_obj = $this->related_settings_for($relationName);
2361
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2362
+	}
2363
+
2364
+
2365
+
2366
+	/**
2367
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2368
+	 * There are the 3 cases:
2369
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2370
+	 * error
2371
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2372
+	 * an error
2373
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2374
+	 *
2375
+	 * @param        EE_Base_Class /int $id_or_obj
2376
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2377
+	 * @param string $relationName key in EEM_Base::_relations
2378
+	 * @return boolean of success
2379
+	 * @throws \EE_Error
2380
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2381
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2382
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2383
+	 *                             because these will be inserted in any new rows created as well.
2384
+	 */
2385
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2386
+	{
2387
+		$relation_obj = $this->related_settings_for($relationName);
2388
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2389
+	}
2390
+
2391
+
2392
+
2393
+	/**
2394
+	 * @param mixed           $id_or_obj
2395
+	 * @param string          $relationName
2396
+	 * @param array           $where_query_params
2397
+	 * @param EE_Base_Class[] objects to which relations were removed
2398
+	 * @return \EE_Base_Class[]
2399
+	 * @throws \EE_Error
2400
+	 */
2401
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2402
+	{
2403
+		$relation_obj = $this->related_settings_for($relationName);
2404
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2405
+	}
2406
+
2407
+
2408
+
2409
+	/**
2410
+	 * Gets all the related items of the specified $model_name, using $query_params.
2411
+	 * Note: by default, we remove the "default query params"
2412
+	 * because we want to get even deleted items etc.
2413
+	 *
2414
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2415
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2416
+	 * @param array  $query_params like EEM_Base::get_all
2417
+	 * @return EE_Base_Class[]
2418
+	 * @throws \EE_Error
2419
+	 */
2420
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2421
+	{
2422
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2423
+		$relation_settings = $this->related_settings_for($model_name);
2424
+		return $relation_settings->get_all_related($model_obj, $query_params);
2425
+	}
2426
+
2427
+
2428
+
2429
+	/**
2430
+	 * Deletes all the model objects across the relation indicated by $model_name
2431
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2432
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2433
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2434
+	 *
2435
+	 * @param EE_Base_Class|int|string $id_or_obj
2436
+	 * @param string                   $model_name
2437
+	 * @param array                    $query_params
2438
+	 * @return int how many deleted
2439
+	 * @throws \EE_Error
2440
+	 */
2441
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2442
+	{
2443
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2444
+		$relation_settings = $this->related_settings_for($model_name);
2445
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2446
+	}
2447
+
2448
+
2449
+
2450
+	/**
2451
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2452
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2453
+	 * the model objects can't be hard deleted because of blocking related model objects,
2454
+	 * just does a soft-delete on them instead.
2455
+	 *
2456
+	 * @param EE_Base_Class|int|string $id_or_obj
2457
+	 * @param string                   $model_name
2458
+	 * @param array                    $query_params
2459
+	 * @return int how many deleted
2460
+	 * @throws \EE_Error
2461
+	 */
2462
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2463
+	{
2464
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2465
+		$relation_settings = $this->related_settings_for($model_name);
2466
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2467
+	}
2468
+
2469
+
2470
+
2471
+	/**
2472
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2473
+	 * unless otherwise specified in the $query_params
2474
+	 *
2475
+	 * @param        int             /EE_Base_Class $id_or_obj
2476
+	 * @param string $model_name     like 'Event', or 'Registration'
2477
+	 * @param array  $query_params   like EEM_Base::get_all's
2478
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2479
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2480
+	 *                               that by the setting $distinct to TRUE;
2481
+	 * @return int
2482
+	 * @throws \EE_Error
2483
+	 */
2484
+	public function count_related(
2485
+		$id_or_obj,
2486
+		$model_name,
2487
+		$query_params = array(),
2488
+		$field_to_count = null,
2489
+		$distinct = false
2490
+	) {
2491
+		$related_model = $this->get_related_model_obj($model_name);
2492
+		//we're just going to use the query params on the related model's normal get_all query,
2493
+		//except add a condition to say to match the current mod
2494
+		if ( ! isset($query_params['default_where_conditions'])) {
2495
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2496
+		}
2497
+		$this_model_name = $this->get_this_model_name();
2498
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2499
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2500
+		return $related_model->count($query_params, $field_to_count, $distinct);
2501
+	}
2502
+
2503
+
2504
+
2505
+	/**
2506
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2507
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2508
+	 *
2509
+	 * @param        int           /EE_Base_Class $id_or_obj
2510
+	 * @param string $model_name   like 'Event', or 'Registration'
2511
+	 * @param array  $query_params like EEM_Base::get_all's
2512
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2513
+	 * @return float
2514
+	 * @throws \EE_Error
2515
+	 */
2516
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2517
+	{
2518
+		$related_model = $this->get_related_model_obj($model_name);
2519
+		if ( ! is_array($query_params)) {
2520
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2521
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2522
+					gettype($query_params)), '4.6.0');
2523
+			$query_params = array();
2524
+		}
2525
+		//we're just going to use the query params on the related model's normal get_all query,
2526
+		//except add a condition to say to match the current mod
2527
+		if ( ! isset($query_params['default_where_conditions'])) {
2528
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2529
+		}
2530
+		$this_model_name = $this->get_this_model_name();
2531
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2532
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2533
+		return $related_model->sum($query_params, $field_to_sum);
2534
+	}
2535
+
2536
+
2537
+
2538
+	/**
2539
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2540
+	 * $modelObject
2541
+	 *
2542
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2543
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2544
+	 * @param array               $query_params     like EEM_Base::get_all's
2545
+	 * @return EE_Base_Class
2546
+	 * @throws \EE_Error
2547
+	 */
2548
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2549
+	{
2550
+		$query_params['limit'] = 1;
2551
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2552
+		if ($results) {
2553
+			return array_shift($results);
2554
+		} else {
2555
+			return null;
2556
+		}
2557
+	}
2558
+
2559
+
2560
+
2561
+	/**
2562
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2563
+	 *
2564
+	 * @return string
2565
+	 */
2566
+	public function get_this_model_name()
2567
+	{
2568
+		return str_replace("EEM_", "", get_class($this));
2569
+	}
2570
+
2571
+
2572
+
2573
+	/**
2574
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2575
+	 *
2576
+	 * @return EE_Any_Foreign_Model_Name_Field
2577
+	 * @throws EE_Error
2578
+	 */
2579
+	public function get_field_containing_related_model_name()
2580
+	{
2581
+		foreach ($this->field_settings(true) as $field) {
2582
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2583
+				$field_with_model_name = $field;
2584
+			}
2585
+		}
2586
+		if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2587
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2588
+				$this->get_this_model_name()));
2589
+		}
2590
+		return $field_with_model_name;
2591
+	}
2592
+
2593
+
2594
+
2595
+	/**
2596
+	 * Inserts a new entry into the database, for each table.
2597
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2598
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2599
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2600
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2601
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2602
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2603
+	 *
2604
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2605
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2606
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2607
+	 *                              of EEM_Base)
2608
+	 * @return int new primary key on main table that got inserted
2609
+	 * @throws EE_Error
2610
+	 */
2611
+	public function insert($field_n_values)
2612
+	{
2613
+		/**
2614
+		 * Filters the fields and their values before inserting an item using the models
2615
+		 *
2616
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2617
+		 * @param EEM_Base $model           the model used
2618
+		 */
2619
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2620
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2621
+			$main_table = $this->_get_main_table();
2622
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2623
+			if ($new_id !== false) {
2624
+				foreach ($this->_get_other_tables() as $other_table) {
2625
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2626
+				}
2627
+			}
2628
+			/**
2629
+			 * Done just after attempting to insert a new model object
2630
+			 *
2631
+			 * @param EEM_Base   $model           used
2632
+			 * @param array      $fields_n_values fields and their values
2633
+			 * @param int|string the              ID of the newly-inserted model object
2634
+			 */
2635
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2636
+			return $new_id;
2637
+		} else {
2638
+			return false;
2639
+		}
2640
+	}
2641
+
2642
+
2643
+
2644
+	/**
2645
+	 * Checks that the result would satisfy the unique indexes on this model
2646
+	 *
2647
+	 * @param array  $field_n_values
2648
+	 * @param string $action
2649
+	 * @return boolean
2650
+	 * @throws \EE_Error
2651
+	 */
2652
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2653
+	{
2654
+		foreach ($this->unique_indexes() as $index_name => $index) {
2655
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2656
+			if ($this->exists(array($uniqueness_where_params))) {
2657
+				EE_Error::add_error(
2658
+					sprintf(
2659
+						__(
2660
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2661
+							"event_espresso"
2662
+						),
2663
+						$action,
2664
+						$this->_get_class_name(),
2665
+						$index_name,
2666
+						implode(",", $index->field_names()),
2667
+						http_build_query($uniqueness_where_params)
2668
+					),
2669
+					__FILE__,
2670
+					__FUNCTION__,
2671
+					__LINE__
2672
+				);
2673
+				return false;
2674
+			}
2675
+		}
2676
+		return true;
2677
+	}
2678
+
2679
+
2680
+
2681
+	/**
2682
+	 * Checks the database for an item that conflicts (ie, if this item were
2683
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2684
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2685
+	 * can be either an EE_Base_Class or an array of fields n values
2686
+	 *
2687
+	 * @param EE_Base_Class|array $obj_or_fields_array
2688
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2689
+	 *                                                 when looking for conflicts
2690
+	 *                                                 (ie, if false, we ignore the model object's primary key
2691
+	 *                                                 when finding "conflicts". If true, it's also considered).
2692
+	 *                                                 Only works for INT primary key,
2693
+	 *                                                 STRING primary keys cannot be ignored
2694
+	 * @throws EE_Error
2695
+	 * @return EE_Base_Class|array
2696
+	 */
2697
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2698
+	{
2699
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2700
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2701
+		} elseif (is_array($obj_or_fields_array)) {
2702
+			$fields_n_values = $obj_or_fields_array;
2703
+		} else {
2704
+			throw new EE_Error(
2705
+				sprintf(
2706
+					__(
2707
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2708
+						"event_espresso"
2709
+					),
2710
+					get_class($this),
2711
+					$obj_or_fields_array
2712
+				)
2713
+			);
2714
+		}
2715
+		$query_params = array();
2716
+		if ($this->has_primary_key_field()
2717
+			&& ($include_primary_key
2718
+				|| $this->get_primary_key_field()
2719
+				   instanceof
2720
+				   EE_Primary_Key_String_Field)
2721
+			&& isset($fields_n_values[$this->primary_key_name()])
2722
+		) {
2723
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2724
+		}
2725
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2726
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2727
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2728
+		}
2729
+		//if there is nothing to base this search on, then we shouldn't find anything
2730
+		if (empty($query_params)) {
2731
+			return array();
2732
+		} else {
2733
+			return $this->get_one($query_params);
2734
+		}
2735
+	}
2736
+
2737
+
2738
+
2739
+	/**
2740
+	 * Like count, but is optimized and returns a boolean instead of an int
2741
+	 *
2742
+	 * @param array $query_params
2743
+	 * @return boolean
2744
+	 * @throws \EE_Error
2745
+	 */
2746
+	public function exists($query_params)
2747
+	{
2748
+		$query_params['limit'] = 1;
2749
+		return $this->count($query_params) > 0;
2750
+	}
2751
+
2752
+
2753
+
2754
+	/**
2755
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2756
+	 *
2757
+	 * @param int|string $id
2758
+	 * @return boolean
2759
+	 * @throws \EE_Error
2760
+	 */
2761
+	public function exists_by_ID($id)
2762
+	{
2763
+		return $this->exists(
2764
+			array(
2765
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2766
+				array(
2767
+					$this->primary_key_name() => $id
2768
+				)
2769
+			)
2770
+		);
2771
+	}
2772
+
2773
+
2774
+
2775
+	/**
2776
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2777
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2778
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2779
+	 * on the main table)
2780
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2781
+	 * cases where we want to call it directly rather than via insert().
2782
+	 *
2783
+	 * @access   protected
2784
+	 * @param EE_Table_Base $table
2785
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2786
+	 *                                       float
2787
+	 * @param int           $new_id          for now we assume only int keys
2788
+	 * @throws EE_Error
2789
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2790
+	 * @return int ID of new row inserted, or FALSE on failure
2791
+	 */
2792
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2793
+	{
2794
+		global $wpdb;
2795
+		$insertion_col_n_values = array();
2796
+		$format_for_insertion = array();
2797
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2798
+		foreach ($fields_on_table as $field_name => $field_obj) {
2799
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2800
+			if ($field_obj->is_auto_increment()) {
2801
+				continue;
2802
+			}
2803
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2804
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2805
+			if ($prepared_value !== null) {
2806
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2807
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2808
+			}
2809
+		}
2810
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2811
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2812
+			//so add the fk to the main table as a column
2813
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2814
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2815
+		}
2816
+		//insert the new entry
2817
+		$result = $this->_do_wpdb_query('insert',
2818
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2819
+		if ($result === false) {
2820
+			return false;
2821
+		}
2822
+		//ok, now what do we return for the ID of the newly-inserted thing?
2823
+		if ($this->has_primary_key_field()) {
2824
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2825
+				return $wpdb->insert_id;
2826
+			} else {
2827
+				//it's not an auto-increment primary key, so
2828
+				//it must have been supplied
2829
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2830
+			}
2831
+		} else {
2832
+			//we can't return a  primary key because there is none. instead return
2833
+			//a unique string indicating this model
2834
+			return $this->get_index_primary_key_string($fields_n_values);
2835
+		}
2836
+	}
2837
+
2838
+
2839
+
2840
+	/**
2841
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2842
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2843
+	 * and there is no default, we pass it along. WPDB will take care of it)
2844
+	 *
2845
+	 * @param EE_Model_Field_Base $field_obj
2846
+	 * @param array               $fields_n_values
2847
+	 * @return mixed string|int|float depending on what the table column will be expecting
2848
+	 * @throws \EE_Error
2849
+	 */
2850
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2851
+	{
2852
+		//if this field doesn't allow nullable, don't allow it
2853
+		if ( ! $field_obj->is_nullable()
2854
+			 && (
2855
+				 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2856
+		) {
2857
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2858
+		}
2859
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2860
+			: null;
2861
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2862
+	}
2863
+
2864
+
2865
+
2866
+	/**
2867
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2868
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2869
+	 * the field's prepare_for_set() method.
2870
+	 *
2871
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2872
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2873
+	 *                                   top of file)
2874
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2875
+	 *                                   $value is a custom selection
2876
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2877
+	 */
2878
+	private function _prepare_value_for_use_in_db($value, $field)
2879
+	{
2880
+		if ($field && $field instanceof EE_Model_Field_Base) {
2881
+			switch ($this->_values_already_prepared_by_model_object) {
2882
+				/** @noinspection PhpMissingBreakStatementInspection */
2883
+				case self::not_prepared_by_model_object:
2884
+					$value = $field->prepare_for_set($value);
2885
+				//purposefully left out "return"
2886
+				case self::prepared_by_model_object:
2887
+					$value = $field->prepare_for_use_in_db($value);
2888
+				case self::prepared_for_use_in_db:
2889
+					//leave the value alone
2890
+			}
2891
+			return $value;
2892
+		} else {
2893
+			return $value;
2894
+		}
2895
+	}
2896
+
2897
+
2898
+
2899
+	/**
2900
+	 * Returns the main table on this model
2901
+	 *
2902
+	 * @return EE_Primary_Table
2903
+	 * @throws EE_Error
2904
+	 */
2905
+	protected function _get_main_table()
2906
+	{
2907
+		foreach ($this->_tables as $table) {
2908
+			if ($table instanceof EE_Primary_Table) {
2909
+				return $table;
2910
+			}
2911
+		}
2912
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2913
+			'event_espresso'), get_class($this)));
2914
+	}
2915
+
2916
+
2917
+
2918
+	/**
2919
+	 * table
2920
+	 * returns EE_Primary_Table table name
2921
+	 *
2922
+	 * @return string
2923
+	 * @throws \EE_Error
2924
+	 */
2925
+	public function table()
2926
+	{
2927
+		return $this->_get_main_table()->get_table_name();
2928
+	}
2929
+
2930
+
2931
+
2932
+	/**
2933
+	 * table
2934
+	 * returns first EE_Secondary_Table table name
2935
+	 *
2936
+	 * @return string
2937
+	 */
2938
+	public function second_table()
2939
+	{
2940
+		// grab second table from tables array
2941
+		$second_table = end($this->_tables);
2942
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2943
+	}
2944
+
2945
+
2946
+
2947
+	/**
2948
+	 * get_table_obj_by_alias
2949
+	 * returns table name given it's alias
2950
+	 *
2951
+	 * @param string $table_alias
2952
+	 * @return EE_Primary_Table | EE_Secondary_Table
2953
+	 */
2954
+	public function get_table_obj_by_alias($table_alias = '')
2955
+	{
2956
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2957
+	}
2958
+
2959
+
2960
+
2961
+	/**
2962
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2963
+	 *
2964
+	 * @return EE_Secondary_Table[]
2965
+	 */
2966
+	protected function _get_other_tables()
2967
+	{
2968
+		$other_tables = array();
2969
+		foreach ($this->_tables as $table_alias => $table) {
2970
+			if ($table instanceof EE_Secondary_Table) {
2971
+				$other_tables[$table_alias] = $table;
2972
+			}
2973
+		}
2974
+		return $other_tables;
2975
+	}
2976
+
2977
+
2978
+
2979
+	/**
2980
+	 * Finds all the fields that correspond to the given table
2981
+	 *
2982
+	 * @param string $table_alias , array key in EEM_Base::_tables
2983
+	 * @return EE_Model_Field_Base[]
2984
+	 */
2985
+	public function _get_fields_for_table($table_alias)
2986
+	{
2987
+		return $this->_fields[$table_alias];
2988
+	}
2989
+
2990
+
2991
+
2992
+	/**
2993
+	 * Recurses through all the where parameters, and finds all the related models we'll need
2994
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
2995
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
2996
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
2997
+	 * related Registration, Transaction, and Payment models.
2998
+	 *
2999
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3000
+	 * @return EE_Model_Query_Info_Carrier
3001
+	 * @throws \EE_Error
3002
+	 */
3003
+	public function _extract_related_models_from_query($query_params)
3004
+	{
3005
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3006
+		if (array_key_exists(0, $query_params)) {
3007
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3008
+		}
3009
+		if (array_key_exists('group_by', $query_params)) {
3010
+			if (is_array($query_params['group_by'])) {
3011
+				$this->_extract_related_models_from_sub_params_array_values(
3012
+					$query_params['group_by'],
3013
+					$query_info_carrier,
3014
+					'group_by'
3015
+				);
3016
+			} elseif ( ! empty ($query_params['group_by'])) {
3017
+				$this->_extract_related_model_info_from_query_param(
3018
+					$query_params['group_by'],
3019
+					$query_info_carrier,
3020
+					'group_by'
3021
+				);
3022
+			}
3023
+		}
3024
+		if (array_key_exists('having', $query_params)) {
3025
+			$this->_extract_related_models_from_sub_params_array_keys(
3026
+				$query_params[0],
3027
+				$query_info_carrier,
3028
+				'having'
3029
+			);
3030
+		}
3031
+		if (array_key_exists('order_by', $query_params)) {
3032
+			if (is_array($query_params['order_by'])) {
3033
+				$this->_extract_related_models_from_sub_params_array_keys(
3034
+					$query_params['order_by'],
3035
+					$query_info_carrier,
3036
+					'order_by'
3037
+				);
3038
+			} elseif ( ! empty($query_params['order_by'])) {
3039
+				$this->_extract_related_model_info_from_query_param(
3040
+					$query_params['order_by'],
3041
+					$query_info_carrier,
3042
+					'order_by'
3043
+				);
3044
+			}
3045
+		}
3046
+		if (array_key_exists('force_join', $query_params)) {
3047
+			$this->_extract_related_models_from_sub_params_array_values(
3048
+				$query_params['force_join'],
3049
+				$query_info_carrier,
3050
+				'force_join'
3051
+			);
3052
+		}
3053
+		return $query_info_carrier;
3054
+	}
3055
+
3056
+
3057
+
3058
+	/**
3059
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3060
+	 *
3061
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3062
+	 *                                                      $query_params['having']
3063
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3064
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3065
+	 * @throws EE_Error
3066
+	 * @return \EE_Model_Query_Info_Carrier
3067
+	 */
3068
+	private function _extract_related_models_from_sub_params_array_keys(
3069
+		$sub_query_params,
3070
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3071
+		$query_param_type
3072
+	) {
3073
+		if ( ! empty($sub_query_params)) {
3074
+			$sub_query_params = (array)$sub_query_params;
3075
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3076
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3077
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3078
+					$query_param_type);
3079
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3080
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3081
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3082
+				//of array('Registration.TXN_ID'=>23)
3083
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3084
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3085
+					if ( ! is_array($possibly_array_of_params)) {
3086
+						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'))",
3087
+							"event_espresso"),
3088
+							$param, $possibly_array_of_params));
3089
+					} else {
3090
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3091
+							$model_query_info_carrier, $query_param_type);
3092
+					}
3093
+				} elseif ($query_param_type === 0 //ie WHERE
3094
+						  && is_array($possibly_array_of_params)
3095
+						  && isset($possibly_array_of_params[2])
3096
+						  && $possibly_array_of_params[2] == true
3097
+				) {
3098
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3099
+					//indicating that $possible_array_of_params[1] is actually a field name,
3100
+					//from which we should extract query parameters!
3101
+					if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3102
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3103
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3104
+					}
3105
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3106
+						$model_query_info_carrier, $query_param_type);
3107
+				}
3108
+			}
3109
+		}
3110
+		return $model_query_info_carrier;
3111
+	}
3112
+
3113
+
3114
+
3115
+	/**
3116
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3117
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3118
+	 *
3119
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3120
+	 *                                                      $query_params['having']
3121
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3122
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3123
+	 * @throws EE_Error
3124
+	 * @return \EE_Model_Query_Info_Carrier
3125
+	 */
3126
+	private function _extract_related_models_from_sub_params_array_values(
3127
+		$sub_query_params,
3128
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3129
+		$query_param_type
3130
+	) {
3131
+		if ( ! empty($sub_query_params)) {
3132
+			if ( ! is_array($sub_query_params)) {
3133
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3134
+					$sub_query_params));
3135
+			}
3136
+			foreach ($sub_query_params as $param) {
3137
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3138
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3139
+					$query_param_type);
3140
+			}
3141
+		}
3142
+		return $model_query_info_carrier;
3143
+	}
3144
+
3145
+
3146
+
3147
+	/**
3148
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3149
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3150
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3151
+	 * but use them in a different order. Eg, we need to know what models we are querying
3152
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3153
+	 * other models before we can finalize the where clause SQL.
3154
+	 *
3155
+	 * @param array $query_params
3156
+	 * @throws EE_Error
3157
+	 * @return EE_Model_Query_Info_Carrier
3158
+	 */
3159
+	public function _create_model_query_info_carrier($query_params)
3160
+	{
3161
+		if ( ! is_array($query_params)) {
3162
+			EE_Error::doing_it_wrong(
3163
+				'EEM_Base::_create_model_query_info_carrier',
3164
+				sprintf(
3165
+					__(
3166
+						'$query_params should be an array, you passed a variable of type %s',
3167
+						'event_espresso'
3168
+					),
3169
+					gettype($query_params)
3170
+				),
3171
+				'4.6.0'
3172
+			);
3173
+			$query_params = array();
3174
+		}
3175
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3176
+		//first check if we should alter the query to account for caps or not
3177
+		//because the caps might require us to do extra joins
3178
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3179
+			$query_params[0] = $where_query_params = array_replace_recursive(
3180
+				$where_query_params,
3181
+				$this->caps_where_conditions(
3182
+					$query_params['caps']
3183
+				)
3184
+			);
3185
+		}
3186
+		$query_object = $this->_extract_related_models_from_query($query_params);
3187
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3188
+		foreach ($where_query_params as $key => $value) {
3189
+			if (is_int($key)) {
3190
+				throw new EE_Error(
3191
+					sprintf(
3192
+						__(
3193
+							"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.",
3194
+							"event_espresso"
3195
+						),
3196
+						$key,
3197
+						var_export($value, true),
3198
+						var_export($query_params, true),
3199
+						get_class($this)
3200
+					)
3201
+				);
3202
+			}
3203
+		}
3204
+		if (
3205
+			array_key_exists('default_where_conditions', $query_params)
3206
+			&& ! empty($query_params['default_where_conditions'])
3207
+		) {
3208
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3209
+		} else {
3210
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3211
+		}
3212
+		$where_query_params = array_merge(
3213
+			$this->_get_default_where_conditions_for_models_in_query(
3214
+				$query_object,
3215
+				$use_default_where_conditions,
3216
+				$where_query_params
3217
+			),
3218
+			$where_query_params
3219
+		);
3220
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3221
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3222
+		// So we need to setup a subquery and use that for the main join.
3223
+		// Note for now this only works on the primary table for the model.
3224
+		// So for instance, you could set the limit array like this:
3225
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3226
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3227
+			$query_object->set_main_model_join_sql(
3228
+				$this->_construct_limit_join_select(
3229
+					$query_params['on_join_limit'][0],
3230
+					$query_params['on_join_limit'][1]
3231
+				)
3232
+			);
3233
+		}
3234
+		//set limit
3235
+		if (array_key_exists('limit', $query_params)) {
3236
+			if (is_array($query_params['limit'])) {
3237
+				if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3238
+					$e = sprintf(
3239
+						__(
3240
+							"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)",
3241
+							"event_espresso"
3242
+						),
3243
+						http_build_query($query_params['limit'])
3244
+					);
3245
+					throw new EE_Error($e . "|" . $e);
3246
+				}
3247
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3248
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3249
+			} elseif ( ! empty ($query_params['limit'])) {
3250
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3251
+			}
3252
+		}
3253
+		//set order by
3254
+		if (array_key_exists('order_by', $query_params)) {
3255
+			if (is_array($query_params['order_by'])) {
3256
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3257
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3258
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3259
+				if (array_key_exists('order', $query_params)) {
3260
+					throw new EE_Error(
3261
+						sprintf(
3262
+							__(
3263
+								"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 ",
3264
+								"event_espresso"
3265
+							),
3266
+							get_class($this),
3267
+							implode(", ", array_keys($query_params['order_by'])),
3268
+							implode(", ", $query_params['order_by']),
3269
+							$query_params['order']
3270
+						)
3271
+					);
3272
+				}
3273
+				$this->_extract_related_models_from_sub_params_array_keys(
3274
+					$query_params['order_by'],
3275
+					$query_object,
3276
+					'order_by'
3277
+				);
3278
+				//assume it's an array of fields to order by
3279
+				$order_array = array();
3280
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3281
+					$order = $this->_extract_order($order);
3282
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3283
+				}
3284
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3285
+			} elseif ( ! empty ($query_params['order_by'])) {
3286
+				$this->_extract_related_model_info_from_query_param(
3287
+					$query_params['order_by'],
3288
+					$query_object,
3289
+					'order',
3290
+					$query_params['order_by']
3291
+				);
3292
+				$order = isset($query_params['order'])
3293
+					? $this->_extract_order($query_params['order'])
3294
+					: 'DESC';
3295
+				$query_object->set_order_by_sql(
3296
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3297
+				);
3298
+			}
3299
+		}
3300
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3301
+		if ( ! array_key_exists('order_by', $query_params)
3302
+			 && array_key_exists('order', $query_params)
3303
+			 && ! empty($query_params['order'])
3304
+		) {
3305
+			$pk_field = $this->get_primary_key_field();
3306
+			$order = $this->_extract_order($query_params['order']);
3307
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3308
+		}
3309
+		//set group by
3310
+		if (array_key_exists('group_by', $query_params)) {
3311
+			if (is_array($query_params['group_by'])) {
3312
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3313
+				$group_by_array = array();
3314
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3315
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3316
+				}
3317
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3318
+			} elseif ( ! empty ($query_params['group_by'])) {
3319
+				$query_object->set_group_by_sql(
3320
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3321
+				);
3322
+			}
3323
+		}
3324
+		//set having
3325
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3326
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3327
+		}
3328
+		//now, just verify they didn't pass anything wack
3329
+		foreach ($query_params as $query_key => $query_value) {
3330
+			if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3331
+				throw new EE_Error(
3332
+					sprintf(
3333
+						__(
3334
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3335
+							'event_espresso'
3336
+						),
3337
+						$query_key,
3338
+						get_class($this),
3339
+						//						print_r( $this->_allowed_query_params, TRUE )
3340
+						implode(',', $this->_allowed_query_params)
3341
+					)
3342
+				);
3343
+			}
3344
+		}
3345
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3346
+		if (empty($main_model_join_sql)) {
3347
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3348
+		}
3349
+		return $query_object;
3350
+	}
3351
+
3352
+
3353
+
3354
+	/**
3355
+	 * Gets the where conditions that should be imposed on the query based on the
3356
+	 * context (eg reading frontend, backend, edit or delete).
3357
+	 *
3358
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3359
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3360
+	 * @throws \EE_Error
3361
+	 */
3362
+	public function caps_where_conditions($context = self::caps_read)
3363
+	{
3364
+		EEM_Base::verify_is_valid_cap_context($context);
3365
+		$cap_where_conditions = array();
3366
+		$cap_restrictions = $this->caps_missing($context);
3367
+		/**
3368
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3369
+		 */
3370
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3371
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3372
+				$restriction_if_no_cap->get_default_where_conditions());
3373
+		}
3374
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3375
+			$cap_restrictions);
3376
+	}
3377
+
3378
+
3379
+
3380
+	/**
3381
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3382
+	 * otherwise throws an exception
3383
+	 *
3384
+	 * @param string $should_be_order_string
3385
+	 * @return string either ASC, asc, DESC or desc
3386
+	 * @throws EE_Error
3387
+	 */
3388
+	private function _extract_order($should_be_order_string)
3389
+	{
3390
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3391
+			return $should_be_order_string;
3392
+		} else {
3393
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3394
+				"event_espresso"), get_class($this), $should_be_order_string));
3395
+		}
3396
+	}
3397
+
3398
+
3399
+
3400
+	/**
3401
+	 * Looks at all the models which are included in this query, and asks each
3402
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3403
+	 * so they can be merged
3404
+	 *
3405
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3406
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3407
+	 *                                                                  'none' means NO default where conditions will
3408
+	 *                                                                  be used AT ALL during this query.
3409
+	 *                                                                  'other_models_only' means default where
3410
+	 *                                                                  conditions from other models will be used, but
3411
+	 *                                                                  not for this primary model. 'all', the default,
3412
+	 *                                                                  means default where conditions will apply as
3413
+	 *                                                                  normal
3414
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3415
+	 * @throws EE_Error
3416
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3417
+	 */
3418
+	private function _get_default_where_conditions_for_models_in_query(
3419
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3420
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3421
+		$where_query_params = array()
3422
+	) {
3423
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3424
+		if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3425
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3426
+				"event_espresso"), $use_default_where_conditions,
3427
+				implode(", ", $allowed_used_default_where_conditions_values)));
3428
+		}
3429
+		$universal_query_params = array();
3430
+		if (
3431
+			in_array(
3432
+				$use_default_where_conditions,
3433
+				array(
3434
+					EEM_Base::default_where_conditions_all,
3435
+					EEM_Base::default_where_conditions_this_only,
3436
+					EEM_Base::default_where_conditions_minimum_others
3437
+				),
3438
+				true
3439
+			)
3440
+		) {
3441
+			$universal_query_params = $this->_get_default_where_conditions();
3442
+		} else if ($use_default_where_conditions === EEM_Base::default_where_conditions_minimum_all) {
3443
+			$universal_query_params = $this->_get_minimum_where_conditions();
3444
+		}
3445
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3446
+
3447
+			$related_model = $this->get_related_model_obj($model_name);
3448
+			if (
3449
+				in_array(
3450
+					$use_default_where_conditions,
3451
+					array(
3452
+						EEM_Base::default_where_conditions_all,
3453
+						EEM_Base::default_where_conditions_others_only
3454
+					),
3455
+					true
3456
+				)
3457
+			) {
3458
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3459
+			} elseif(
3460
+				in_array(
3461
+					$use_default_where_conditions,
3462
+					array(
3463
+						EEM_Base::default_where_conditions_minimum_others,
3464
+						EEM_Base::default_where_conditions_minimum_all
3465
+					),
3466
+					true
3467
+				)
3468
+			) {
3469
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3470
+			} else {
3471
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3472
+				continue;
3473
+			}
3474
+
3475
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3476
+				$related_model_universal_where_params,
3477
+				$where_query_params,
3478
+				$related_model,
3479
+				$model_relation_path
3480
+			);
3481
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3482
+				$universal_query_params,
3483
+				$overrides
3484
+			);
3485
+		}
3486
+		return $universal_query_params;
3487
+	}
3488
+
3489
+
3490
+
3491
+	/**
3492
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3493
+	 * then we also add a special where condition which allows for that model's primary key
3494
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3495
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3496
+	 *
3497
+	 * @param array    $default_where_conditions
3498
+	 * @param array    $provided_where_conditions
3499
+	 * @param EEM_Base $model
3500
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3501
+	 * @return array like EEM_Base::get_all's $query_params[0]
3502
+	 * @throws \EE_Error
3503
+	 */
3504
+	private function _override_defaults_or_make_null_friendly(
3505
+		$default_where_conditions,
3506
+		$provided_where_conditions,
3507
+		$model,
3508
+		$model_relation_path
3509
+	) {
3510
+		$null_friendly_where_conditions = array();
3511
+		$none_overridden = true;
3512
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3513
+		foreach ($default_where_conditions as $key => $val) {
3514
+			if (isset($provided_where_conditions[$key])) {
3515
+				$none_overridden = false;
3516
+			} else {
3517
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3518
+			}
3519
+		}
3520
+		if ($none_overridden && $default_where_conditions) {
3521
+			if ($model->has_primary_key_field()) {
3522
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3523
+																				. "."
3524
+																				. $model->primary_key_name()] = array('IS NULL');
3525
+			}/*else{
3526 3526
 				//@todo NO PK, use other defaults
3527 3527
 			}*/
3528
-        }
3529
-        return $null_friendly_where_conditions;
3530
-    }
3531
-
3532
-
3533
-
3534
-    /**
3535
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3536
-     * default where conditions on all get_all, update, and delete queries done by this model.
3537
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3538
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3539
-     *
3540
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3541
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3542
-     */
3543
-    private function _get_default_where_conditions($model_relation_path = null)
3544
-    {
3545
-        if ($this->_ignore_where_strategy) {
3546
-            return array();
3547
-        }
3548
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3549
-    }
3550
-
3551
-
3552
-
3553
-    /**
3554
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3555
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3556
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3557
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3558
-     * Similar to _get_default_where_conditions
3559
-     *
3560
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3561
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3562
-     */
3563
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3564
-    {
3565
-        if ($this->_ignore_where_strategy) {
3566
-            return array();
3567
-        }
3568
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3569
-    }
3570
-
3571
-
3572
-
3573
-    /**
3574
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3575
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3576
-     *
3577
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3578
-     * @return string
3579
-     * @throws \EE_Error
3580
-     */
3581
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3582
-    {
3583
-        $selects = $this->_get_columns_to_select_for_this_model();
3584
-        foreach (
3585
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3586
-            $name_of_other_model_included
3587
-        ) {
3588
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3589
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3590
-            foreach ($other_model_selects as $key => $value) {
3591
-                $selects[] = $value;
3592
-            }
3593
-        }
3594
-        return implode(", ", $selects);
3595
-    }
3596
-
3597
-
3598
-
3599
-    /**
3600
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3601
-     * So that's going to be the columns for all the fields on the model
3602
-     *
3603
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3604
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3605
-     */
3606
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3607
-    {
3608
-        $fields = $this->field_settings();
3609
-        $selects = array();
3610
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3611
-            $this->get_this_model_name());
3612
-        foreach ($fields as $field_obj) {
3613
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3614
-                         . $field_obj->get_table_alias()
3615
-                         . "."
3616
-                         . $field_obj->get_table_column()
3617
-                         . " AS '"
3618
-                         . $table_alias_with_model_relation_chain_prefix
3619
-                         . $field_obj->get_table_alias()
3620
-                         . "."
3621
-                         . $field_obj->get_table_column()
3622
-                         . "'";
3623
-        }
3624
-        //make sure we are also getting the PKs of each table
3625
-        $tables = $this->get_tables();
3626
-        if (count($tables) > 1) {
3627
-            foreach ($tables as $table_obj) {
3628
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3629
-                                       . $table_obj->get_fully_qualified_pk_column();
3630
-                if ( ! in_array($qualified_pk_column, $selects)) {
3631
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3632
-                }
3633
-            }
3634
-        }
3635
-        return $selects;
3636
-    }
3637
-
3638
-
3639
-
3640
-    /**
3641
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3642
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3643
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3644
-     * SQL for joining, and the data types
3645
-     *
3646
-     * @param null|string                 $original_query_param
3647
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3648
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3649
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3650
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3651
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3652
-     *                                                          or 'Registration's
3653
-     * @param string                      $original_query_param what it originally was (eg
3654
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3655
-     *                                                          matches $query_param
3656
-     * @throws EE_Error
3657
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3658
-     */
3659
-    private function _extract_related_model_info_from_query_param(
3660
-        $query_param,
3661
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3662
-        $query_param_type,
3663
-        $original_query_param = null
3664
-    ) {
3665
-        if ($original_query_param === null) {
3666
-            $original_query_param = $query_param;
3667
-        }
3668
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3669
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3670
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3671
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3672
-        //check to see if we have a field on this model
3673
-        $this_model_fields = $this->field_settings(true);
3674
-        if (array_key_exists($query_param, $this_model_fields)) {
3675
-            if ($allow_fields) {
3676
-                return;
3677
-            } else {
3678
-                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",
3679
-                    "event_espresso"),
3680
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3681
-            }
3682
-        } //check if this is a special logic query param
3683
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3684
-            if ($allow_logic_query_params) {
3685
-                return;
3686
-            } else {
3687
-                throw new EE_Error(
3688
-                    sprintf(
3689
-                        __('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',
3690
-                            'event_espresso'),
3691
-                        implode('", "', $this->_logic_query_param_keys),
3692
-                        $query_param,
3693
-                        get_class($this),
3694
-                        '<br />',
3695
-                        "\t"
3696
-                        . ' $passed_in_query_info = <pre>'
3697
-                        . print_r($passed_in_query_info, true)
3698
-                        . '</pre>'
3699
-                        . "\n\t"
3700
-                        . ' $query_param_type = '
3701
-                        . $query_param_type
3702
-                        . "\n\t"
3703
-                        . ' $original_query_param = '
3704
-                        . $original_query_param
3705
-                    )
3706
-                );
3707
-            }
3708
-        } //check if it's a custom selection
3709
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3710
-            return;
3711
-        }
3712
-        //check if has a model name at the beginning
3713
-        //and
3714
-        //check if it's a field on a related model
3715
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3716
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3717
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3718
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3719
-                if ($query_param === '') {
3720
-                    //nothing left to $query_param
3721
-                    //we should actually end in a field name, not a model like this!
3722
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3723
-                        "event_espresso"),
3724
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3725
-                } else {
3726
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3727
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3728
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3729
-                    return;
3730
-                }
3731
-            } elseif ($query_param === $valid_related_model_name) {
3732
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3733
-                return;
3734
-            }
3735
-        }
3736
-        //ok so $query_param didn't start with a model name
3737
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3738
-        //it's wack, that's what it is
3739
-        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",
3740
-            "event_espresso"),
3741
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3742
-    }
3743
-
3744
-
3745
-
3746
-    /**
3747
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3748
-     * and store it on $passed_in_query_info
3749
-     *
3750
-     * @param string                      $model_name
3751
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3752
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3753
-     *                                                          model and $model_name. Eg, if we are querying Event,
3754
-     *                                                          and are adding a join to 'Payment' with the original
3755
-     *                                                          query param key
3756
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3757
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3758
-     *                                                          Payment wants to add default query params so that it
3759
-     *                                                          will know what models to prepend onto its default query
3760
-     *                                                          params or in case it wants to rename tables (in case
3761
-     *                                                          there are multiple joins to the same table)
3762
-     * @return void
3763
-     * @throws \EE_Error
3764
-     */
3765
-    private function _add_join_to_model(
3766
-        $model_name,
3767
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3768
-        $original_query_param
3769
-    ) {
3770
-        $relation_obj = $this->related_settings_for($model_name);
3771
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3772
-        //check if the relation is HABTM, because then we're essentially doing two joins
3773
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3774
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3775
-            $join_model_obj = $relation_obj->get_join_model();
3776
-            //replace the model specified with the join model for this relation chain, whi
3777
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3778
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3779
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3780
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3781
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3782
-            $passed_in_query_info->merge($new_query_info);
3783
-        }
3784
-        //now just join to the other table pointed to by the relation object, and add its data types
3785
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3786
-            array($model_relation_chain => $model_name),
3787
-            $relation_obj->get_join_statement($model_relation_chain));
3788
-        $passed_in_query_info->merge($new_query_info);
3789
-    }
3790
-
3791
-
3792
-
3793
-    /**
3794
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3795
-     *
3796
-     * @param array $where_params like EEM_Base::get_all
3797
-     * @return string of SQL
3798
-     * @throws \EE_Error
3799
-     */
3800
-    private function _construct_where_clause($where_params)
3801
-    {
3802
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3803
-        if ($SQL) {
3804
-            return " WHERE " . $SQL;
3805
-        } else {
3806
-            return '';
3807
-        }
3808
-    }
3809
-
3810
-
3811
-
3812
-    /**
3813
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3814
-     * and should be passed HAVING parameters, not WHERE parameters
3815
-     *
3816
-     * @param array $having_params
3817
-     * @return string
3818
-     * @throws \EE_Error
3819
-     */
3820
-    private function _construct_having_clause($having_params)
3821
-    {
3822
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3823
-        if ($SQL) {
3824
-            return " HAVING " . $SQL;
3825
-        } else {
3826
-            return '';
3827
-        }
3828
-    }
3829
-
3830
-
3831
-
3832
-    /**
3833
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3834
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3835
-     * EEM_Attendee.
3836
-     *
3837
-     * @param string $field_name
3838
-     * @param string $model_name
3839
-     * @return EE_Model_Field_Base
3840
-     * @throws EE_Error
3841
-     */
3842
-    protected function _get_field_on_model($field_name, $model_name)
3843
-    {
3844
-        $model_class = 'EEM_' . $model_name;
3845
-        $model_filepath = $model_class . ".model.php";
3846
-        if (is_readable($model_filepath)) {
3847
-            require_once($model_filepath);
3848
-            $model_instance = call_user_func($model_name . "::instance");
3849
-            /* @var $model_instance EEM_Base */
3850
-            return $model_instance->field_settings_for($field_name);
3851
-        } else {
3852
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3853
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3854
-        }
3855
-    }
3856
-
3857
-
3858
-
3859
-    /**
3860
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3861
-     * Event_Meta.meta_value = 'foo'))"
3862
-     *
3863
-     * @param array  $where_params see EEM_Base::get_all for documentation
3864
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3865
-     * @throws EE_Error
3866
-     * @return string of SQL
3867
-     */
3868
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3869
-    {
3870
-        $where_clauses = array();
3871
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3872
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3873
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3874
-                switch ($query_param) {
3875
-                    case 'not':
3876
-                    case 'NOT':
3877
-                        $where_clauses[] = "! ("
3878
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3879
-                                $glue)
3880
-                                           . ")";
3881
-                        break;
3882
-                    case 'and':
3883
-                    case 'AND':
3884
-                        $where_clauses[] = " ("
3885
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3886
-                                ' AND ')
3887
-                                           . ")";
3888
-                        break;
3889
-                    case 'or':
3890
-                    case 'OR':
3891
-                        $where_clauses[] = " ("
3892
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3893
-                                ' OR ')
3894
-                                           . ")";
3895
-                        break;
3896
-                }
3897
-            } else {
3898
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3899
-                //if it's not a normal field, maybe it's a custom selection?
3900
-                if ( ! $field_obj) {
3901
-                    if (isset($this->_custom_selections[$query_param][1])) {
3902
-                        $field_obj = $this->_custom_selections[$query_param][1];
3903
-                    } else {
3904
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3905
-                            "event_espresso"), $query_param));
3906
-                    }
3907
-                }
3908
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3909
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3910
-            }
3911
-        }
3912
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3913
-    }
3914
-
3915
-
3916
-
3917
-    /**
3918
-     * Takes the input parameter and extract the table name (alias) and column name
3919
-     *
3920
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3921
-     * @throws EE_Error
3922
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3923
-     */
3924
-    private function _deduce_column_name_from_query_param($query_param)
3925
-    {
3926
-        $field = $this->_deduce_field_from_query_param($query_param);
3927
-        if ($field) {
3928
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3929
-                $query_param);
3930
-            return $table_alias_prefix . $field->get_qualified_column();
3931
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
3932
-            //maybe it's custom selection item?
3933
-            //if so, just use it as the "column name"
3934
-            return $query_param;
3935
-        } else {
3936
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
3937
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
3938
-        }
3939
-    }
3940
-
3941
-
3942
-
3943
-    /**
3944
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
3945
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
3946
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3947
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3948
-     *
3949
-     * @param string $condition_query_param_key
3950
-     * @return string
3951
-     */
3952
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
3953
-    {
3954
-        $pos_of_star = strpos($condition_query_param_key, '*');
3955
-        if ($pos_of_star === false) {
3956
-            return $condition_query_param_key;
3957
-        } else {
3958
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3959
-            return $condition_query_param_sans_star;
3960
-        }
3961
-    }
3962
-
3963
-
3964
-
3965
-    /**
3966
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3967
-     *
3968
-     * @param                            mixed      array | string    $op_and_value
3969
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3970
-     * @throws EE_Error
3971
-     * @return string
3972
-     */
3973
-    private function _construct_op_and_value($op_and_value, $field_obj)
3974
-    {
3975
-        if (is_array($op_and_value)) {
3976
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
3977
-            if ( ! $operator) {
3978
-                $php_array_like_string = array();
3979
-                foreach ($op_and_value as $key => $value) {
3980
-                    $php_array_like_string[] = "$key=>$value";
3981
-                }
3982
-                throw new EE_Error(
3983
-                    sprintf(
3984
-                        __(
3985
-                            "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))",
3986
-                            "event_espresso"
3987
-                        ),
3988
-                        implode(",", $php_array_like_string)
3989
-                    )
3990
-                );
3991
-            }
3992
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
3993
-        } else {
3994
-            $operator = '=';
3995
-            $value = $op_and_value;
3996
-        }
3997
-        //check to see if the value is actually another field
3998
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3999
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4000
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4001
-            //in this case, the value should be an array, or at least a comma-separated list
4002
-            //it will need to handle a little differently
4003
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4004
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4005
-            return $operator . SP . $cleaned_value;
4006
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4007
-            //the value should be an array with count of two.
4008
-            if (count($value) !== 2) {
4009
-                throw new EE_Error(
4010
-                    sprintf(
4011
-                        __(
4012
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4013
-                            'event_espresso'
4014
-                        ),
4015
-                        "BETWEEN"
4016
-                    )
4017
-                );
4018
-            }
4019
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4020
-            return $operator . SP . $cleaned_value;
4021
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4022
-            if ($value !== null) {
4023
-                throw new EE_Error(
4024
-                    sprintf(
4025
-                        __(
4026
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4027
-                            "event_espresso"
4028
-                        ),
4029
-                        $value,
4030
-                        $operator
4031
-                    )
4032
-                );
4033
-            }
4034
-            return $operator;
4035
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4036
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4037
-            //remove other junk. So just treat it as a string.
4038
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4039
-        } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4040
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4041
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4042
-            throw new EE_Error(
4043
-                sprintf(
4044
-                    __(
4045
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4046
-                        'event_espresso'
4047
-                    ),
4048
-                    $operator,
4049
-                    $operator
4050
-                )
4051
-            );
4052
-        } elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4053
-            throw new EE_Error(
4054
-                sprintf(
4055
-                    __(
4056
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4057
-                        'event_espresso'
4058
-                    ),
4059
-                    $operator,
4060
-                    $operator
4061
-                )
4062
-            );
4063
-        } else {
4064
-            throw new EE_Error(
4065
-                sprintf(
4066
-                    __(
4067
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4068
-                        "event_espresso"
4069
-                    ),
4070
-                    http_build_query($op_and_value)
4071
-                )
4072
-            );
4073
-        }
4074
-    }
4075
-
4076
-
4077
-
4078
-    /**
4079
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4080
-     *
4081
-     * @param array                      $values
4082
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4083
-     *                                              '%s'
4084
-     * @return string
4085
-     * @throws \EE_Error
4086
-     */
4087
-    public function _construct_between_value($values, $field_obj)
4088
-    {
4089
-        $cleaned_values = array();
4090
-        foreach ($values as $value) {
4091
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4092
-        }
4093
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4094
-    }
4095
-
4096
-
4097
-
4098
-    /**
4099
-     * Takes an array or a comma-separated list of $values and cleans them
4100
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4101
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4102
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4103
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4104
-     *
4105
-     * @param mixed                      $values    array or comma-separated string
4106
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4107
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4108
-     * @throws \EE_Error
4109
-     */
4110
-    public function _construct_in_value($values, $field_obj)
4111
-    {
4112
-        //check if the value is a CSV list
4113
-        if (is_string($values)) {
4114
-            //in which case, turn it into an array
4115
-            $values = explode(",", $values);
4116
-        }
4117
-        $cleaned_values = array();
4118
-        foreach ($values as $value) {
4119
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4120
-        }
4121
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4122
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4123
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4124
-        if (empty($cleaned_values)) {
4125
-            $all_fields = $this->field_settings();
4126
-            $a_field = array_shift($all_fields);
4127
-            $main_table = $this->_get_main_table();
4128
-            $cleaned_values[] = "SELECT "
4129
-                                . $a_field->get_table_column()
4130
-                                . " FROM "
4131
-                                . $main_table->get_table_name()
4132
-                                . " WHERE FALSE";
4133
-        }
4134
-        return "(" . implode(",", $cleaned_values) . ")";
4135
-    }
4136
-
4137
-
4138
-
4139
-    /**
4140
-     * @param mixed                      $value
4141
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4142
-     * @throws EE_Error
4143
-     * @return false|null|string
4144
-     */
4145
-    private function _wpdb_prepare_using_field($value, $field_obj)
4146
-    {
4147
-        /** @type WPDB $wpdb */
4148
-        global $wpdb;
4149
-        if ($field_obj instanceof EE_Model_Field_Base) {
4150
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4151
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4152
-        } else {//$field_obj should really just be a data type
4153
-            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4154
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4155
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4156
-            }
4157
-            return $wpdb->prepare($field_obj, $value);
4158
-        }
4159
-    }
4160
-
4161
-
4162
-
4163
-    /**
4164
-     * Takes the input parameter and finds the model field that it indicates.
4165
-     *
4166
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4167
-     * @throws EE_Error
4168
-     * @return EE_Model_Field_Base
4169
-     */
4170
-    protected function _deduce_field_from_query_param($query_param_name)
4171
-    {
4172
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4173
-        //which will help us find the database table and column
4174
-        $query_param_parts = explode(".", $query_param_name);
4175
-        if (empty($query_param_parts)) {
4176
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4177
-                'event_espresso'), $query_param_name));
4178
-        }
4179
-        $number_of_parts = count($query_param_parts);
4180
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4181
-        if ($number_of_parts === 1) {
4182
-            $field_name = $last_query_param_part;
4183
-            $model_obj = $this;
4184
-        } else {// $number_of_parts >= 2
4185
-            //the last part is the column name, and there are only 2parts. therefore...
4186
-            $field_name = $last_query_param_part;
4187
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4188
-        }
4189
-        try {
4190
-            return $model_obj->field_settings_for($field_name);
4191
-        } catch (EE_Error $e) {
4192
-            return null;
4193
-        }
4194
-    }
4195
-
4196
-
4197
-
4198
-    /**
4199
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4200
-     * alias and column which corresponds to it
4201
-     *
4202
-     * @param string $field_name
4203
-     * @throws EE_Error
4204
-     * @return string
4205
-     */
4206
-    public function _get_qualified_column_for_field($field_name)
4207
-    {
4208
-        $all_fields = $this->field_settings();
4209
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4210
-        if ($field) {
4211
-            return $field->get_qualified_column();
4212
-        } else {
4213
-            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.",
4214
-                'event_espresso'), $field_name, get_class($this)));
4215
-        }
4216
-    }
4217
-
4218
-
4219
-
4220
-    /**
4221
-     * constructs the select use on special limit joins
4222
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4223
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4224
-     * (as that is typically where the limits would be set).
4225
-     *
4226
-     * @param  string       $table_alias The table the select is being built for
4227
-     * @param  mixed|string $limit       The limit for this select
4228
-     * @return string                The final select join element for the query.
4229
-     */
4230
-    public function _construct_limit_join_select($table_alias, $limit)
4231
-    {
4232
-        $SQL = '';
4233
-        foreach ($this->_tables as $table_obj) {
4234
-            if ($table_obj instanceof EE_Primary_Table) {
4235
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4236
-                    ? $table_obj->get_select_join_limit($limit)
4237
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4238
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4239
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4240
-                    ? $table_obj->get_select_join_limit_join($limit)
4241
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4242
-            }
4243
-        }
4244
-        return $SQL;
4245
-    }
4246
-
4247
-
4248
-
4249
-    /**
4250
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4251
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4252
-     *
4253
-     * @return string SQL
4254
-     * @throws \EE_Error
4255
-     */
4256
-    public function _construct_internal_join()
4257
-    {
4258
-        $SQL = $this->_get_main_table()->get_table_sql();
4259
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4260
-        return $SQL;
4261
-    }
4262
-
4263
-
4264
-
4265
-    /**
4266
-     * Constructs the SQL for joining all the tables on this model.
4267
-     * Normally $alias should be the primary table's alias, but in cases where
4268
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4269
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4270
-     * alias, this will construct SQL like:
4271
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4272
-     * With $alias being a secondary table's alias, this will construct SQL like:
4273
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4274
-     *
4275
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4276
-     * @return string
4277
-     */
4278
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4279
-    {
4280
-        $SQL = '';
4281
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4282
-        foreach ($this->_tables as $table_obj) {
4283
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4284
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4285
-                    //so we're joining to this table, meaning the table is already in
4286
-                    //the FROM statement, BUT the primary table isn't. So we want
4287
-                    //to add the inverse join sql
4288
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4289
-                } else {
4290
-                    //just add a regular JOIN to this table from the primary table
4291
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4292
-                }
4293
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4294
-        }
4295
-        return $SQL;
4296
-    }
4297
-
4298
-
4299
-
4300
-    /**
4301
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4302
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4303
-     * their data type (eg, '%s', '%d', etc)
4304
-     *
4305
-     * @return array
4306
-     */
4307
-    public function _get_data_types()
4308
-    {
4309
-        $data_types = array();
4310
-        foreach ($this->field_settings() as $field_obj) {
4311
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4312
-            /** @var $field_obj EE_Model_Field_Base */
4313
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4314
-        }
4315
-        return $data_types;
4316
-    }
4317
-
4318
-
4319
-
4320
-    /**
4321
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4322
-     *
4323
-     * @param string $model_name
4324
-     * @throws EE_Error
4325
-     * @return EEM_Base
4326
-     */
4327
-    public function get_related_model_obj($model_name)
4328
-    {
4329
-        $model_classname = "EEM_" . $model_name;
4330
-        if ( ! class_exists($model_classname)) {
4331
-            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",
4332
-                'event_espresso'), $model_name, $model_classname));
4333
-        }
4334
-        return call_user_func($model_classname . "::instance");
4335
-    }
4336
-
4337
-
4338
-
4339
-    /**
4340
-     * Returns the array of EE_ModelRelations for this model.
4341
-     *
4342
-     * @return EE_Model_Relation_Base[]
4343
-     */
4344
-    public function relation_settings()
4345
-    {
4346
-        return $this->_model_relations;
4347
-    }
4348
-
4349
-
4350
-
4351
-    /**
4352
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4353
-     * because without THOSE models, this model probably doesn't have much purpose.
4354
-     * (Eg, without an event, datetimes have little purpose.)
4355
-     *
4356
-     * @return EE_Belongs_To_Relation[]
4357
-     */
4358
-    public function belongs_to_relations()
4359
-    {
4360
-        $belongs_to_relations = array();
4361
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4362
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4363
-                $belongs_to_relations[$model_name] = $relation_obj;
4364
-            }
4365
-        }
4366
-        return $belongs_to_relations;
4367
-    }
4368
-
4369
-
4370
-
4371
-    /**
4372
-     * Returns the specified EE_Model_Relation, or throws an exception
4373
-     *
4374
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4375
-     * @throws EE_Error
4376
-     * @return EE_Model_Relation_Base
4377
-     */
4378
-    public function related_settings_for($relation_name)
4379
-    {
4380
-        $relatedModels = $this->relation_settings();
4381
-        if ( ! array_key_exists($relation_name, $relatedModels)) {
4382
-            throw new EE_Error(
4383
-                sprintf(
4384
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4385
-                        'event_espresso'),
4386
-                    $relation_name,
4387
-                    $this->_get_class_name(),
4388
-                    implode(', ', array_keys($relatedModels))
4389
-                )
4390
-            );
4391
-        }
4392
-        return $relatedModels[$relation_name];
4393
-    }
4394
-
4395
-
4396
-
4397
-    /**
4398
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4399
-     * fields
4400
-     *
4401
-     * @param string $fieldName
4402
-     * @throws EE_Error
4403
-     * @return EE_Model_Field_Base
4404
-     */
4405
-    public function field_settings_for($fieldName)
4406
-    {
4407
-        $fieldSettings = $this->field_settings(true);
4408
-        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4409
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4410
-                get_class($this)));
4411
-        }
4412
-        return $fieldSettings[$fieldName];
4413
-    }
4414
-
4415
-
4416
-
4417
-    /**
4418
-     * Checks if this field exists on this model
4419
-     *
4420
-     * @param string $fieldName a key in the model's _field_settings array
4421
-     * @return boolean
4422
-     */
4423
-    public function has_field($fieldName)
4424
-    {
4425
-        $fieldSettings = $this->field_settings(true);
4426
-        if (isset($fieldSettings[$fieldName])) {
4427
-            return true;
4428
-        } else {
4429
-            return false;
4430
-        }
4431
-    }
4432
-
4433
-
4434
-
4435
-    /**
4436
-     * Returns whether or not this model has a relation to the specified model
4437
-     *
4438
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4439
-     * @return boolean
4440
-     */
4441
-    public function has_relation($relation_name)
4442
-    {
4443
-        $relations = $this->relation_settings();
4444
-        if (isset($relations[$relation_name])) {
4445
-            return true;
4446
-        } else {
4447
-            return false;
4448
-        }
4449
-    }
4450
-
4451
-
4452
-
4453
-    /**
4454
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4455
-     * Eg, on EE_Answer that would be ANS_ID field object
4456
-     *
4457
-     * @param $field_obj
4458
-     * @return boolean
4459
-     */
4460
-    public function is_primary_key_field($field_obj)
4461
-    {
4462
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4463
-    }
4464
-
4465
-
4466
-
4467
-    /**
4468
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4469
-     * Eg, on EE_Answer that would be ANS_ID field object
4470
-     *
4471
-     * @return EE_Model_Field_Base
4472
-     * @throws EE_Error
4473
-     */
4474
-    public function get_primary_key_field()
4475
-    {
4476
-        if ($this->_primary_key_field === null) {
4477
-            foreach ($this->field_settings(true) as $field_obj) {
4478
-                if ($this->is_primary_key_field($field_obj)) {
4479
-                    $this->_primary_key_field = $field_obj;
4480
-                    break;
4481
-                }
4482
-            }
4483
-            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4484
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4485
-                    get_class($this)));
4486
-            }
4487
-        }
4488
-        return $this->_primary_key_field;
4489
-    }
4490
-
4491
-
4492
-
4493
-    /**
4494
-     * Returns whether or not not there is a primary key on this model.
4495
-     * Internally does some caching.
4496
-     *
4497
-     * @return boolean
4498
-     */
4499
-    public function has_primary_key_field()
4500
-    {
4501
-        if ($this->_has_primary_key_field === null) {
4502
-            try {
4503
-                $this->get_primary_key_field();
4504
-                $this->_has_primary_key_field = true;
4505
-            } catch (EE_Error $e) {
4506
-                $this->_has_primary_key_field = false;
4507
-            }
4508
-        }
4509
-        return $this->_has_primary_key_field;
4510
-    }
4511
-
4512
-
4513
-
4514
-    /**
4515
-     * Finds the first field of type $field_class_name.
4516
-     *
4517
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4518
-     *                                 EE_Foreign_Key_Field, etc
4519
-     * @return EE_Model_Field_Base or null if none is found
4520
-     */
4521
-    public function get_a_field_of_type($field_class_name)
4522
-    {
4523
-        foreach ($this->field_settings() as $field) {
4524
-            if ($field instanceof $field_class_name) {
4525
-                return $field;
4526
-            }
4527
-        }
4528
-        return null;
4529
-    }
4530
-
4531
-
4532
-
4533
-    /**
4534
-     * Gets a foreign key field pointing to model.
4535
-     *
4536
-     * @param string $model_name eg Event, Registration, not EEM_Event
4537
-     * @return EE_Foreign_Key_Field_Base
4538
-     * @throws EE_Error
4539
-     */
4540
-    public function get_foreign_key_to($model_name)
4541
-    {
4542
-        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4543
-            foreach ($this->field_settings() as $field) {
4544
-                if (
4545
-                    $field instanceof EE_Foreign_Key_Field_Base
4546
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4547
-                ) {
4548
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4549
-                    break;
4550
-                }
4551
-            }
4552
-            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4553
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4554
-                    'event_espresso'), $model_name, get_class($this)));
4555
-            }
4556
-        }
4557
-        return $this->_cache_foreign_key_to_fields[$model_name];
4558
-    }
4559
-
4560
-
4561
-
4562
-    /**
4563
-     * Gets the actual table for the table alias
4564
-     *
4565
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4566
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4567
-     *                            Either one works
4568
-     * @return EE_Table_Base
4569
-     */
4570
-    public function get_table_for_alias($table_alias)
4571
-    {
4572
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4573
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4574
-    }
4575
-
4576
-
4577
-
4578
-    /**
4579
-     * Returns a flat array of all field son this model, instead of organizing them
4580
-     * by table_alias as they are in the constructor.
4581
-     *
4582
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4583
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4584
-     */
4585
-    public function field_settings($include_db_only_fields = false)
4586
-    {
4587
-        if ($include_db_only_fields) {
4588
-            if ($this->_cached_fields === null) {
4589
-                $this->_cached_fields = array();
4590
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4591
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4592
-                        $this->_cached_fields[$field_name] = $field_obj;
4593
-                    }
4594
-                }
4595
-            }
4596
-            return $this->_cached_fields;
4597
-        } else {
4598
-            if ($this->_cached_fields_non_db_only === null) {
4599
-                $this->_cached_fields_non_db_only = array();
4600
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4601
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4602
-                        /** @var $field_obj EE_Model_Field_Base */
4603
-                        if ( ! $field_obj->is_db_only_field()) {
4604
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4605
-                        }
4606
-                    }
4607
-                }
4608
-            }
4609
-            return $this->_cached_fields_non_db_only;
4610
-        }
4611
-    }
4612
-
4613
-
4614
-
4615
-    /**
4616
-     *        cycle though array of attendees and create objects out of each item
4617
-     *
4618
-     * @access        private
4619
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4620
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4621
-     *                           numerically indexed)
4622
-     * @throws \EE_Error
4623
-     */
4624
-    protected function _create_objects($rows = array())
4625
-    {
4626
-        $array_of_objects = array();
4627
-        if (empty($rows)) {
4628
-            return array();
4629
-        }
4630
-        $count_if_model_has_no_primary_key = 0;
4631
-        $has_primary_key = $this->has_primary_key_field();
4632
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4633
-        foreach ((array)$rows as $row) {
4634
-            if (empty($row)) {
4635
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4636
-                return array();
4637
-            }
4638
-            //check if we've already set this object in the results array,
4639
-            //in which case there's no need to process it further (again)
4640
-            if ($has_primary_key) {
4641
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4642
-                    $row,
4643
-                    $primary_key_field->get_qualified_column(),
4644
-                    $primary_key_field->get_table_column()
4645
-                );
4646
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4647
-                    continue;
4648
-                }
4649
-            }
4650
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4651
-            if ( ! $classInstance) {
4652
-                throw new EE_Error(
4653
-                    sprintf(
4654
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4655
-                        $this->get_this_model_name(),
4656
-                        http_build_query($row)
4657
-                    )
4658
-                );
4659
-            }
4660
-            //set the timezone on the instantiated objects
4661
-            $classInstance->set_timezone($this->_timezone);
4662
-            //make sure if there is any timezone setting present that we set the timezone for the object
4663
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4664
-            $array_of_objects[$key] = $classInstance;
4665
-            //also, for all the relations of type BelongsTo, see if we can cache
4666
-            //those related models
4667
-            //(we could do this for other relations too, but if there are conditions
4668
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4669
-            //so it requires a little more thought than just caching them immediately...)
4670
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4671
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4672
-                    //check if this model's INFO is present. If so, cache it on the model
4673
-                    $other_model = $relation_obj->get_other_model();
4674
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4675
-                    //if we managed to make a model object from the results, cache it on the main model object
4676
-                    if ($other_model_obj_maybe) {
4677
-                        //set timezone on these other model objects if they are present
4678
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4679
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4680
-                    }
4681
-                }
4682
-            }
4683
-        }
4684
-        return $array_of_objects;
4685
-    }
4686
-
4687
-
4688
-
4689
-    /**
4690
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4691
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4692
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4693
-     * object (as set in the model_field!).
4694
-     *
4695
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4696
-     */
4697
-    public function create_default_object()
4698
-    {
4699
-        $this_model_fields_and_values = array();
4700
-        //setup the row using default values;
4701
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4702
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4703
-        }
4704
-        $className = $this->_get_class_name();
4705
-        $classInstance = EE_Registry::instance()
4706
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4707
-        return $classInstance;
4708
-    }
4709
-
4710
-
4711
-
4712
-    /**
4713
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4714
-     *                             or an stdClass where each property is the name of a column,
4715
-     * @return EE_Base_Class
4716
-     * @throws \EE_Error
4717
-     */
4718
-    public function instantiate_class_from_array_or_object($cols_n_values)
4719
-    {
4720
-        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4721
-            $cols_n_values = get_object_vars($cols_n_values);
4722
-        }
4723
-        $primary_key = null;
4724
-        //make sure the array only has keys that are fields/columns on this model
4725
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4726
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4727
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4728
-        }
4729
-        $className = $this->_get_class_name();
4730
-        //check we actually found results that we can use to build our model object
4731
-        //if not, return null
4732
-        if ($this->has_primary_key_field()) {
4733
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4734
-                return null;
4735
-            }
4736
-        } else if ($this->unique_indexes()) {
4737
-            $first_column = reset($this_model_fields_n_values);
4738
-            if (empty($first_column)) {
4739
-                return null;
4740
-            }
4741
-        }
4742
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4743
-        if ($primary_key) {
4744
-            $classInstance = $this->get_from_entity_map($primary_key);
4745
-            if ( ! $classInstance) {
4746
-                $classInstance = EE_Registry::instance()
4747
-                                            ->load_class($className,
4748
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4749
-                // add this new object to the entity map
4750
-                $classInstance = $this->add_to_entity_map($classInstance);
4751
-            }
4752
-        } else {
4753
-            $classInstance = EE_Registry::instance()
4754
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4755
-                                            true, false);
4756
-        }
4757
-        //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.
4758
-        $this->set_timezone($classInstance->get_timezone());
4759
-        return $classInstance;
4760
-    }
4761
-
4762
-
4763
-
4764
-    /**
4765
-     * Gets the model object from the  entity map if it exists
4766
-     *
4767
-     * @param int|string $id the ID of the model object
4768
-     * @return EE_Base_Class
4769
-     */
4770
-    public function get_from_entity_map($id)
4771
-    {
4772
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4773
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4774
-    }
4775
-
4776
-
4777
-
4778
-    /**
4779
-     * add_to_entity_map
4780
-     * Adds the object to the model's entity mappings
4781
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4782
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4783
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4784
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4785
-     *        then this method should be called immediately after the update query
4786
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4787
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4788
-     *
4789
-     * @param    EE_Base_Class $object
4790
-     * @throws EE_Error
4791
-     * @return \EE_Base_Class
4792
-     */
4793
-    public function add_to_entity_map(EE_Base_Class $object)
4794
-    {
4795
-        $className = $this->_get_class_name();
4796
-        if ( ! $object instanceof $className) {
4797
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4798
-                is_object($object) ? get_class($object) : $object, $className));
4799
-        }
4800
-        /** @var $object EE_Base_Class */
4801
-        if ( ! $object->ID()) {
4802
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4803
-                "event_espresso"), get_class($this)));
4804
-        }
4805
-        // double check it's not already there
4806
-        $classInstance = $this->get_from_entity_map($object->ID());
4807
-        if ($classInstance) {
4808
-            return $classInstance;
4809
-        } else {
4810
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4811
-            return $object;
4812
-        }
4813
-    }
4814
-
4815
-
4816
-
4817
-    /**
4818
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4819
-     * if no identifier is provided, then the entire entity map is emptied
4820
-     *
4821
-     * @param int|string $id the ID of the model object
4822
-     * @return boolean
4823
-     */
4824
-    public function clear_entity_map($id = null)
4825
-    {
4826
-        if (empty($id)) {
4827
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4828
-            return true;
4829
-        }
4830
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4831
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4832
-            return true;
4833
-        }
4834
-        return false;
4835
-    }
4836
-
4837
-
4838
-
4839
-    /**
4840
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4841
-     * Given an array where keys are column (or column alias) names and values,
4842
-     * returns an array of their corresponding field names and database values
4843
-     *
4844
-     * @param array $cols_n_values
4845
-     * @return array
4846
-     */
4847
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4848
-    {
4849
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4850
-    }
4851
-
4852
-
4853
-
4854
-    /**
4855
-     * _deduce_fields_n_values_from_cols_n_values
4856
-     * Given an array where keys are column (or column alias) names and values,
4857
-     * returns an array of their corresponding field names and database values
4858
-     *
4859
-     * @param string $cols_n_values
4860
-     * @return array
4861
-     */
4862
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4863
-    {
4864
-        $this_model_fields_n_values = array();
4865
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
4866
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4867
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4868
-            //there is a primary key on this table and its not set. Use defaults for all its columns
4869
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
4870
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4871
-                    if ( ! $field_obj->is_db_only_field()) {
4872
-                        //prepare field as if its coming from db
4873
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4874
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4875
-                    }
4876
-                }
4877
-            } else {
4878
-                //the table's rows existed. Use their values
4879
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4880
-                    if ( ! $field_obj->is_db_only_field()) {
4881
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4882
-                            $cols_n_values, $field_obj->get_qualified_column(),
4883
-                            $field_obj->get_table_column()
4884
-                        );
4885
-                    }
4886
-                }
4887
-            }
4888
-        }
4889
-        return $this_model_fields_n_values;
4890
-    }
4891
-
4892
-
4893
-
4894
-    /**
4895
-     * @param $cols_n_values
4896
-     * @param $qualified_column
4897
-     * @param $regular_column
4898
-     * @return null
4899
-     */
4900
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4901
-    {
4902
-        $value = null;
4903
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4904
-        //does the field on the model relate to this column retrieved from the db?
4905
-        //or is it a db-only field? (not relating to the model)
4906
-        if (isset($cols_n_values[$qualified_column])) {
4907
-            $value = $cols_n_values[$qualified_column];
4908
-        } elseif (isset($cols_n_values[$regular_column])) {
4909
-            $value = $cols_n_values[$regular_column];
4910
-        }
4911
-        return $value;
4912
-    }
4913
-
4914
-
4915
-
4916
-    /**
4917
-     * refresh_entity_map_from_db
4918
-     * Makes sure the model object in the entity map at $id assumes the values
4919
-     * of the database (opposite of EE_base_Class::save())
4920
-     *
4921
-     * @param int|string $id
4922
-     * @return EE_Base_Class
4923
-     * @throws \EE_Error
4924
-     */
4925
-    public function refresh_entity_map_from_db($id)
4926
-    {
4927
-        $obj_in_map = $this->get_from_entity_map($id);
4928
-        if ($obj_in_map) {
4929
-            $wpdb_results = $this->_get_all_wpdb_results(
4930
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
4931
-            );
4932
-            if ($wpdb_results && is_array($wpdb_results)) {
4933
-                $one_row = reset($wpdb_results);
4934
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
4935
-                    $obj_in_map->set_from_db($field_name, $db_value);
4936
-                }
4937
-                //clear the cache of related model objects
4938
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4939
-                    $obj_in_map->clear_cache($relation_name, null, true);
4940
-                }
4941
-            }
4942
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
4943
-            return $obj_in_map;
4944
-        } else {
4945
-            return $this->get_one_by_ID($id);
4946
-        }
4947
-    }
4948
-
4949
-
4950
-
4951
-    /**
4952
-     * refresh_entity_map_with
4953
-     * Leaves the entry in the entity map alone, but updates it to match the provided
4954
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4955
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4956
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4957
-     *
4958
-     * @param int|string    $id
4959
-     * @param EE_Base_Class $replacing_model_obj
4960
-     * @return \EE_Base_Class
4961
-     * @throws \EE_Error
4962
-     */
4963
-    public function refresh_entity_map_with($id, $replacing_model_obj)
4964
-    {
4965
-        $obj_in_map = $this->get_from_entity_map($id);
4966
-        if ($obj_in_map) {
4967
-            if ($replacing_model_obj instanceof EE_Base_Class) {
4968
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
4969
-                    $obj_in_map->set($field_name, $value);
4970
-                }
4971
-                //make the model object in the entity map's cache match the $replacing_model_obj
4972
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4973
-                    $obj_in_map->clear_cache($relation_name, null, true);
4974
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
4975
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
4976
-                    }
4977
-                }
4978
-            }
4979
-            return $obj_in_map;
4980
-        } else {
4981
-            $this->add_to_entity_map($replacing_model_obj);
4982
-            return $replacing_model_obj;
4983
-        }
4984
-    }
4985
-
4986
-
4987
-
4988
-    /**
4989
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4990
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4991
-     * require_once($this->_getClassName().".class.php");
4992
-     *
4993
-     * @return string
4994
-     */
4995
-    private function _get_class_name()
4996
-    {
4997
-        return "EE_" . $this->get_this_model_name();
4998
-    }
4999
-
5000
-
5001
-
5002
-    /**
5003
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5004
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5005
-     * it would be 'Events'.
5006
-     *
5007
-     * @param int $quantity
5008
-     * @return string
5009
-     */
5010
-    public function item_name($quantity = 1)
5011
-    {
5012
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5013
-    }
5014
-
5015
-
5016
-
5017
-    /**
5018
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5019
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5020
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5021
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5022
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5023
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5024
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5025
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5026
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5027
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5028
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5029
-     *        return $previousReturnValue.$returnString;
5030
-     * }
5031
-     * require('EEM_Answer.model.php');
5032
-     * $answer=EEM_Answer::instance();
5033
-     * echo $answer->my_callback('monkeys',100);
5034
-     * //will output "you called my_callback! and passed args:monkeys,100"
5035
-     *
5036
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5037
-     * @param array  $args       array of original arguments passed to the function
5038
-     * @throws EE_Error
5039
-     * @return mixed whatever the plugin which calls add_filter decides
5040
-     */
5041
-    public function __call($methodName, $args)
5042
-    {
5043
-        $className = get_class($this);
5044
-        $tagName = "FHEE__{$className}__{$methodName}";
5045
-        if ( ! has_filter($tagName)) {
5046
-            throw new EE_Error(
5047
-                sprintf(
5048
-                    __('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 );',
5049
-                        'event_espresso'),
5050
-                    $methodName,
5051
-                    $className,
5052
-                    $tagName,
5053
-                    '<br />'
5054
-                )
5055
-            );
5056
-        }
5057
-        return apply_filters($tagName, null, $this, $args);
5058
-    }
5059
-
5060
-
5061
-
5062
-    /**
5063
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5064
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5065
-     *
5066
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5067
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5068
-     *                                                       the object's class name
5069
-     *                                                       or object's ID
5070
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5071
-     *                                                       exists in the database. If it does not, we add it
5072
-     * @throws EE_Error
5073
-     * @return EE_Base_Class
5074
-     */
5075
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5076
-    {
5077
-        $className = $this->_get_class_name();
5078
-        if ($base_class_obj_or_id instanceof $className) {
5079
-            $model_object = $base_class_obj_or_id;
5080
-        } else {
5081
-            $primary_key_field = $this->get_primary_key_field();
5082
-            if (
5083
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5084
-                && (
5085
-                    is_int($base_class_obj_or_id)
5086
-                    || is_string($base_class_obj_or_id)
5087
-                )
5088
-            ) {
5089
-                // assume it's an ID.
5090
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5091
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5092
-            } else if (
5093
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5094
-                && is_string($base_class_obj_or_id)
5095
-            ) {
5096
-                // assume its a string representation of the object
5097
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5098
-            } else {
5099
-                throw new EE_Error(
5100
-                    sprintf(
5101
-                        __(
5102
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5103
-                            'event_espresso'
5104
-                        ),
5105
-                        $base_class_obj_or_id,
5106
-                        $this->_get_class_name(),
5107
-                        print_r($base_class_obj_or_id, true)
5108
-                    )
5109
-                );
5110
-            }
5111
-        }
5112
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5113
-            $model_object->save();
5114
-        }
5115
-        return $model_object;
5116
-    }
5117
-
5118
-
5119
-
5120
-    /**
5121
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5122
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5123
-     * returns it ID.
5124
-     *
5125
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5126
-     * @return int|string depending on the type of this model object's ID
5127
-     * @throws EE_Error
5128
-     */
5129
-    public function ensure_is_ID($base_class_obj_or_id)
5130
-    {
5131
-        $className = $this->_get_class_name();
5132
-        if ($base_class_obj_or_id instanceof $className) {
5133
-            /** @var $base_class_obj_or_id EE_Base_Class */
5134
-            $id = $base_class_obj_or_id->ID();
5135
-        } elseif (is_int($base_class_obj_or_id)) {
5136
-            //assume it's an ID
5137
-            $id = $base_class_obj_or_id;
5138
-        } elseif (is_string($base_class_obj_or_id)) {
5139
-            //assume its a string representation of the object
5140
-            $id = $base_class_obj_or_id;
5141
-        } else {
5142
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5143
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5144
-                print_r($base_class_obj_or_id, true)));
5145
-        }
5146
-        return $id;
5147
-    }
5148
-
5149
-
5150
-
5151
-    /**
5152
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5153
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5154
-     * been sanitized and converted into the appropriate domain.
5155
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5156
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5157
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5158
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5159
-     * $EVT = EEM_Event::instance(); $old_setting =
5160
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5161
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5162
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5163
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5164
-     *
5165
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5166
-     * @return void
5167
-     */
5168
-    public function assume_values_already_prepared_by_model_object(
5169
-        $values_already_prepared = self::not_prepared_by_model_object
5170
-    ) {
5171
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5172
-    }
5173
-
5174
-
5175
-
5176
-    /**
5177
-     * Read comments for assume_values_already_prepared_by_model_object()
5178
-     *
5179
-     * @return int
5180
-     */
5181
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5182
-    {
5183
-        return $this->_values_already_prepared_by_model_object;
5184
-    }
5185
-
5186
-
5187
-
5188
-    /**
5189
-     * Gets all the indexes on this model
5190
-     *
5191
-     * @return EE_Index[]
5192
-     */
5193
-    public function indexes()
5194
-    {
5195
-        return $this->_indexes;
5196
-    }
5197
-
5198
-
5199
-
5200
-    /**
5201
-     * Gets all the Unique Indexes on this model
5202
-     *
5203
-     * @return EE_Unique_Index[]
5204
-     */
5205
-    public function unique_indexes()
5206
-    {
5207
-        $unique_indexes = array();
5208
-        foreach ($this->_indexes as $name => $index) {
5209
-            if ($index instanceof EE_Unique_Index) {
5210
-                $unique_indexes [$name] = $index;
5211
-            }
5212
-        }
5213
-        return $unique_indexes;
5214
-    }
5215
-
5216
-
5217
-
5218
-    /**
5219
-     * Gets all the fields which, when combined, make the primary key.
5220
-     * This is usually just an array with 1 element (the primary key), but in cases
5221
-     * where there is no primary key, it's a combination of fields as defined
5222
-     * on a primary index
5223
-     *
5224
-     * @return EE_Model_Field_Base[] indexed by the field's name
5225
-     * @throws \EE_Error
5226
-     */
5227
-    public function get_combined_primary_key_fields()
5228
-    {
5229
-        foreach ($this->indexes() as $index) {
5230
-            if ($index instanceof EE_Primary_Key_Index) {
5231
-                return $index->fields();
5232
-            }
5233
-        }
5234
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5235
-    }
5236
-
5237
-
5238
-
5239
-    /**
5240
-     * Used to build a primary key string (when the model has no primary key),
5241
-     * which can be used a unique string to identify this model object.
5242
-     *
5243
-     * @param array $cols_n_values keys are field names, values are their values
5244
-     * @return string
5245
-     * @throws \EE_Error
5246
-     */
5247
-    public function get_index_primary_key_string($cols_n_values)
5248
-    {
5249
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5250
-            $this->get_combined_primary_key_fields());
5251
-        return http_build_query($cols_n_values_for_primary_key_index);
5252
-    }
5253
-
5254
-
5255
-
5256
-    /**
5257
-     * Gets the field values from the primary key string
5258
-     *
5259
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5260
-     * @param string $index_primary_key_string
5261
-     * @return null|array
5262
-     * @throws \EE_Error
5263
-     */
5264
-    public function parse_index_primary_key_string($index_primary_key_string)
5265
-    {
5266
-        $key_fields = $this->get_combined_primary_key_fields();
5267
-        //check all of them are in the $id
5268
-        $key_vals_in_combined_pk = array();
5269
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5270
-        foreach ($key_fields as $key_field_name => $field_obj) {
5271
-            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5272
-                return null;
5273
-            }
5274
-        }
5275
-        return $key_vals_in_combined_pk;
5276
-    }
5277
-
5278
-
5279
-
5280
-    /**
5281
-     * verifies that an array of key-value pairs for model fields has a key
5282
-     * for each field comprising the primary key index
5283
-     *
5284
-     * @param array $key_vals
5285
-     * @return boolean
5286
-     * @throws \EE_Error
5287
-     */
5288
-    public function has_all_combined_primary_key_fields($key_vals)
5289
-    {
5290
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5291
-        foreach ($keys_it_should_have as $key) {
5292
-            if ( ! isset($key_vals[$key])) {
5293
-                return false;
5294
-            }
5295
-        }
5296
-        return true;
5297
-    }
5298
-
5299
-
5300
-
5301
-    /**
5302
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5303
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5304
-     *
5305
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5306
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5307
-     * @throws EE_Error
5308
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5309
-     *                                                              indexed)
5310
-     */
5311
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5312
-    {
5313
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5314
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5315
-        } elseif (is_array($model_object_or_attributes_array)) {
5316
-            $attributes_array = $model_object_or_attributes_array;
5317
-        } else {
5318
-            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",
5319
-                "event_espresso"), $model_object_or_attributes_array));
5320
-        }
5321
-        //even copies obviously won't have the same ID, so remove the primary key
5322
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5323
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5324
-            unset($attributes_array[$this->primary_key_name()]);
5325
-        }
5326
-        if (isset($query_params[0])) {
5327
-            $query_params[0] = array_merge($attributes_array, $query_params);
5328
-        } else {
5329
-            $query_params[0] = $attributes_array;
5330
-        }
5331
-        return $this->get_all($query_params);
5332
-    }
5333
-
5334
-
5335
-
5336
-    /**
5337
-     * Gets the first copy we find. See get_all_copies for more details
5338
-     *
5339
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5340
-     * @param array $query_params
5341
-     * @return EE_Base_Class
5342
-     * @throws \EE_Error
5343
-     */
5344
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5345
-    {
5346
-        if ( ! is_array($query_params)) {
5347
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5348
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5349
-                    gettype($query_params)), '4.6.0');
5350
-            $query_params = array();
5351
-        }
5352
-        $query_params['limit'] = 1;
5353
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5354
-        if (is_array($copies)) {
5355
-            return array_shift($copies);
5356
-        } else {
5357
-            return null;
5358
-        }
5359
-    }
5360
-
5361
-
5362
-
5363
-    /**
5364
-     * Updates the item with the specified id. Ignores default query parameters because
5365
-     * we have specified the ID, and its assumed we KNOW what we're doing
5366
-     *
5367
-     * @param array      $fields_n_values keys are field names, values are their new values
5368
-     * @param int|string $id              the value of the primary key to update
5369
-     * @return int number of rows updated
5370
-     * @throws \EE_Error
5371
-     */
5372
-    public function update_by_ID($fields_n_values, $id)
5373
-    {
5374
-        $query_params = array(
5375
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5376
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5377
-        );
5378
-        return $this->update($fields_n_values, $query_params);
5379
-    }
5380
-
5381
-
5382
-
5383
-    /**
5384
-     * Changes an operator which was supplied to the models into one usable in SQL
5385
-     *
5386
-     * @param string $operator_supplied
5387
-     * @return string an operator which can be used in SQL
5388
-     * @throws EE_Error
5389
-     */
5390
-    private function _prepare_operator_for_sql($operator_supplied)
5391
-    {
5392
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5393
-            : null;
5394
-        if ($sql_operator) {
5395
-            return $sql_operator;
5396
-        } else {
5397
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5398
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5399
-        }
5400
-    }
5401
-
5402
-
5403
-
5404
-    /**
5405
-     * Gets an array where keys are the primary keys and values are their 'names'
5406
-     * (as determined by the model object's name() function, which is often overridden)
5407
-     *
5408
-     * @param array $query_params like get_all's
5409
-     * @return string[]
5410
-     * @throws \EE_Error
5411
-     */
5412
-    public function get_all_names($query_params = array())
5413
-    {
5414
-        $objs = $this->get_all($query_params);
5415
-        $names = array();
5416
-        foreach ($objs as $obj) {
5417
-            $names[$obj->ID()] = $obj->name();
5418
-        }
5419
-        return $names;
5420
-    }
5421
-
5422
-
5423
-
5424
-    /**
5425
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5426
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5427
-     * this is duplicated effort and reduces efficiency) you would be better to use
5428
-     * array_keys() on $model_objects.
5429
-     *
5430
-     * @param \EE_Base_Class[] $model_objects
5431
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5432
-     *                                               in the returned array
5433
-     * @return array
5434
-     * @throws \EE_Error
5435
-     */
5436
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5437
-    {
5438
-        if ( ! $this->has_primary_key_field()) {
5439
-            if (WP_DEBUG) {
5440
-                EE_Error::add_error(
5441
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5442
-                    __FILE__,
5443
-                    __FUNCTION__,
5444
-                    __LINE__
5445
-                );
5446
-            }
5447
-        }
5448
-        $IDs = array();
5449
-        foreach ($model_objects as $model_object) {
5450
-            $id = $model_object->ID();
5451
-            if ( ! $id) {
5452
-                if ($filter_out_empty_ids) {
5453
-                    continue;
5454
-                }
5455
-                if (WP_DEBUG) {
5456
-                    EE_Error::add_error(
5457
-                        __(
5458
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5459
-                            'event_espresso'
5460
-                        ),
5461
-                        __FILE__,
5462
-                        __FUNCTION__,
5463
-                        __LINE__
5464
-                    );
5465
-                }
5466
-            }
5467
-            $IDs[] = $id;
5468
-        }
5469
-        return $IDs;
5470
-    }
5471
-
5472
-
5473
-
5474
-    /**
5475
-     * Returns the string used in capabilities relating to this model. If there
5476
-     * are no capabilities that relate to this model returns false
5477
-     *
5478
-     * @return string|false
5479
-     */
5480
-    public function cap_slug()
5481
-    {
5482
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5483
-    }
5484
-
5485
-
5486
-
5487
-    /**
5488
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5489
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5490
-     * only returns the cap restrictions array in that context (ie, the array
5491
-     * at that key)
5492
-     *
5493
-     * @param string $context
5494
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5495
-     * @throws \EE_Error
5496
-     */
5497
-    public function cap_restrictions($context = EEM_Base::caps_read)
5498
-    {
5499
-        EEM_Base::verify_is_valid_cap_context($context);
5500
-        //check if we ought to run the restriction generator first
5501
-        if (
5502
-            isset($this->_cap_restriction_generators[$context])
5503
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5504
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5505
-        ) {
5506
-            $this->_cap_restrictions[$context] = array_merge(
5507
-                $this->_cap_restrictions[$context],
5508
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5509
-            );
5510
-        }
5511
-        //and make sure we've finalized the construction of each restriction
5512
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5513
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5514
-                $where_conditions_obj->_finalize_construct($this);
5515
-            }
5516
-        }
5517
-        return $this->_cap_restrictions[$context];
5518
-    }
5519
-
5520
-
5521
-
5522
-    /**
5523
-     * Indicating whether or not this model thinks its a wp core model
5524
-     *
5525
-     * @return boolean
5526
-     */
5527
-    public function is_wp_core_model()
5528
-    {
5529
-        return $this->_wp_core_model;
5530
-    }
5531
-
5532
-
5533
-
5534
-    /**
5535
-     * Gets all the caps that are missing which impose a restriction on
5536
-     * queries made in this context
5537
-     *
5538
-     * @param string $context one of EEM_Base::caps_ constants
5539
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5540
-     * @throws \EE_Error
5541
-     */
5542
-    public function caps_missing($context = EEM_Base::caps_read)
5543
-    {
5544
-        $missing_caps = array();
5545
-        $cap_restrictions = $this->cap_restrictions($context);
5546
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5547
-            if ( ! EE_Capabilities::instance()
5548
-                                  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5549
-            ) {
5550
-                $missing_caps[$cap] = $restriction_if_no_cap;
5551
-            }
5552
-        }
5553
-        return $missing_caps;
5554
-    }
5555
-
5556
-
5557
-
5558
-    /**
5559
-     * Gets the mapping from capability contexts to action strings used in capability names
5560
-     *
5561
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5562
-     * one of 'read', 'edit', or 'delete'
5563
-     */
5564
-    public function cap_contexts_to_cap_action_map()
5565
-    {
5566
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5567
-            $this);
5568
-    }
5569
-
5570
-
5571
-
5572
-    /**
5573
-     * Gets the action string for the specified capability context
5574
-     *
5575
-     * @param string $context
5576
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5577
-     * @throws \EE_Error
5578
-     */
5579
-    public function cap_action_for_context($context)
5580
-    {
5581
-        $mapping = $this->cap_contexts_to_cap_action_map();
5582
-        if (isset($mapping[$context])) {
5583
-            return $mapping[$context];
5584
-        }
5585
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5586
-            return $action;
5587
-        }
5588
-        throw new EE_Error(
5589
-            sprintf(
5590
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5591
-                $context,
5592
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5593
-            )
5594
-        );
5595
-    }
5596
-
5597
-
5598
-
5599
-    /**
5600
-     * Returns all the capability contexts which are valid when querying models
5601
-     *
5602
-     * @return array
5603
-     */
5604
-    public static function valid_cap_contexts()
5605
-    {
5606
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5607
-            self::caps_read,
5608
-            self::caps_read_admin,
5609
-            self::caps_edit,
5610
-            self::caps_delete,
5611
-        ));
5612
-    }
5613
-
5614
-
5615
-
5616
-    /**
5617
-     * Returns all valid options for 'default_where_conditions'
5618
-     * @return array
5619
-     */
5620
-    public static function valid_default_where_conditions()
5621
-    {
5622
-        return array(
5623
-            EEM_Base::default_where_conditions_all,
5624
-            EEM_Base::default_where_conditions_this_only,
5625
-            EEM_Base::default_where_conditions_others_only,
5626
-            EEM_Base::default_where_conditions_minimum_all,
5627
-            EEM_Base::default_where_conditions_minimum_others,
5628
-            EEM_Base::default_where_conditions_none
5629
-        );
5630
-    }
5631
-
5632
-    // public static function default_where_conditions_full
5633
-
5634
-
5635
-
5636
-    /**
5637
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5638
-     *
5639
-     * @param string $context
5640
-     * @return bool
5641
-     * @throws \EE_Error
5642
-     */
5643
-    static public function verify_is_valid_cap_context($context)
5644
-    {
5645
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5646
-        if (in_array($context, $valid_cap_contexts)) {
5647
-            return true;
5648
-        } else {
5649
-            throw new EE_Error(
5650
-                sprintf(
5651
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5652
-                        'event_espresso'),
5653
-                    $context,
5654
-                    'EEM_Base',
5655
-                    implode(',', $valid_cap_contexts)
5656
-                )
5657
-            );
5658
-        }
5659
-    }
5660
-
5661
-
5662
-
5663
-    /**
5664
-     * Clears all the models field caches. This is only useful when a sub-class
5665
-     * might have added a field or something and these caches might be invalidated
5666
-     */
5667
-    protected function _invalidate_field_caches()
5668
-    {
5669
-        $this->_cache_foreign_key_to_fields = array();
5670
-        $this->_cached_fields = null;
5671
-        $this->_cached_fields_non_db_only = null;
5672
-    }
3528
+		}
3529
+		return $null_friendly_where_conditions;
3530
+	}
3531
+
3532
+
3533
+
3534
+	/**
3535
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3536
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3537
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3538
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3539
+	 *
3540
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3541
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3542
+	 */
3543
+	private function _get_default_where_conditions($model_relation_path = null)
3544
+	{
3545
+		if ($this->_ignore_where_strategy) {
3546
+			return array();
3547
+		}
3548
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3549
+	}
3550
+
3551
+
3552
+
3553
+	/**
3554
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3555
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3556
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3557
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3558
+	 * Similar to _get_default_where_conditions
3559
+	 *
3560
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3561
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3562
+	 */
3563
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3564
+	{
3565
+		if ($this->_ignore_where_strategy) {
3566
+			return array();
3567
+		}
3568
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3569
+	}
3570
+
3571
+
3572
+
3573
+	/**
3574
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3575
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3576
+	 *
3577
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3578
+	 * @return string
3579
+	 * @throws \EE_Error
3580
+	 */
3581
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3582
+	{
3583
+		$selects = $this->_get_columns_to_select_for_this_model();
3584
+		foreach (
3585
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3586
+			$name_of_other_model_included
3587
+		) {
3588
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3589
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3590
+			foreach ($other_model_selects as $key => $value) {
3591
+				$selects[] = $value;
3592
+			}
3593
+		}
3594
+		return implode(", ", $selects);
3595
+	}
3596
+
3597
+
3598
+
3599
+	/**
3600
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3601
+	 * So that's going to be the columns for all the fields on the model
3602
+	 *
3603
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3604
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3605
+	 */
3606
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3607
+	{
3608
+		$fields = $this->field_settings();
3609
+		$selects = array();
3610
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3611
+			$this->get_this_model_name());
3612
+		foreach ($fields as $field_obj) {
3613
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3614
+						 . $field_obj->get_table_alias()
3615
+						 . "."
3616
+						 . $field_obj->get_table_column()
3617
+						 . " AS '"
3618
+						 . $table_alias_with_model_relation_chain_prefix
3619
+						 . $field_obj->get_table_alias()
3620
+						 . "."
3621
+						 . $field_obj->get_table_column()
3622
+						 . "'";
3623
+		}
3624
+		//make sure we are also getting the PKs of each table
3625
+		$tables = $this->get_tables();
3626
+		if (count($tables) > 1) {
3627
+			foreach ($tables as $table_obj) {
3628
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3629
+									   . $table_obj->get_fully_qualified_pk_column();
3630
+				if ( ! in_array($qualified_pk_column, $selects)) {
3631
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3632
+				}
3633
+			}
3634
+		}
3635
+		return $selects;
3636
+	}
3637
+
3638
+
3639
+
3640
+	/**
3641
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3642
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3643
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3644
+	 * SQL for joining, and the data types
3645
+	 *
3646
+	 * @param null|string                 $original_query_param
3647
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3648
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3649
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3650
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3651
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3652
+	 *                                                          or 'Registration's
3653
+	 * @param string                      $original_query_param what it originally was (eg
3654
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3655
+	 *                                                          matches $query_param
3656
+	 * @throws EE_Error
3657
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3658
+	 */
3659
+	private function _extract_related_model_info_from_query_param(
3660
+		$query_param,
3661
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3662
+		$query_param_type,
3663
+		$original_query_param = null
3664
+	) {
3665
+		if ($original_query_param === null) {
3666
+			$original_query_param = $query_param;
3667
+		}
3668
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3669
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3670
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3671
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3672
+		//check to see if we have a field on this model
3673
+		$this_model_fields = $this->field_settings(true);
3674
+		if (array_key_exists($query_param, $this_model_fields)) {
3675
+			if ($allow_fields) {
3676
+				return;
3677
+			} else {
3678
+				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",
3679
+					"event_espresso"),
3680
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3681
+			}
3682
+		} //check if this is a special logic query param
3683
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3684
+			if ($allow_logic_query_params) {
3685
+				return;
3686
+			} else {
3687
+				throw new EE_Error(
3688
+					sprintf(
3689
+						__('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',
3690
+							'event_espresso'),
3691
+						implode('", "', $this->_logic_query_param_keys),
3692
+						$query_param,
3693
+						get_class($this),
3694
+						'<br />',
3695
+						"\t"
3696
+						. ' $passed_in_query_info = <pre>'
3697
+						. print_r($passed_in_query_info, true)
3698
+						. '</pre>'
3699
+						. "\n\t"
3700
+						. ' $query_param_type = '
3701
+						. $query_param_type
3702
+						. "\n\t"
3703
+						. ' $original_query_param = '
3704
+						. $original_query_param
3705
+					)
3706
+				);
3707
+			}
3708
+		} //check if it's a custom selection
3709
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3710
+			return;
3711
+		}
3712
+		//check if has a model name at the beginning
3713
+		//and
3714
+		//check if it's a field on a related model
3715
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3716
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3717
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3718
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3719
+				if ($query_param === '') {
3720
+					//nothing left to $query_param
3721
+					//we should actually end in a field name, not a model like this!
3722
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3723
+						"event_espresso"),
3724
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3725
+				} else {
3726
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3727
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3728
+						$passed_in_query_info, $query_param_type, $original_query_param);
3729
+					return;
3730
+				}
3731
+			} elseif ($query_param === $valid_related_model_name) {
3732
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3733
+				return;
3734
+			}
3735
+		}
3736
+		//ok so $query_param didn't start with a model name
3737
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3738
+		//it's wack, that's what it is
3739
+		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",
3740
+			"event_espresso"),
3741
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3742
+	}
3743
+
3744
+
3745
+
3746
+	/**
3747
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3748
+	 * and store it on $passed_in_query_info
3749
+	 *
3750
+	 * @param string                      $model_name
3751
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3752
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3753
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3754
+	 *                                                          and are adding a join to 'Payment' with the original
3755
+	 *                                                          query param key
3756
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3757
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3758
+	 *                                                          Payment wants to add default query params so that it
3759
+	 *                                                          will know what models to prepend onto its default query
3760
+	 *                                                          params or in case it wants to rename tables (in case
3761
+	 *                                                          there are multiple joins to the same table)
3762
+	 * @return void
3763
+	 * @throws \EE_Error
3764
+	 */
3765
+	private function _add_join_to_model(
3766
+		$model_name,
3767
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3768
+		$original_query_param
3769
+	) {
3770
+		$relation_obj = $this->related_settings_for($model_name);
3771
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3772
+		//check if the relation is HABTM, because then we're essentially doing two joins
3773
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3774
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3775
+			$join_model_obj = $relation_obj->get_join_model();
3776
+			//replace the model specified with the join model for this relation chain, whi
3777
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3778
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3779
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3780
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3781
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3782
+			$passed_in_query_info->merge($new_query_info);
3783
+		}
3784
+		//now just join to the other table pointed to by the relation object, and add its data types
3785
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3786
+			array($model_relation_chain => $model_name),
3787
+			$relation_obj->get_join_statement($model_relation_chain));
3788
+		$passed_in_query_info->merge($new_query_info);
3789
+	}
3790
+
3791
+
3792
+
3793
+	/**
3794
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3795
+	 *
3796
+	 * @param array $where_params like EEM_Base::get_all
3797
+	 * @return string of SQL
3798
+	 * @throws \EE_Error
3799
+	 */
3800
+	private function _construct_where_clause($where_params)
3801
+	{
3802
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3803
+		if ($SQL) {
3804
+			return " WHERE " . $SQL;
3805
+		} else {
3806
+			return '';
3807
+		}
3808
+	}
3809
+
3810
+
3811
+
3812
+	/**
3813
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3814
+	 * and should be passed HAVING parameters, not WHERE parameters
3815
+	 *
3816
+	 * @param array $having_params
3817
+	 * @return string
3818
+	 * @throws \EE_Error
3819
+	 */
3820
+	private function _construct_having_clause($having_params)
3821
+	{
3822
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3823
+		if ($SQL) {
3824
+			return " HAVING " . $SQL;
3825
+		} else {
3826
+			return '';
3827
+		}
3828
+	}
3829
+
3830
+
3831
+
3832
+	/**
3833
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3834
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3835
+	 * EEM_Attendee.
3836
+	 *
3837
+	 * @param string $field_name
3838
+	 * @param string $model_name
3839
+	 * @return EE_Model_Field_Base
3840
+	 * @throws EE_Error
3841
+	 */
3842
+	protected function _get_field_on_model($field_name, $model_name)
3843
+	{
3844
+		$model_class = 'EEM_' . $model_name;
3845
+		$model_filepath = $model_class . ".model.php";
3846
+		if (is_readable($model_filepath)) {
3847
+			require_once($model_filepath);
3848
+			$model_instance = call_user_func($model_name . "::instance");
3849
+			/* @var $model_instance EEM_Base */
3850
+			return $model_instance->field_settings_for($field_name);
3851
+		} else {
3852
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3853
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3854
+		}
3855
+	}
3856
+
3857
+
3858
+
3859
+	/**
3860
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3861
+	 * Event_Meta.meta_value = 'foo'))"
3862
+	 *
3863
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3864
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3865
+	 * @throws EE_Error
3866
+	 * @return string of SQL
3867
+	 */
3868
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3869
+	{
3870
+		$where_clauses = array();
3871
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3872
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3873
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3874
+				switch ($query_param) {
3875
+					case 'not':
3876
+					case 'NOT':
3877
+						$where_clauses[] = "! ("
3878
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3879
+								$glue)
3880
+										   . ")";
3881
+						break;
3882
+					case 'and':
3883
+					case 'AND':
3884
+						$where_clauses[] = " ("
3885
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3886
+								' AND ')
3887
+										   . ")";
3888
+						break;
3889
+					case 'or':
3890
+					case 'OR':
3891
+						$where_clauses[] = " ("
3892
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3893
+								' OR ')
3894
+										   . ")";
3895
+						break;
3896
+				}
3897
+			} else {
3898
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3899
+				//if it's not a normal field, maybe it's a custom selection?
3900
+				if ( ! $field_obj) {
3901
+					if (isset($this->_custom_selections[$query_param][1])) {
3902
+						$field_obj = $this->_custom_selections[$query_param][1];
3903
+					} else {
3904
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3905
+							"event_espresso"), $query_param));
3906
+					}
3907
+				}
3908
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3909
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3910
+			}
3911
+		}
3912
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3913
+	}
3914
+
3915
+
3916
+
3917
+	/**
3918
+	 * Takes the input parameter and extract the table name (alias) and column name
3919
+	 *
3920
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3921
+	 * @throws EE_Error
3922
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3923
+	 */
3924
+	private function _deduce_column_name_from_query_param($query_param)
3925
+	{
3926
+		$field = $this->_deduce_field_from_query_param($query_param);
3927
+		if ($field) {
3928
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3929
+				$query_param);
3930
+			return $table_alias_prefix . $field->get_qualified_column();
3931
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
3932
+			//maybe it's custom selection item?
3933
+			//if so, just use it as the "column name"
3934
+			return $query_param;
3935
+		} else {
3936
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
3937
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
3938
+		}
3939
+	}
3940
+
3941
+
3942
+
3943
+	/**
3944
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
3945
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
3946
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3947
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3948
+	 *
3949
+	 * @param string $condition_query_param_key
3950
+	 * @return string
3951
+	 */
3952
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
3953
+	{
3954
+		$pos_of_star = strpos($condition_query_param_key, '*');
3955
+		if ($pos_of_star === false) {
3956
+			return $condition_query_param_key;
3957
+		} else {
3958
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3959
+			return $condition_query_param_sans_star;
3960
+		}
3961
+	}
3962
+
3963
+
3964
+
3965
+	/**
3966
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3967
+	 *
3968
+	 * @param                            mixed      array | string    $op_and_value
3969
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3970
+	 * @throws EE_Error
3971
+	 * @return string
3972
+	 */
3973
+	private function _construct_op_and_value($op_and_value, $field_obj)
3974
+	{
3975
+		if (is_array($op_and_value)) {
3976
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
3977
+			if ( ! $operator) {
3978
+				$php_array_like_string = array();
3979
+				foreach ($op_and_value as $key => $value) {
3980
+					$php_array_like_string[] = "$key=>$value";
3981
+				}
3982
+				throw new EE_Error(
3983
+					sprintf(
3984
+						__(
3985
+							"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))",
3986
+							"event_espresso"
3987
+						),
3988
+						implode(",", $php_array_like_string)
3989
+					)
3990
+				);
3991
+			}
3992
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
3993
+		} else {
3994
+			$operator = '=';
3995
+			$value = $op_and_value;
3996
+		}
3997
+		//check to see if the value is actually another field
3998
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3999
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4000
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4001
+			//in this case, the value should be an array, or at least a comma-separated list
4002
+			//it will need to handle a little differently
4003
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4004
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4005
+			return $operator . SP . $cleaned_value;
4006
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4007
+			//the value should be an array with count of two.
4008
+			if (count($value) !== 2) {
4009
+				throw new EE_Error(
4010
+					sprintf(
4011
+						__(
4012
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4013
+							'event_espresso'
4014
+						),
4015
+						"BETWEEN"
4016
+					)
4017
+				);
4018
+			}
4019
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4020
+			return $operator . SP . $cleaned_value;
4021
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4022
+			if ($value !== null) {
4023
+				throw new EE_Error(
4024
+					sprintf(
4025
+						__(
4026
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4027
+							"event_espresso"
4028
+						),
4029
+						$value,
4030
+						$operator
4031
+					)
4032
+				);
4033
+			}
4034
+			return $operator;
4035
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4036
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4037
+			//remove other junk. So just treat it as a string.
4038
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4039
+		} elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4040
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4041
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4042
+			throw new EE_Error(
4043
+				sprintf(
4044
+					__(
4045
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4046
+						'event_espresso'
4047
+					),
4048
+					$operator,
4049
+					$operator
4050
+				)
4051
+			);
4052
+		} elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4053
+			throw new EE_Error(
4054
+				sprintf(
4055
+					__(
4056
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4057
+						'event_espresso'
4058
+					),
4059
+					$operator,
4060
+					$operator
4061
+				)
4062
+			);
4063
+		} else {
4064
+			throw new EE_Error(
4065
+				sprintf(
4066
+					__(
4067
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4068
+						"event_espresso"
4069
+					),
4070
+					http_build_query($op_and_value)
4071
+				)
4072
+			);
4073
+		}
4074
+	}
4075
+
4076
+
4077
+
4078
+	/**
4079
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4080
+	 *
4081
+	 * @param array                      $values
4082
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4083
+	 *                                              '%s'
4084
+	 * @return string
4085
+	 * @throws \EE_Error
4086
+	 */
4087
+	public function _construct_between_value($values, $field_obj)
4088
+	{
4089
+		$cleaned_values = array();
4090
+		foreach ($values as $value) {
4091
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4092
+		}
4093
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4094
+	}
4095
+
4096
+
4097
+
4098
+	/**
4099
+	 * Takes an array or a comma-separated list of $values and cleans them
4100
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4101
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4102
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4103
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4104
+	 *
4105
+	 * @param mixed                      $values    array or comma-separated string
4106
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4107
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4108
+	 * @throws \EE_Error
4109
+	 */
4110
+	public function _construct_in_value($values, $field_obj)
4111
+	{
4112
+		//check if the value is a CSV list
4113
+		if (is_string($values)) {
4114
+			//in which case, turn it into an array
4115
+			$values = explode(",", $values);
4116
+		}
4117
+		$cleaned_values = array();
4118
+		foreach ($values as $value) {
4119
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4120
+		}
4121
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4122
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4123
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4124
+		if (empty($cleaned_values)) {
4125
+			$all_fields = $this->field_settings();
4126
+			$a_field = array_shift($all_fields);
4127
+			$main_table = $this->_get_main_table();
4128
+			$cleaned_values[] = "SELECT "
4129
+								. $a_field->get_table_column()
4130
+								. " FROM "
4131
+								. $main_table->get_table_name()
4132
+								. " WHERE FALSE";
4133
+		}
4134
+		return "(" . implode(",", $cleaned_values) . ")";
4135
+	}
4136
+
4137
+
4138
+
4139
+	/**
4140
+	 * @param mixed                      $value
4141
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4142
+	 * @throws EE_Error
4143
+	 * @return false|null|string
4144
+	 */
4145
+	private function _wpdb_prepare_using_field($value, $field_obj)
4146
+	{
4147
+		/** @type WPDB $wpdb */
4148
+		global $wpdb;
4149
+		if ($field_obj instanceof EE_Model_Field_Base) {
4150
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4151
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4152
+		} else {//$field_obj should really just be a data type
4153
+			if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4154
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4155
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4156
+			}
4157
+			return $wpdb->prepare($field_obj, $value);
4158
+		}
4159
+	}
4160
+
4161
+
4162
+
4163
+	/**
4164
+	 * Takes the input parameter and finds the model field that it indicates.
4165
+	 *
4166
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4167
+	 * @throws EE_Error
4168
+	 * @return EE_Model_Field_Base
4169
+	 */
4170
+	protected function _deduce_field_from_query_param($query_param_name)
4171
+	{
4172
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4173
+		//which will help us find the database table and column
4174
+		$query_param_parts = explode(".", $query_param_name);
4175
+		if (empty($query_param_parts)) {
4176
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4177
+				'event_espresso'), $query_param_name));
4178
+		}
4179
+		$number_of_parts = count($query_param_parts);
4180
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4181
+		if ($number_of_parts === 1) {
4182
+			$field_name = $last_query_param_part;
4183
+			$model_obj = $this;
4184
+		} else {// $number_of_parts >= 2
4185
+			//the last part is the column name, and there are only 2parts. therefore...
4186
+			$field_name = $last_query_param_part;
4187
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4188
+		}
4189
+		try {
4190
+			return $model_obj->field_settings_for($field_name);
4191
+		} catch (EE_Error $e) {
4192
+			return null;
4193
+		}
4194
+	}
4195
+
4196
+
4197
+
4198
+	/**
4199
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4200
+	 * alias and column which corresponds to it
4201
+	 *
4202
+	 * @param string $field_name
4203
+	 * @throws EE_Error
4204
+	 * @return string
4205
+	 */
4206
+	public function _get_qualified_column_for_field($field_name)
4207
+	{
4208
+		$all_fields = $this->field_settings();
4209
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4210
+		if ($field) {
4211
+			return $field->get_qualified_column();
4212
+		} else {
4213
+			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.",
4214
+				'event_espresso'), $field_name, get_class($this)));
4215
+		}
4216
+	}
4217
+
4218
+
4219
+
4220
+	/**
4221
+	 * constructs the select use on special limit joins
4222
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4223
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4224
+	 * (as that is typically where the limits would be set).
4225
+	 *
4226
+	 * @param  string       $table_alias The table the select is being built for
4227
+	 * @param  mixed|string $limit       The limit for this select
4228
+	 * @return string                The final select join element for the query.
4229
+	 */
4230
+	public function _construct_limit_join_select($table_alias, $limit)
4231
+	{
4232
+		$SQL = '';
4233
+		foreach ($this->_tables as $table_obj) {
4234
+			if ($table_obj instanceof EE_Primary_Table) {
4235
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4236
+					? $table_obj->get_select_join_limit($limit)
4237
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4238
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4239
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4240
+					? $table_obj->get_select_join_limit_join($limit)
4241
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4242
+			}
4243
+		}
4244
+		return $SQL;
4245
+	}
4246
+
4247
+
4248
+
4249
+	/**
4250
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4251
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4252
+	 *
4253
+	 * @return string SQL
4254
+	 * @throws \EE_Error
4255
+	 */
4256
+	public function _construct_internal_join()
4257
+	{
4258
+		$SQL = $this->_get_main_table()->get_table_sql();
4259
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4260
+		return $SQL;
4261
+	}
4262
+
4263
+
4264
+
4265
+	/**
4266
+	 * Constructs the SQL for joining all the tables on this model.
4267
+	 * Normally $alias should be the primary table's alias, but in cases where
4268
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4269
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4270
+	 * alias, this will construct SQL like:
4271
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4272
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4273
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4274
+	 *
4275
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4276
+	 * @return string
4277
+	 */
4278
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4279
+	{
4280
+		$SQL = '';
4281
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4282
+		foreach ($this->_tables as $table_obj) {
4283
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4284
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4285
+					//so we're joining to this table, meaning the table is already in
4286
+					//the FROM statement, BUT the primary table isn't. So we want
4287
+					//to add the inverse join sql
4288
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4289
+				} else {
4290
+					//just add a regular JOIN to this table from the primary table
4291
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4292
+				}
4293
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4294
+		}
4295
+		return $SQL;
4296
+	}
4297
+
4298
+
4299
+
4300
+	/**
4301
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4302
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4303
+	 * their data type (eg, '%s', '%d', etc)
4304
+	 *
4305
+	 * @return array
4306
+	 */
4307
+	public function _get_data_types()
4308
+	{
4309
+		$data_types = array();
4310
+		foreach ($this->field_settings() as $field_obj) {
4311
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4312
+			/** @var $field_obj EE_Model_Field_Base */
4313
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4314
+		}
4315
+		return $data_types;
4316
+	}
4317
+
4318
+
4319
+
4320
+	/**
4321
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4322
+	 *
4323
+	 * @param string $model_name
4324
+	 * @throws EE_Error
4325
+	 * @return EEM_Base
4326
+	 */
4327
+	public function get_related_model_obj($model_name)
4328
+	{
4329
+		$model_classname = "EEM_" . $model_name;
4330
+		if ( ! class_exists($model_classname)) {
4331
+			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",
4332
+				'event_espresso'), $model_name, $model_classname));
4333
+		}
4334
+		return call_user_func($model_classname . "::instance");
4335
+	}
4336
+
4337
+
4338
+
4339
+	/**
4340
+	 * Returns the array of EE_ModelRelations for this model.
4341
+	 *
4342
+	 * @return EE_Model_Relation_Base[]
4343
+	 */
4344
+	public function relation_settings()
4345
+	{
4346
+		return $this->_model_relations;
4347
+	}
4348
+
4349
+
4350
+
4351
+	/**
4352
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4353
+	 * because without THOSE models, this model probably doesn't have much purpose.
4354
+	 * (Eg, without an event, datetimes have little purpose.)
4355
+	 *
4356
+	 * @return EE_Belongs_To_Relation[]
4357
+	 */
4358
+	public function belongs_to_relations()
4359
+	{
4360
+		$belongs_to_relations = array();
4361
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4362
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4363
+				$belongs_to_relations[$model_name] = $relation_obj;
4364
+			}
4365
+		}
4366
+		return $belongs_to_relations;
4367
+	}
4368
+
4369
+
4370
+
4371
+	/**
4372
+	 * Returns the specified EE_Model_Relation, or throws an exception
4373
+	 *
4374
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4375
+	 * @throws EE_Error
4376
+	 * @return EE_Model_Relation_Base
4377
+	 */
4378
+	public function related_settings_for($relation_name)
4379
+	{
4380
+		$relatedModels = $this->relation_settings();
4381
+		if ( ! array_key_exists($relation_name, $relatedModels)) {
4382
+			throw new EE_Error(
4383
+				sprintf(
4384
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4385
+						'event_espresso'),
4386
+					$relation_name,
4387
+					$this->_get_class_name(),
4388
+					implode(', ', array_keys($relatedModels))
4389
+				)
4390
+			);
4391
+		}
4392
+		return $relatedModels[$relation_name];
4393
+	}
4394
+
4395
+
4396
+
4397
+	/**
4398
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4399
+	 * fields
4400
+	 *
4401
+	 * @param string $fieldName
4402
+	 * @throws EE_Error
4403
+	 * @return EE_Model_Field_Base
4404
+	 */
4405
+	public function field_settings_for($fieldName)
4406
+	{
4407
+		$fieldSettings = $this->field_settings(true);
4408
+		if ( ! array_key_exists($fieldName, $fieldSettings)) {
4409
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4410
+				get_class($this)));
4411
+		}
4412
+		return $fieldSettings[$fieldName];
4413
+	}
4414
+
4415
+
4416
+
4417
+	/**
4418
+	 * Checks if this field exists on this model
4419
+	 *
4420
+	 * @param string $fieldName a key in the model's _field_settings array
4421
+	 * @return boolean
4422
+	 */
4423
+	public function has_field($fieldName)
4424
+	{
4425
+		$fieldSettings = $this->field_settings(true);
4426
+		if (isset($fieldSettings[$fieldName])) {
4427
+			return true;
4428
+		} else {
4429
+			return false;
4430
+		}
4431
+	}
4432
+
4433
+
4434
+
4435
+	/**
4436
+	 * Returns whether or not this model has a relation to the specified model
4437
+	 *
4438
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4439
+	 * @return boolean
4440
+	 */
4441
+	public function has_relation($relation_name)
4442
+	{
4443
+		$relations = $this->relation_settings();
4444
+		if (isset($relations[$relation_name])) {
4445
+			return true;
4446
+		} else {
4447
+			return false;
4448
+		}
4449
+	}
4450
+
4451
+
4452
+
4453
+	/**
4454
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4455
+	 * Eg, on EE_Answer that would be ANS_ID field object
4456
+	 *
4457
+	 * @param $field_obj
4458
+	 * @return boolean
4459
+	 */
4460
+	public function is_primary_key_field($field_obj)
4461
+	{
4462
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4463
+	}
4464
+
4465
+
4466
+
4467
+	/**
4468
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4469
+	 * Eg, on EE_Answer that would be ANS_ID field object
4470
+	 *
4471
+	 * @return EE_Model_Field_Base
4472
+	 * @throws EE_Error
4473
+	 */
4474
+	public function get_primary_key_field()
4475
+	{
4476
+		if ($this->_primary_key_field === null) {
4477
+			foreach ($this->field_settings(true) as $field_obj) {
4478
+				if ($this->is_primary_key_field($field_obj)) {
4479
+					$this->_primary_key_field = $field_obj;
4480
+					break;
4481
+				}
4482
+			}
4483
+			if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4484
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4485
+					get_class($this)));
4486
+			}
4487
+		}
4488
+		return $this->_primary_key_field;
4489
+	}
4490
+
4491
+
4492
+
4493
+	/**
4494
+	 * Returns whether or not not there is a primary key on this model.
4495
+	 * Internally does some caching.
4496
+	 *
4497
+	 * @return boolean
4498
+	 */
4499
+	public function has_primary_key_field()
4500
+	{
4501
+		if ($this->_has_primary_key_field === null) {
4502
+			try {
4503
+				$this->get_primary_key_field();
4504
+				$this->_has_primary_key_field = true;
4505
+			} catch (EE_Error $e) {
4506
+				$this->_has_primary_key_field = false;
4507
+			}
4508
+		}
4509
+		return $this->_has_primary_key_field;
4510
+	}
4511
+
4512
+
4513
+
4514
+	/**
4515
+	 * Finds the first field of type $field_class_name.
4516
+	 *
4517
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4518
+	 *                                 EE_Foreign_Key_Field, etc
4519
+	 * @return EE_Model_Field_Base or null if none is found
4520
+	 */
4521
+	public function get_a_field_of_type($field_class_name)
4522
+	{
4523
+		foreach ($this->field_settings() as $field) {
4524
+			if ($field instanceof $field_class_name) {
4525
+				return $field;
4526
+			}
4527
+		}
4528
+		return null;
4529
+	}
4530
+
4531
+
4532
+
4533
+	/**
4534
+	 * Gets a foreign key field pointing to model.
4535
+	 *
4536
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4537
+	 * @return EE_Foreign_Key_Field_Base
4538
+	 * @throws EE_Error
4539
+	 */
4540
+	public function get_foreign_key_to($model_name)
4541
+	{
4542
+		if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4543
+			foreach ($this->field_settings() as $field) {
4544
+				if (
4545
+					$field instanceof EE_Foreign_Key_Field_Base
4546
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4547
+				) {
4548
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4549
+					break;
4550
+				}
4551
+			}
4552
+			if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4553
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4554
+					'event_espresso'), $model_name, get_class($this)));
4555
+			}
4556
+		}
4557
+		return $this->_cache_foreign_key_to_fields[$model_name];
4558
+	}
4559
+
4560
+
4561
+
4562
+	/**
4563
+	 * Gets the actual table for the table alias
4564
+	 *
4565
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4566
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4567
+	 *                            Either one works
4568
+	 * @return EE_Table_Base
4569
+	 */
4570
+	public function get_table_for_alias($table_alias)
4571
+	{
4572
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4573
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4574
+	}
4575
+
4576
+
4577
+
4578
+	/**
4579
+	 * Returns a flat array of all field son this model, instead of organizing them
4580
+	 * by table_alias as they are in the constructor.
4581
+	 *
4582
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4583
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4584
+	 */
4585
+	public function field_settings($include_db_only_fields = false)
4586
+	{
4587
+		if ($include_db_only_fields) {
4588
+			if ($this->_cached_fields === null) {
4589
+				$this->_cached_fields = array();
4590
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4591
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4592
+						$this->_cached_fields[$field_name] = $field_obj;
4593
+					}
4594
+				}
4595
+			}
4596
+			return $this->_cached_fields;
4597
+		} else {
4598
+			if ($this->_cached_fields_non_db_only === null) {
4599
+				$this->_cached_fields_non_db_only = array();
4600
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4601
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4602
+						/** @var $field_obj EE_Model_Field_Base */
4603
+						if ( ! $field_obj->is_db_only_field()) {
4604
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4605
+						}
4606
+					}
4607
+				}
4608
+			}
4609
+			return $this->_cached_fields_non_db_only;
4610
+		}
4611
+	}
4612
+
4613
+
4614
+
4615
+	/**
4616
+	 *        cycle though array of attendees and create objects out of each item
4617
+	 *
4618
+	 * @access        private
4619
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4620
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4621
+	 *                           numerically indexed)
4622
+	 * @throws \EE_Error
4623
+	 */
4624
+	protected function _create_objects($rows = array())
4625
+	{
4626
+		$array_of_objects = array();
4627
+		if (empty($rows)) {
4628
+			return array();
4629
+		}
4630
+		$count_if_model_has_no_primary_key = 0;
4631
+		$has_primary_key = $this->has_primary_key_field();
4632
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4633
+		foreach ((array)$rows as $row) {
4634
+			if (empty($row)) {
4635
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4636
+				return array();
4637
+			}
4638
+			//check if we've already set this object in the results array,
4639
+			//in which case there's no need to process it further (again)
4640
+			if ($has_primary_key) {
4641
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4642
+					$row,
4643
+					$primary_key_field->get_qualified_column(),
4644
+					$primary_key_field->get_table_column()
4645
+				);
4646
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4647
+					continue;
4648
+				}
4649
+			}
4650
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4651
+			if ( ! $classInstance) {
4652
+				throw new EE_Error(
4653
+					sprintf(
4654
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4655
+						$this->get_this_model_name(),
4656
+						http_build_query($row)
4657
+					)
4658
+				);
4659
+			}
4660
+			//set the timezone on the instantiated objects
4661
+			$classInstance->set_timezone($this->_timezone);
4662
+			//make sure if there is any timezone setting present that we set the timezone for the object
4663
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4664
+			$array_of_objects[$key] = $classInstance;
4665
+			//also, for all the relations of type BelongsTo, see if we can cache
4666
+			//those related models
4667
+			//(we could do this for other relations too, but if there are conditions
4668
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4669
+			//so it requires a little more thought than just caching them immediately...)
4670
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4671
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4672
+					//check if this model's INFO is present. If so, cache it on the model
4673
+					$other_model = $relation_obj->get_other_model();
4674
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4675
+					//if we managed to make a model object from the results, cache it on the main model object
4676
+					if ($other_model_obj_maybe) {
4677
+						//set timezone on these other model objects if they are present
4678
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4679
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4680
+					}
4681
+				}
4682
+			}
4683
+		}
4684
+		return $array_of_objects;
4685
+	}
4686
+
4687
+
4688
+
4689
+	/**
4690
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4691
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4692
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4693
+	 * object (as set in the model_field!).
4694
+	 *
4695
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4696
+	 */
4697
+	public function create_default_object()
4698
+	{
4699
+		$this_model_fields_and_values = array();
4700
+		//setup the row using default values;
4701
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4702
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4703
+		}
4704
+		$className = $this->_get_class_name();
4705
+		$classInstance = EE_Registry::instance()
4706
+									->load_class($className, array($this_model_fields_and_values), false, false);
4707
+		return $classInstance;
4708
+	}
4709
+
4710
+
4711
+
4712
+	/**
4713
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4714
+	 *                             or an stdClass where each property is the name of a column,
4715
+	 * @return EE_Base_Class
4716
+	 * @throws \EE_Error
4717
+	 */
4718
+	public function instantiate_class_from_array_or_object($cols_n_values)
4719
+	{
4720
+		if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4721
+			$cols_n_values = get_object_vars($cols_n_values);
4722
+		}
4723
+		$primary_key = null;
4724
+		//make sure the array only has keys that are fields/columns on this model
4725
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4726
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4727
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4728
+		}
4729
+		$className = $this->_get_class_name();
4730
+		//check we actually found results that we can use to build our model object
4731
+		//if not, return null
4732
+		if ($this->has_primary_key_field()) {
4733
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4734
+				return null;
4735
+			}
4736
+		} else if ($this->unique_indexes()) {
4737
+			$first_column = reset($this_model_fields_n_values);
4738
+			if (empty($first_column)) {
4739
+				return null;
4740
+			}
4741
+		}
4742
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4743
+		if ($primary_key) {
4744
+			$classInstance = $this->get_from_entity_map($primary_key);
4745
+			if ( ! $classInstance) {
4746
+				$classInstance = EE_Registry::instance()
4747
+											->load_class($className,
4748
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4749
+				// add this new object to the entity map
4750
+				$classInstance = $this->add_to_entity_map($classInstance);
4751
+			}
4752
+		} else {
4753
+			$classInstance = EE_Registry::instance()
4754
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4755
+											true, false);
4756
+		}
4757
+		//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.
4758
+		$this->set_timezone($classInstance->get_timezone());
4759
+		return $classInstance;
4760
+	}
4761
+
4762
+
4763
+
4764
+	/**
4765
+	 * Gets the model object from the  entity map if it exists
4766
+	 *
4767
+	 * @param int|string $id the ID of the model object
4768
+	 * @return EE_Base_Class
4769
+	 */
4770
+	public function get_from_entity_map($id)
4771
+	{
4772
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4773
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4774
+	}
4775
+
4776
+
4777
+
4778
+	/**
4779
+	 * add_to_entity_map
4780
+	 * Adds the object to the model's entity mappings
4781
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4782
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4783
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4784
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4785
+	 *        then this method should be called immediately after the update query
4786
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4787
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4788
+	 *
4789
+	 * @param    EE_Base_Class $object
4790
+	 * @throws EE_Error
4791
+	 * @return \EE_Base_Class
4792
+	 */
4793
+	public function add_to_entity_map(EE_Base_Class $object)
4794
+	{
4795
+		$className = $this->_get_class_name();
4796
+		if ( ! $object instanceof $className) {
4797
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4798
+				is_object($object) ? get_class($object) : $object, $className));
4799
+		}
4800
+		/** @var $object EE_Base_Class */
4801
+		if ( ! $object->ID()) {
4802
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4803
+				"event_espresso"), get_class($this)));
4804
+		}
4805
+		// double check it's not already there
4806
+		$classInstance = $this->get_from_entity_map($object->ID());
4807
+		if ($classInstance) {
4808
+			return $classInstance;
4809
+		} else {
4810
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4811
+			return $object;
4812
+		}
4813
+	}
4814
+
4815
+
4816
+
4817
+	/**
4818
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4819
+	 * if no identifier is provided, then the entire entity map is emptied
4820
+	 *
4821
+	 * @param int|string $id the ID of the model object
4822
+	 * @return boolean
4823
+	 */
4824
+	public function clear_entity_map($id = null)
4825
+	{
4826
+		if (empty($id)) {
4827
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4828
+			return true;
4829
+		}
4830
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4831
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4832
+			return true;
4833
+		}
4834
+		return false;
4835
+	}
4836
+
4837
+
4838
+
4839
+	/**
4840
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4841
+	 * Given an array where keys are column (or column alias) names and values,
4842
+	 * returns an array of their corresponding field names and database values
4843
+	 *
4844
+	 * @param array $cols_n_values
4845
+	 * @return array
4846
+	 */
4847
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4848
+	{
4849
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4850
+	}
4851
+
4852
+
4853
+
4854
+	/**
4855
+	 * _deduce_fields_n_values_from_cols_n_values
4856
+	 * Given an array where keys are column (or column alias) names and values,
4857
+	 * returns an array of their corresponding field names and database values
4858
+	 *
4859
+	 * @param string $cols_n_values
4860
+	 * @return array
4861
+	 */
4862
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4863
+	{
4864
+		$this_model_fields_n_values = array();
4865
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
4866
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4867
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4868
+			//there is a primary key on this table and its not set. Use defaults for all its columns
4869
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
4870
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4871
+					if ( ! $field_obj->is_db_only_field()) {
4872
+						//prepare field as if its coming from db
4873
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4874
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4875
+					}
4876
+				}
4877
+			} else {
4878
+				//the table's rows existed. Use their values
4879
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4880
+					if ( ! $field_obj->is_db_only_field()) {
4881
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4882
+							$cols_n_values, $field_obj->get_qualified_column(),
4883
+							$field_obj->get_table_column()
4884
+						);
4885
+					}
4886
+				}
4887
+			}
4888
+		}
4889
+		return $this_model_fields_n_values;
4890
+	}
4891
+
4892
+
4893
+
4894
+	/**
4895
+	 * @param $cols_n_values
4896
+	 * @param $qualified_column
4897
+	 * @param $regular_column
4898
+	 * @return null
4899
+	 */
4900
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4901
+	{
4902
+		$value = null;
4903
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4904
+		//does the field on the model relate to this column retrieved from the db?
4905
+		//or is it a db-only field? (not relating to the model)
4906
+		if (isset($cols_n_values[$qualified_column])) {
4907
+			$value = $cols_n_values[$qualified_column];
4908
+		} elseif (isset($cols_n_values[$regular_column])) {
4909
+			$value = $cols_n_values[$regular_column];
4910
+		}
4911
+		return $value;
4912
+	}
4913
+
4914
+
4915
+
4916
+	/**
4917
+	 * refresh_entity_map_from_db
4918
+	 * Makes sure the model object in the entity map at $id assumes the values
4919
+	 * of the database (opposite of EE_base_Class::save())
4920
+	 *
4921
+	 * @param int|string $id
4922
+	 * @return EE_Base_Class
4923
+	 * @throws \EE_Error
4924
+	 */
4925
+	public function refresh_entity_map_from_db($id)
4926
+	{
4927
+		$obj_in_map = $this->get_from_entity_map($id);
4928
+		if ($obj_in_map) {
4929
+			$wpdb_results = $this->_get_all_wpdb_results(
4930
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
4931
+			);
4932
+			if ($wpdb_results && is_array($wpdb_results)) {
4933
+				$one_row = reset($wpdb_results);
4934
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
4935
+					$obj_in_map->set_from_db($field_name, $db_value);
4936
+				}
4937
+				//clear the cache of related model objects
4938
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4939
+					$obj_in_map->clear_cache($relation_name, null, true);
4940
+				}
4941
+			}
4942
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
4943
+			return $obj_in_map;
4944
+		} else {
4945
+			return $this->get_one_by_ID($id);
4946
+		}
4947
+	}
4948
+
4949
+
4950
+
4951
+	/**
4952
+	 * refresh_entity_map_with
4953
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
4954
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4955
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4956
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4957
+	 *
4958
+	 * @param int|string    $id
4959
+	 * @param EE_Base_Class $replacing_model_obj
4960
+	 * @return \EE_Base_Class
4961
+	 * @throws \EE_Error
4962
+	 */
4963
+	public function refresh_entity_map_with($id, $replacing_model_obj)
4964
+	{
4965
+		$obj_in_map = $this->get_from_entity_map($id);
4966
+		if ($obj_in_map) {
4967
+			if ($replacing_model_obj instanceof EE_Base_Class) {
4968
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
4969
+					$obj_in_map->set($field_name, $value);
4970
+				}
4971
+				//make the model object in the entity map's cache match the $replacing_model_obj
4972
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4973
+					$obj_in_map->clear_cache($relation_name, null, true);
4974
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
4975
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
4976
+					}
4977
+				}
4978
+			}
4979
+			return $obj_in_map;
4980
+		} else {
4981
+			$this->add_to_entity_map($replacing_model_obj);
4982
+			return $replacing_model_obj;
4983
+		}
4984
+	}
4985
+
4986
+
4987
+
4988
+	/**
4989
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4990
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4991
+	 * require_once($this->_getClassName().".class.php");
4992
+	 *
4993
+	 * @return string
4994
+	 */
4995
+	private function _get_class_name()
4996
+	{
4997
+		return "EE_" . $this->get_this_model_name();
4998
+	}
4999
+
5000
+
5001
+
5002
+	/**
5003
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5004
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5005
+	 * it would be 'Events'.
5006
+	 *
5007
+	 * @param int $quantity
5008
+	 * @return string
5009
+	 */
5010
+	public function item_name($quantity = 1)
5011
+	{
5012
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5013
+	}
5014
+
5015
+
5016
+
5017
+	/**
5018
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5019
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5020
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5021
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5022
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5023
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5024
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5025
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5026
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5027
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5028
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5029
+	 *        return $previousReturnValue.$returnString;
5030
+	 * }
5031
+	 * require('EEM_Answer.model.php');
5032
+	 * $answer=EEM_Answer::instance();
5033
+	 * echo $answer->my_callback('monkeys',100);
5034
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5035
+	 *
5036
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5037
+	 * @param array  $args       array of original arguments passed to the function
5038
+	 * @throws EE_Error
5039
+	 * @return mixed whatever the plugin which calls add_filter decides
5040
+	 */
5041
+	public function __call($methodName, $args)
5042
+	{
5043
+		$className = get_class($this);
5044
+		$tagName = "FHEE__{$className}__{$methodName}";
5045
+		if ( ! has_filter($tagName)) {
5046
+			throw new EE_Error(
5047
+				sprintf(
5048
+					__('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 );',
5049
+						'event_espresso'),
5050
+					$methodName,
5051
+					$className,
5052
+					$tagName,
5053
+					'<br />'
5054
+				)
5055
+			);
5056
+		}
5057
+		return apply_filters($tagName, null, $this, $args);
5058
+	}
5059
+
5060
+
5061
+
5062
+	/**
5063
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5064
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5065
+	 *
5066
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5067
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5068
+	 *                                                       the object's class name
5069
+	 *                                                       or object's ID
5070
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5071
+	 *                                                       exists in the database. If it does not, we add it
5072
+	 * @throws EE_Error
5073
+	 * @return EE_Base_Class
5074
+	 */
5075
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5076
+	{
5077
+		$className = $this->_get_class_name();
5078
+		if ($base_class_obj_or_id instanceof $className) {
5079
+			$model_object = $base_class_obj_or_id;
5080
+		} else {
5081
+			$primary_key_field = $this->get_primary_key_field();
5082
+			if (
5083
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5084
+				&& (
5085
+					is_int($base_class_obj_or_id)
5086
+					|| is_string($base_class_obj_or_id)
5087
+				)
5088
+			) {
5089
+				// assume it's an ID.
5090
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5091
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5092
+			} else if (
5093
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5094
+				&& is_string($base_class_obj_or_id)
5095
+			) {
5096
+				// assume its a string representation of the object
5097
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5098
+			} else {
5099
+				throw new EE_Error(
5100
+					sprintf(
5101
+						__(
5102
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5103
+							'event_espresso'
5104
+						),
5105
+						$base_class_obj_or_id,
5106
+						$this->_get_class_name(),
5107
+						print_r($base_class_obj_or_id, true)
5108
+					)
5109
+				);
5110
+			}
5111
+		}
5112
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5113
+			$model_object->save();
5114
+		}
5115
+		return $model_object;
5116
+	}
5117
+
5118
+
5119
+
5120
+	/**
5121
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5122
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5123
+	 * returns it ID.
5124
+	 *
5125
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5126
+	 * @return int|string depending on the type of this model object's ID
5127
+	 * @throws EE_Error
5128
+	 */
5129
+	public function ensure_is_ID($base_class_obj_or_id)
5130
+	{
5131
+		$className = $this->_get_class_name();
5132
+		if ($base_class_obj_or_id instanceof $className) {
5133
+			/** @var $base_class_obj_or_id EE_Base_Class */
5134
+			$id = $base_class_obj_or_id->ID();
5135
+		} elseif (is_int($base_class_obj_or_id)) {
5136
+			//assume it's an ID
5137
+			$id = $base_class_obj_or_id;
5138
+		} elseif (is_string($base_class_obj_or_id)) {
5139
+			//assume its a string representation of the object
5140
+			$id = $base_class_obj_or_id;
5141
+		} else {
5142
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5143
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5144
+				print_r($base_class_obj_or_id, true)));
5145
+		}
5146
+		return $id;
5147
+	}
5148
+
5149
+
5150
+
5151
+	/**
5152
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5153
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5154
+	 * been sanitized and converted into the appropriate domain.
5155
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5156
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5157
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5158
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5159
+	 * $EVT = EEM_Event::instance(); $old_setting =
5160
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5161
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5162
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5163
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5164
+	 *
5165
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5166
+	 * @return void
5167
+	 */
5168
+	public function assume_values_already_prepared_by_model_object(
5169
+		$values_already_prepared = self::not_prepared_by_model_object
5170
+	) {
5171
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5172
+	}
5173
+
5174
+
5175
+
5176
+	/**
5177
+	 * Read comments for assume_values_already_prepared_by_model_object()
5178
+	 *
5179
+	 * @return int
5180
+	 */
5181
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5182
+	{
5183
+		return $this->_values_already_prepared_by_model_object;
5184
+	}
5185
+
5186
+
5187
+
5188
+	/**
5189
+	 * Gets all the indexes on this model
5190
+	 *
5191
+	 * @return EE_Index[]
5192
+	 */
5193
+	public function indexes()
5194
+	{
5195
+		return $this->_indexes;
5196
+	}
5197
+
5198
+
5199
+
5200
+	/**
5201
+	 * Gets all the Unique Indexes on this model
5202
+	 *
5203
+	 * @return EE_Unique_Index[]
5204
+	 */
5205
+	public function unique_indexes()
5206
+	{
5207
+		$unique_indexes = array();
5208
+		foreach ($this->_indexes as $name => $index) {
5209
+			if ($index instanceof EE_Unique_Index) {
5210
+				$unique_indexes [$name] = $index;
5211
+			}
5212
+		}
5213
+		return $unique_indexes;
5214
+	}
5215
+
5216
+
5217
+
5218
+	/**
5219
+	 * Gets all the fields which, when combined, make the primary key.
5220
+	 * This is usually just an array with 1 element (the primary key), but in cases
5221
+	 * where there is no primary key, it's a combination of fields as defined
5222
+	 * on a primary index
5223
+	 *
5224
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5225
+	 * @throws \EE_Error
5226
+	 */
5227
+	public function get_combined_primary_key_fields()
5228
+	{
5229
+		foreach ($this->indexes() as $index) {
5230
+			if ($index instanceof EE_Primary_Key_Index) {
5231
+				return $index->fields();
5232
+			}
5233
+		}
5234
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5235
+	}
5236
+
5237
+
5238
+
5239
+	/**
5240
+	 * Used to build a primary key string (when the model has no primary key),
5241
+	 * which can be used a unique string to identify this model object.
5242
+	 *
5243
+	 * @param array $cols_n_values keys are field names, values are their values
5244
+	 * @return string
5245
+	 * @throws \EE_Error
5246
+	 */
5247
+	public function get_index_primary_key_string($cols_n_values)
5248
+	{
5249
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5250
+			$this->get_combined_primary_key_fields());
5251
+		return http_build_query($cols_n_values_for_primary_key_index);
5252
+	}
5253
+
5254
+
5255
+
5256
+	/**
5257
+	 * Gets the field values from the primary key string
5258
+	 *
5259
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5260
+	 * @param string $index_primary_key_string
5261
+	 * @return null|array
5262
+	 * @throws \EE_Error
5263
+	 */
5264
+	public function parse_index_primary_key_string($index_primary_key_string)
5265
+	{
5266
+		$key_fields = $this->get_combined_primary_key_fields();
5267
+		//check all of them are in the $id
5268
+		$key_vals_in_combined_pk = array();
5269
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5270
+		foreach ($key_fields as $key_field_name => $field_obj) {
5271
+			if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5272
+				return null;
5273
+			}
5274
+		}
5275
+		return $key_vals_in_combined_pk;
5276
+	}
5277
+
5278
+
5279
+
5280
+	/**
5281
+	 * verifies that an array of key-value pairs for model fields has a key
5282
+	 * for each field comprising the primary key index
5283
+	 *
5284
+	 * @param array $key_vals
5285
+	 * @return boolean
5286
+	 * @throws \EE_Error
5287
+	 */
5288
+	public function has_all_combined_primary_key_fields($key_vals)
5289
+	{
5290
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5291
+		foreach ($keys_it_should_have as $key) {
5292
+			if ( ! isset($key_vals[$key])) {
5293
+				return false;
5294
+			}
5295
+		}
5296
+		return true;
5297
+	}
5298
+
5299
+
5300
+
5301
+	/**
5302
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5303
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5304
+	 *
5305
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5306
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5307
+	 * @throws EE_Error
5308
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5309
+	 *                                                              indexed)
5310
+	 */
5311
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5312
+	{
5313
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5314
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5315
+		} elseif (is_array($model_object_or_attributes_array)) {
5316
+			$attributes_array = $model_object_or_attributes_array;
5317
+		} else {
5318
+			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",
5319
+				"event_espresso"), $model_object_or_attributes_array));
5320
+		}
5321
+		//even copies obviously won't have the same ID, so remove the primary key
5322
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5323
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5324
+			unset($attributes_array[$this->primary_key_name()]);
5325
+		}
5326
+		if (isset($query_params[0])) {
5327
+			$query_params[0] = array_merge($attributes_array, $query_params);
5328
+		} else {
5329
+			$query_params[0] = $attributes_array;
5330
+		}
5331
+		return $this->get_all($query_params);
5332
+	}
5333
+
5334
+
5335
+
5336
+	/**
5337
+	 * Gets the first copy we find. See get_all_copies for more details
5338
+	 *
5339
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5340
+	 * @param array $query_params
5341
+	 * @return EE_Base_Class
5342
+	 * @throws \EE_Error
5343
+	 */
5344
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5345
+	{
5346
+		if ( ! is_array($query_params)) {
5347
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5348
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5349
+					gettype($query_params)), '4.6.0');
5350
+			$query_params = array();
5351
+		}
5352
+		$query_params['limit'] = 1;
5353
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5354
+		if (is_array($copies)) {
5355
+			return array_shift($copies);
5356
+		} else {
5357
+			return null;
5358
+		}
5359
+	}
5360
+
5361
+
5362
+
5363
+	/**
5364
+	 * Updates the item with the specified id. Ignores default query parameters because
5365
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5366
+	 *
5367
+	 * @param array      $fields_n_values keys are field names, values are their new values
5368
+	 * @param int|string $id              the value of the primary key to update
5369
+	 * @return int number of rows updated
5370
+	 * @throws \EE_Error
5371
+	 */
5372
+	public function update_by_ID($fields_n_values, $id)
5373
+	{
5374
+		$query_params = array(
5375
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5376
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5377
+		);
5378
+		return $this->update($fields_n_values, $query_params);
5379
+	}
5380
+
5381
+
5382
+
5383
+	/**
5384
+	 * Changes an operator which was supplied to the models into one usable in SQL
5385
+	 *
5386
+	 * @param string $operator_supplied
5387
+	 * @return string an operator which can be used in SQL
5388
+	 * @throws EE_Error
5389
+	 */
5390
+	private function _prepare_operator_for_sql($operator_supplied)
5391
+	{
5392
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5393
+			: null;
5394
+		if ($sql_operator) {
5395
+			return $sql_operator;
5396
+		} else {
5397
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5398
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5399
+		}
5400
+	}
5401
+
5402
+
5403
+
5404
+	/**
5405
+	 * Gets an array where keys are the primary keys and values are their 'names'
5406
+	 * (as determined by the model object's name() function, which is often overridden)
5407
+	 *
5408
+	 * @param array $query_params like get_all's
5409
+	 * @return string[]
5410
+	 * @throws \EE_Error
5411
+	 */
5412
+	public function get_all_names($query_params = array())
5413
+	{
5414
+		$objs = $this->get_all($query_params);
5415
+		$names = array();
5416
+		foreach ($objs as $obj) {
5417
+			$names[$obj->ID()] = $obj->name();
5418
+		}
5419
+		return $names;
5420
+	}
5421
+
5422
+
5423
+
5424
+	/**
5425
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5426
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5427
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5428
+	 * array_keys() on $model_objects.
5429
+	 *
5430
+	 * @param \EE_Base_Class[] $model_objects
5431
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5432
+	 *                                               in the returned array
5433
+	 * @return array
5434
+	 * @throws \EE_Error
5435
+	 */
5436
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5437
+	{
5438
+		if ( ! $this->has_primary_key_field()) {
5439
+			if (WP_DEBUG) {
5440
+				EE_Error::add_error(
5441
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5442
+					__FILE__,
5443
+					__FUNCTION__,
5444
+					__LINE__
5445
+				);
5446
+			}
5447
+		}
5448
+		$IDs = array();
5449
+		foreach ($model_objects as $model_object) {
5450
+			$id = $model_object->ID();
5451
+			if ( ! $id) {
5452
+				if ($filter_out_empty_ids) {
5453
+					continue;
5454
+				}
5455
+				if (WP_DEBUG) {
5456
+					EE_Error::add_error(
5457
+						__(
5458
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5459
+							'event_espresso'
5460
+						),
5461
+						__FILE__,
5462
+						__FUNCTION__,
5463
+						__LINE__
5464
+					);
5465
+				}
5466
+			}
5467
+			$IDs[] = $id;
5468
+		}
5469
+		return $IDs;
5470
+	}
5471
+
5472
+
5473
+
5474
+	/**
5475
+	 * Returns the string used in capabilities relating to this model. If there
5476
+	 * are no capabilities that relate to this model returns false
5477
+	 *
5478
+	 * @return string|false
5479
+	 */
5480
+	public function cap_slug()
5481
+	{
5482
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5483
+	}
5484
+
5485
+
5486
+
5487
+	/**
5488
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5489
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5490
+	 * only returns the cap restrictions array in that context (ie, the array
5491
+	 * at that key)
5492
+	 *
5493
+	 * @param string $context
5494
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5495
+	 * @throws \EE_Error
5496
+	 */
5497
+	public function cap_restrictions($context = EEM_Base::caps_read)
5498
+	{
5499
+		EEM_Base::verify_is_valid_cap_context($context);
5500
+		//check if we ought to run the restriction generator first
5501
+		if (
5502
+			isset($this->_cap_restriction_generators[$context])
5503
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5504
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5505
+		) {
5506
+			$this->_cap_restrictions[$context] = array_merge(
5507
+				$this->_cap_restrictions[$context],
5508
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5509
+			);
5510
+		}
5511
+		//and make sure we've finalized the construction of each restriction
5512
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5513
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5514
+				$where_conditions_obj->_finalize_construct($this);
5515
+			}
5516
+		}
5517
+		return $this->_cap_restrictions[$context];
5518
+	}
5519
+
5520
+
5521
+
5522
+	/**
5523
+	 * Indicating whether or not this model thinks its a wp core model
5524
+	 *
5525
+	 * @return boolean
5526
+	 */
5527
+	public function is_wp_core_model()
5528
+	{
5529
+		return $this->_wp_core_model;
5530
+	}
5531
+
5532
+
5533
+
5534
+	/**
5535
+	 * Gets all the caps that are missing which impose a restriction on
5536
+	 * queries made in this context
5537
+	 *
5538
+	 * @param string $context one of EEM_Base::caps_ constants
5539
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5540
+	 * @throws \EE_Error
5541
+	 */
5542
+	public function caps_missing($context = EEM_Base::caps_read)
5543
+	{
5544
+		$missing_caps = array();
5545
+		$cap_restrictions = $this->cap_restrictions($context);
5546
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5547
+			if ( ! EE_Capabilities::instance()
5548
+								  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5549
+			) {
5550
+				$missing_caps[$cap] = $restriction_if_no_cap;
5551
+			}
5552
+		}
5553
+		return $missing_caps;
5554
+	}
5555
+
5556
+
5557
+
5558
+	/**
5559
+	 * Gets the mapping from capability contexts to action strings used in capability names
5560
+	 *
5561
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5562
+	 * one of 'read', 'edit', or 'delete'
5563
+	 */
5564
+	public function cap_contexts_to_cap_action_map()
5565
+	{
5566
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5567
+			$this);
5568
+	}
5569
+
5570
+
5571
+
5572
+	/**
5573
+	 * Gets the action string for the specified capability context
5574
+	 *
5575
+	 * @param string $context
5576
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5577
+	 * @throws \EE_Error
5578
+	 */
5579
+	public function cap_action_for_context($context)
5580
+	{
5581
+		$mapping = $this->cap_contexts_to_cap_action_map();
5582
+		if (isset($mapping[$context])) {
5583
+			return $mapping[$context];
5584
+		}
5585
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5586
+			return $action;
5587
+		}
5588
+		throw new EE_Error(
5589
+			sprintf(
5590
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5591
+				$context,
5592
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5593
+			)
5594
+		);
5595
+	}
5596
+
5597
+
5598
+
5599
+	/**
5600
+	 * Returns all the capability contexts which are valid when querying models
5601
+	 *
5602
+	 * @return array
5603
+	 */
5604
+	public static function valid_cap_contexts()
5605
+	{
5606
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5607
+			self::caps_read,
5608
+			self::caps_read_admin,
5609
+			self::caps_edit,
5610
+			self::caps_delete,
5611
+		));
5612
+	}
5613
+
5614
+
5615
+
5616
+	/**
5617
+	 * Returns all valid options for 'default_where_conditions'
5618
+	 * @return array
5619
+	 */
5620
+	public static function valid_default_where_conditions()
5621
+	{
5622
+		return array(
5623
+			EEM_Base::default_where_conditions_all,
5624
+			EEM_Base::default_where_conditions_this_only,
5625
+			EEM_Base::default_where_conditions_others_only,
5626
+			EEM_Base::default_where_conditions_minimum_all,
5627
+			EEM_Base::default_where_conditions_minimum_others,
5628
+			EEM_Base::default_where_conditions_none
5629
+		);
5630
+	}
5631
+
5632
+	// public static function default_where_conditions_full
5633
+
5634
+
5635
+
5636
+	/**
5637
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5638
+	 *
5639
+	 * @param string $context
5640
+	 * @return bool
5641
+	 * @throws \EE_Error
5642
+	 */
5643
+	static public function verify_is_valid_cap_context($context)
5644
+	{
5645
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5646
+		if (in_array($context, $valid_cap_contexts)) {
5647
+			return true;
5648
+		} else {
5649
+			throw new EE_Error(
5650
+				sprintf(
5651
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5652
+						'event_espresso'),
5653
+					$context,
5654
+					'EEM_Base',
5655
+					implode(',', $valid_cap_contexts)
5656
+				)
5657
+			);
5658
+		}
5659
+	}
5660
+
5661
+
5662
+
5663
+	/**
5664
+	 * Clears all the models field caches. This is only useful when a sub-class
5665
+	 * might have added a field or something and these caches might be invalidated
5666
+	 */
5667
+	protected function _invalidate_field_caches()
5668
+	{
5669
+		$this->_cache_foreign_key_to_fields = array();
5670
+		$this->_cached_fields = null;
5671
+		$this->_cached_fields_non_db_only = null;
5672
+	}
5673 5673
 
5674 5674
 
5675 5675
 
Please login to merge, or discard this patch.
Spacing   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -511,7 +511,7 @@  discard block
 block discarded – undo
511 511
     {
512 512
         // check that the model has not been loaded too soon
513 513
         if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
514
-            throw new EE_Error (
514
+            throw new EE_Error(
515 515
                 sprintf(
516 516
                     __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
517 517
                         'event_espresso'),
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
          *
532 532
          * @var EE_Table_Base[] $_tables
533 533
          */
534
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
534
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
535 535
         foreach ($this->_tables as $table_alias => $table_obj) {
536 536
             /** @var $table_obj EE_Table_Base */
537 537
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
          *
547 547
          * @param EE_Model_Field_Base[] $_fields
548 548
          */
549
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
549
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
550 550
         $this->_invalidate_field_caches();
551 551
         foreach ($this->_fields as $table_alias => $fields_for_table) {
552 552
             if ( ! array_key_exists($table_alias, $this->_tables)) {
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
          *
578 578
          * @param EE_Model_Relation_Base[] $_model_relations
579 579
          */
580
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
580
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
581 581
             $this->_model_relations);
582 582
         foreach ($this->_model_relations as $model_name => $relation_obj) {
583 583
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -639,7 +639,7 @@  discard block
 block discarded – undo
639 639
                 }
640 640
             }
641 641
         }
642
-        do_action('AHEE__' . get_class($this) . '__construct__end');
642
+        do_action('AHEE__'.get_class($this).'__construct__end');
643 643
     }
644 644
 
645 645
 
@@ -674,7 +674,7 @@  discard block
 block discarded – undo
674 674
      */
675 675
     public static function set_model_query_blog_id($blog_id = 0)
676 676
     {
677
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
677
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
678 678
     }
679 679
 
680 680
 
@@ -933,13 +933,13 @@  discard block
 block discarded – undo
933 933
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
934 934
                 $last_model_name = end($models_to_follow_to_wp_users);
935 935
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
936
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
936
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
937 937
             } else {
938 938
                 $model_with_fk_to_wp_users = $this;
939 939
                 $model_chain_to_wp_user = '';
940 940
             }
941 941
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
942
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
942
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
943 943
         } catch (EE_Error $e) {
944 944
             return false;
945 945
         }
@@ -1011,12 +1011,12 @@  discard block
 block discarded – undo
1011 1011
         // remember the custom selections, if any, and type cast as array
1012 1012
         // (unless $columns_to_select is an object, then just set as an empty array)
1013 1013
         // Note: (array) 'some string' === array( 'some string' )
1014
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1014
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1015 1015
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1016 1016
         $select_expressions = $columns_to_select !== null
1017 1017
             ? $this->_construct_select_from_input($columns_to_select)
1018 1018
             : $this->_construct_default_select_sql($model_query_info);
1019
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1019
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1020 1020
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1021 1021
     }
1022 1022
 
@@ -1348,7 +1348,7 @@  discard block
 block discarded – undo
1348 1348
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1349 1349
         $query_params['limit'] = $limit;
1350 1350
         //set direction
1351
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1351
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1352 1352
         $query_params['order_by'] = $operand === '>'
1353 1353
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1354 1354
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1589,7 +1589,7 @@  discard block
 block discarded – undo
1589 1589
          * @param EEM_Base $model           the model being queried
1590 1590
          * @param array    $query_params    see EEM_Base::get_all()
1591 1591
          */
1592
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1592
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1593 1593
             $query_params);
1594 1594
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1595 1595
         //to do that, for each table, verify that it's PK isn't null.
@@ -1603,7 +1603,7 @@  discard block
 block discarded – undo
1603 1603
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1604 1604
         foreach ($wpdb_select_results as $wpdb_result) {
1605 1605
             // type cast stdClass as array
1606
-            $wpdb_result = (array)$wpdb_result;
1606
+            $wpdb_result = (array) $wpdb_result;
1607 1607
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1608 1608
             if ($this->has_primary_key_field()) {
1609 1609
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1684,7 +1684,7 @@  discard block
 block discarded – undo
1684 1684
                . $model_query_info->get_full_join_sql()
1685 1685
                . " SET "
1686 1686
                . $this->_construct_update_sql($fields_n_values)
1687
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1687
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1688 1688
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1689 1689
         /**
1690 1690
          * Action called after a model update call has been made.
@@ -1695,7 +1695,7 @@  discard block
 block discarded – undo
1695 1695
          * @param int      $rows_affected
1696 1696
          */
1697 1697
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1698
-        return $rows_affected;//how many supposedly got updated
1698
+        return $rows_affected; //how many supposedly got updated
1699 1699
     }
1700 1700
 
1701 1701
 
@@ -1723,7 +1723,7 @@  discard block
 block discarded – undo
1723 1723
         }
1724 1724
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1725 1725
         $select_expressions = $field->get_qualified_column();
1726
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1726
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1727 1727
         return $this->_do_wpdb_query('get_col', array($SQL));
1728 1728
     }
1729 1729
 
@@ -1773,7 +1773,7 @@  discard block
 block discarded – undo
1773 1773
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1774 1774
             $value_sql = $prepared_value === null ? 'NULL'
1775 1775
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1776
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1776
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1777 1777
         }
1778 1778
         return implode(",", $cols_n_values);
1779 1779
     }
@@ -1905,7 +1905,7 @@  discard block
 block discarded – undo
1905 1905
          * @param int      $rows_deleted
1906 1906
          */
1907 1907
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1908
-        return $rows_deleted;//how many supposedly got deleted
1908
+        return $rows_deleted; //how many supposedly got deleted
1909 1909
     }
1910 1910
 
1911 1911
 
@@ -2021,7 +2021,7 @@  discard block
 block discarded – undo
2021 2021
             foreach ($deletes as $column => $values) {
2022 2022
                 //make sure we have unique $values;
2023 2023
                 $values = array_unique($values);
2024
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2024
+                $query[] = $column.' IN('.implode(",", $values).')';
2025 2025
             }
2026 2026
             return ! empty($query) ? implode(' AND ', $query) : '';
2027 2027
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2037,7 +2037,7 @@  discard block
 block discarded – undo
2037 2037
                                                            . $delete_object[$cpk_field->get_qualified_column()];
2038 2038
                     }
2039 2039
                 }
2040
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2040
+                $ways_to_identify_a_row[] = "(".implode(" AND ", $values_for_each_cpk_for_a_row).")";
2041 2041
             }
2042 2042
             return implode(" OR ", $ways_to_identify_a_row);
2043 2043
         } else {
@@ -2086,9 +2086,9 @@  discard block
 block discarded – undo
2086 2086
                 $column_to_count = '*';
2087 2087
             }
2088 2088
         }
2089
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2090
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2091
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2089
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2090
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2091
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2092 2092
     }
2093 2093
 
2094 2094
 
@@ -2110,13 +2110,13 @@  discard block
 block discarded – undo
2110 2110
             $field_obj = $this->get_primary_key_field();
2111 2111
         }
2112 2112
         $column_to_count = $field_obj->get_qualified_column();
2113
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2113
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2114 2114
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2115 2115
         $data_type = $field_obj->get_wpdb_data_type();
2116 2116
         if ($data_type === '%d' || $data_type === '%s') {
2117
-            return (float)$return_value;
2117
+            return (float) $return_value;
2118 2118
         } else {//must be %f
2119
-            return (float)$return_value;
2119
+            return (float) $return_value;
2120 2120
         }
2121 2121
     }
2122 2122
 
@@ -2291,11 +2291,11 @@  discard block
 block discarded – undo
2291 2291
      */
2292 2292
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2293 2293
     {
2294
-        return " FROM " . $model_query_info->get_full_join_sql() .
2295
-               $model_query_info->get_where_sql() .
2296
-               $model_query_info->get_group_by_sql() .
2297
-               $model_query_info->get_having_sql() .
2298
-               $model_query_info->get_order_by_sql() .
2294
+        return " FROM ".$model_query_info->get_full_join_sql().
2295
+               $model_query_info->get_where_sql().
2296
+               $model_query_info->get_group_by_sql().
2297
+               $model_query_info->get_having_sql().
2298
+               $model_query_info->get_order_by_sql().
2299 2299
                $model_query_info->get_limit_sql();
2300 2300
     }
2301 2301
 
@@ -2496,7 +2496,7 @@  discard block
 block discarded – undo
2496 2496
         }
2497 2497
         $this_model_name = $this->get_this_model_name();
2498 2498
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2499
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2499
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2500 2500
         return $related_model->count($query_params, $field_to_count, $distinct);
2501 2501
     }
2502 2502
 
@@ -2529,7 +2529,7 @@  discard block
 block discarded – undo
2529 2529
         }
2530 2530
         $this_model_name = $this->get_this_model_name();
2531 2531
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2532
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2532
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2533 2533
         return $related_model->sum($query_params, $field_to_sum);
2534 2534
     }
2535 2535
 
@@ -2616,7 +2616,7 @@  discard block
 block discarded – undo
2616 2616
          * @param array    $fields_n_values keys are the fields and values are their new values
2617 2617
          * @param EEM_Base $model           the model used
2618 2618
          */
2619
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2619
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2620 2620
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2621 2621
             $main_table = $this->_get_main_table();
2622 2622
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2724,7 +2724,7 @@  discard block
 block discarded – undo
2724 2724
         }
2725 2725
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2726 2726
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2727
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2727
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2728 2728
         }
2729 2729
         //if there is nothing to base this search on, then we shouldn't find anything
2730 2730
         if (empty($query_params)) {
@@ -2811,7 +2811,7 @@  discard block
 block discarded – undo
2811 2811
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2812 2812
             //so add the fk to the main table as a column
2813 2813
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2814
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2814
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2815 2815
         }
2816 2816
         //insert the new entry
2817 2817
         $result = $this->_do_wpdb_query('insert',
@@ -3071,7 +3071,7 @@  discard block
 block discarded – undo
3071 3071
         $query_param_type
3072 3072
     ) {
3073 3073
         if ( ! empty($sub_query_params)) {
3074
-            $sub_query_params = (array)$sub_query_params;
3074
+            $sub_query_params = (array) $sub_query_params;
3075 3075
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3076 3076
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3077 3077
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3242,12 +3242,12 @@  discard block
 block discarded – undo
3242 3242
                         ),
3243 3243
                         http_build_query($query_params['limit'])
3244 3244
                     );
3245
-                    throw new EE_Error($e . "|" . $e);
3245
+                    throw new EE_Error($e."|".$e);
3246 3246
                 }
3247 3247
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3248
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3248
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3249 3249
             } elseif ( ! empty ($query_params['limit'])) {
3250
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3250
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3251 3251
             }
3252 3252
         }
3253 3253
         //set order by
@@ -3279,9 +3279,9 @@  discard block
 block discarded – undo
3279 3279
                 $order_array = array();
3280 3280
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3281 3281
                     $order = $this->_extract_order($order);
3282
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3282
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3283 3283
                 }
3284
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3284
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3285 3285
             } elseif ( ! empty ($query_params['order_by'])) {
3286 3286
                 $this->_extract_related_model_info_from_query_param(
3287 3287
                     $query_params['order_by'],
@@ -3293,7 +3293,7 @@  discard block
 block discarded – undo
3293 3293
                     ? $this->_extract_order($query_params['order'])
3294 3294
                     : 'DESC';
3295 3295
                 $query_object->set_order_by_sql(
3296
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3296
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3297 3297
                 );
3298 3298
             }
3299 3299
         }
@@ -3304,7 +3304,7 @@  discard block
 block discarded – undo
3304 3304
         ) {
3305 3305
             $pk_field = $this->get_primary_key_field();
3306 3306
             $order = $this->_extract_order($query_params['order']);
3307
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3307
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3308 3308
         }
3309 3309
         //set group by
3310 3310
         if (array_key_exists('group_by', $query_params)) {
@@ -3314,10 +3314,10 @@  discard block
 block discarded – undo
3314 3314
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3315 3315
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3316 3316
                 }
3317
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3317
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3318 3318
             } elseif ( ! empty ($query_params['group_by'])) {
3319 3319
                 $query_object->set_group_by_sql(
3320
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3320
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3321 3321
                 );
3322 3322
             }
3323 3323
         }
@@ -3456,7 +3456,7 @@  discard block
 block discarded – undo
3456 3456
                 )
3457 3457
             ) {
3458 3458
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3459
-            } elseif(
3459
+            } elseif (
3460 3460
                 in_array(
3461 3461
                     $use_default_where_conditions,
3462 3462
                     array(
@@ -3509,7 +3509,7 @@  discard block
 block discarded – undo
3509 3509
     ) {
3510 3510
         $null_friendly_where_conditions = array();
3511 3511
         $none_overridden = true;
3512
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3512
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3513 3513
         foreach ($default_where_conditions as $key => $val) {
3514 3514
             if (isset($provided_where_conditions[$key])) {
3515 3515
                 $none_overridden = false;
@@ -3713,9 +3713,9 @@  discard block
 block discarded – undo
3713 3713
         //and
3714 3714
         //check if it's a field on a related model
3715 3715
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3716
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3716
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3717 3717
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3718
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3718
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3719 3719
                 if ($query_param === '') {
3720 3720
                     //nothing left to $query_param
3721 3721
                     //we should actually end in a field name, not a model like this!
@@ -3801,7 +3801,7 @@  discard block
 block discarded – undo
3801 3801
     {
3802 3802
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3803 3803
         if ($SQL) {
3804
-            return " WHERE " . $SQL;
3804
+            return " WHERE ".$SQL;
3805 3805
         } else {
3806 3806
             return '';
3807 3807
         }
@@ -3821,7 +3821,7 @@  discard block
 block discarded – undo
3821 3821
     {
3822 3822
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3823 3823
         if ($SQL) {
3824
-            return " HAVING " . $SQL;
3824
+            return " HAVING ".$SQL;
3825 3825
         } else {
3826 3826
             return '';
3827 3827
         }
@@ -3841,11 +3841,11 @@  discard block
 block discarded – undo
3841 3841
      */
3842 3842
     protected function _get_field_on_model($field_name, $model_name)
3843 3843
     {
3844
-        $model_class = 'EEM_' . $model_name;
3845
-        $model_filepath = $model_class . ".model.php";
3844
+        $model_class = 'EEM_'.$model_name;
3845
+        $model_filepath = $model_class.".model.php";
3846 3846
         if (is_readable($model_filepath)) {
3847 3847
             require_once($model_filepath);
3848
-            $model_instance = call_user_func($model_name . "::instance");
3848
+            $model_instance = call_user_func($model_name."::instance");
3849 3849
             /* @var $model_instance EEM_Base */
3850 3850
             return $model_instance->field_settings_for($field_name);
3851 3851
         } else {
@@ -3869,7 +3869,7 @@  discard block
 block discarded – undo
3869 3869
     {
3870 3870
         $where_clauses = array();
3871 3871
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3872
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3872
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
3873 3873
             if (in_array($query_param, $this->_logic_query_param_keys)) {
3874 3874
                 switch ($query_param) {
3875 3875
                     case 'not':
@@ -3906,7 +3906,7 @@  discard block
 block discarded – undo
3906 3906
                     }
3907 3907
                 }
3908 3908
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3909
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3909
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
3910 3910
             }
3911 3911
         }
3912 3912
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -3927,7 +3927,7 @@  discard block
 block discarded – undo
3927 3927
         if ($field) {
3928 3928
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3929 3929
                 $query_param);
3930
-            return $table_alias_prefix . $field->get_qualified_column();
3930
+            return $table_alias_prefix.$field->get_qualified_column();
3931 3931
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
3932 3932
             //maybe it's custom selection item?
3933 3933
             //if so, just use it as the "column name"
@@ -3996,13 +3996,13 @@  discard block
 block discarded – undo
3996 3996
         }
3997 3997
         //check to see if the value is actually another field
3998 3998
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3999
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
3999
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4000 4000
         } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4001 4001
             //in this case, the value should be an array, or at least a comma-separated list
4002 4002
             //it will need to handle a little differently
4003 4003
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4004 4004
             //note: $cleaned_value has already been run through $wpdb->prepare()
4005
-            return $operator . SP . $cleaned_value;
4005
+            return $operator.SP.$cleaned_value;
4006 4006
         } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4007 4007
             //the value should be an array with count of two.
4008 4008
             if (count($value) !== 2) {
@@ -4017,7 +4017,7 @@  discard block
 block discarded – undo
4017 4017
                 );
4018 4018
             }
4019 4019
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4020
-            return $operator . SP . $cleaned_value;
4020
+            return $operator.SP.$cleaned_value;
4021 4021
         } elseif (in_array($operator, $this->_null_style_operators)) {
4022 4022
             if ($value !== null) {
4023 4023
                 throw new EE_Error(
@@ -4035,9 +4035,9 @@  discard block
 block discarded – undo
4035 4035
         } elseif ($operator === 'LIKE' && ! is_array($value)) {
4036 4036
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4037 4037
             //remove other junk. So just treat it as a string.
4038
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4038
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4039 4039
         } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4040
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4040
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4041 4041
         } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4042 4042
             throw new EE_Error(
4043 4043
                 sprintf(
@@ -4090,7 +4090,7 @@  discard block
 block discarded – undo
4090 4090
         foreach ($values as $value) {
4091 4091
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4092 4092
         }
4093
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4093
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4094 4094
     }
4095 4095
 
4096 4096
 
@@ -4131,7 +4131,7 @@  discard block
 block discarded – undo
4131 4131
                                 . $main_table->get_table_name()
4132 4132
                                 . " WHERE FALSE";
4133 4133
         }
4134
-        return "(" . implode(",", $cleaned_values) . ")";
4134
+        return "(".implode(",", $cleaned_values).")";
4135 4135
     }
4136 4136
 
4137 4137
 
@@ -4234,11 +4234,11 @@  discard block
 block discarded – undo
4234 4234
             if ($table_obj instanceof EE_Primary_Table) {
4235 4235
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4236 4236
                     ? $table_obj->get_select_join_limit($limit)
4237
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4237
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4238 4238
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4239 4239
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4240 4240
                     ? $table_obj->get_select_join_limit_join($limit)
4241
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4241
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4242 4242
             }
4243 4243
         }
4244 4244
         return $SQL;
@@ -4326,12 +4326,12 @@  discard block
 block discarded – undo
4326 4326
      */
4327 4327
     public function get_related_model_obj($model_name)
4328 4328
     {
4329
-        $model_classname = "EEM_" . $model_name;
4329
+        $model_classname = "EEM_".$model_name;
4330 4330
         if ( ! class_exists($model_classname)) {
4331 4331
             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",
4332 4332
                 'event_espresso'), $model_name, $model_classname));
4333 4333
         }
4334
-        return call_user_func($model_classname . "::instance");
4334
+        return call_user_func($model_classname."::instance");
4335 4335
     }
4336 4336
 
4337 4337
 
@@ -4630,7 +4630,7 @@  discard block
 block discarded – undo
4630 4630
         $count_if_model_has_no_primary_key = 0;
4631 4631
         $has_primary_key = $this->has_primary_key_field();
4632 4632
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4633
-        foreach ((array)$rows as $row) {
4633
+        foreach ((array) $rows as $row) {
4634 4634
             if (empty($row)) {
4635 4635
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4636 4636
                 return array();
@@ -4994,7 +4994,7 @@  discard block
 block discarded – undo
4994 4994
      */
4995 4995
     private function _get_class_name()
4996 4996
     {
4997
-        return "EE_" . $this->get_this_model_name();
4997
+        return "EE_".$this->get_this_model_name();
4998 4998
     }
4999 4999
 
5000 5000
 
@@ -5009,7 +5009,7 @@  discard block
 block discarded – undo
5009 5009
      */
5010 5010
     public function item_name($quantity = 1)
5011 5011
     {
5012
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5012
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5013 5013
     }
5014 5014
 
5015 5015
 
@@ -5545,7 +5545,7 @@  discard block
 block discarded – undo
5545 5545
         $cap_restrictions = $this->cap_restrictions($context);
5546 5546
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5547 5547
             if ( ! EE_Capabilities::instance()
5548
-                                  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5548
+                                  ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5549 5549
             ) {
5550 5550
                 $missing_caps[$cap] = $restriction_if_no_cap;
5551 5551
             }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +215 added lines, -215 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('ABSPATH')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /*
5 5
   Plugin Name:		Event Espresso
@@ -40,239 +40,239 @@  discard block
 block discarded – undo
40 40
  * @since            4.0
41 41
  */
42 42
 if (function_exists('espresso_version')) {
43
-    /**
44
-     *    espresso_duplicate_plugin_error
45
-     *    displays if more than one version of EE is activated at the same time
46
-     */
47
-    function espresso_duplicate_plugin_error()
48
-    {
49
-        ?>
43
+	/**
44
+	 *    espresso_duplicate_plugin_error
45
+	 *    displays if more than one version of EE is activated at the same time
46
+	 */
47
+	function espresso_duplicate_plugin_error()
48
+	{
49
+		?>
50 50
         <div class="error">
51 51
             <p>
52 52
                 <?php echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                ); ?>
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+				); ?>
56 56
             </p>
57 57
         </div>
58 58
         <?php
59
-        espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-    }
59
+		espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+	}
61 61
 
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
-    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
+	if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                            esc_html__(
79
-                                    'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                                    'event_espresso'
81
-                            ),
82
-                            EE_MIN_PHP_VER_REQUIRED,
83
-                            PHP_VERSION,
84
-                            '<br/>',
85
-                            '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+							esc_html__(
79
+									'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+									'event_espresso'
81
+							),
82
+							EE_MIN_PHP_VER_REQUIRED,
83
+							PHP_VERSION,
84
+							'<br/>',
85
+							'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        /**
97
-         * espresso_version
98
-         * Returns the plugin version
99
-         *
100
-         * @return string
101
-         */
102
-        function espresso_version()
103
-        {
104
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.23.rc.011');
105
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		/**
97
+		 * espresso_version
98
+		 * Returns the plugin version
99
+		 *
100
+		 * @return string
101
+		 */
102
+		function espresso_version()
103
+		{
104
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.23.rc.011');
105
+		}
106 106
 
107
-        // define versions
108
-        define('EVENT_ESPRESSO_VERSION', espresso_version());
109
-        define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
-        define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
-        define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
-        //used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
-        if ( ! defined('DS')) {
115
-            define('DS', '/');
116
-        }
117
-        if ( ! defined('PS')) {
118
-            define('PS', PATH_SEPARATOR);
119
-        }
120
-        if ( ! defined('SP')) {
121
-            define('SP', ' ');
122
-        }
123
-        if ( ! defined('EENL')) {
124
-            define('EENL', "\n");
125
-        }
126
-        define('EE_SUPPORT_EMAIL', '[email protected]');
127
-        // define the plugin directory and URL
128
-        define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
-        define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
-        define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
-        // main root folder paths
132
-        define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
-        define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
-        define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
-        define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
-        define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
-        define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
-        define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
-        define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
-        // core system paths
141
-        define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
-        define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
-        define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
-        define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
-        define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
-        define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
-        define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
-        define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
-        define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
-        define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
-        define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
-        define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
-        // gateways
154
-        define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
-        define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
-        // asset URL paths
157
-        define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
-        define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
-        define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
-        define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
-        define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
-        define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
-        // define upload paths
164
-        $uploads = wp_upload_dir();
165
-        // define the uploads directory and URL
166
-        define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
-        define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
-        // define the templates directory and URL
169
-        define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
-        define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
-        // define the gateway directory and URL
172
-        define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
-        define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
-        // languages folder/path
175
-        define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
-        define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
-        //check for dompdf fonts in uploads
178
-        if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
-            define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
-        }
181
-        //ajax constants
182
-        define(
183
-                'EE_FRONT_AJAX',
184
-                isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
-        );
186
-        define(
187
-                'EE_ADMIN_AJAX',
188
-                isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
-        );
190
-        //just a handy constant occasionally needed for finding values representing infinity in the DB
191
-        //you're better to use this than its straight value (currently -1) in case you ever
192
-        //want to change its default value! or find when -1 means infinity
193
-        define('EE_INF_IN_DB', -1);
194
-        define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
-        define('EE_DEBUG', false);
196
-        /**
197
-         *    espresso_plugin_activation
198
-         *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
199
-         */
200
-        function espresso_plugin_activation()
201
-        {
202
-            update_option('ee_espresso_activation', true);
203
-        }
107
+		// define versions
108
+		define('EVENT_ESPRESSO_VERSION', espresso_version());
109
+		define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
+		define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
+		define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
+		//used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
+		if ( ! defined('DS')) {
115
+			define('DS', '/');
116
+		}
117
+		if ( ! defined('PS')) {
118
+			define('PS', PATH_SEPARATOR);
119
+		}
120
+		if ( ! defined('SP')) {
121
+			define('SP', ' ');
122
+		}
123
+		if ( ! defined('EENL')) {
124
+			define('EENL', "\n");
125
+		}
126
+		define('EE_SUPPORT_EMAIL', '[email protected]');
127
+		// define the plugin directory and URL
128
+		define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
+		define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
+		define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
+		// main root folder paths
132
+		define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
+		define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
+		define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
+		define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
+		define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
+		define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
+		define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
+		define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
+		// core system paths
141
+		define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
+		define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
+		define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
+		define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
+		define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
+		define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
+		define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
+		define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
+		define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
+		define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
+		define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
+		define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
+		// gateways
154
+		define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
+		define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
+		// asset URL paths
157
+		define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
+		define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
+		define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
+		define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
+		define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
+		define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
+		// define upload paths
164
+		$uploads = wp_upload_dir();
165
+		// define the uploads directory and URL
166
+		define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
+		define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
+		// define the templates directory and URL
169
+		define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
+		define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
+		// define the gateway directory and URL
172
+		define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
+		define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
+		// languages folder/path
175
+		define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
+		define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
+		//check for dompdf fonts in uploads
178
+		if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
+			define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
+		}
181
+		//ajax constants
182
+		define(
183
+				'EE_FRONT_AJAX',
184
+				isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
+		);
186
+		define(
187
+				'EE_ADMIN_AJAX',
188
+				isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
+		);
190
+		//just a handy constant occasionally needed for finding values representing infinity in the DB
191
+		//you're better to use this than its straight value (currently -1) in case you ever
192
+		//want to change its default value! or find when -1 means infinity
193
+		define('EE_INF_IN_DB', -1);
194
+		define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
+		define('EE_DEBUG', false);
196
+		/**
197
+		 *    espresso_plugin_activation
198
+		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
199
+		 */
200
+		function espresso_plugin_activation()
201
+		{
202
+			update_option('ee_espresso_activation', true);
203
+		}
204 204
 
205
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
206
-        /**
207
-         *    espresso_load_error_handling
208
-         *    this function loads EE's class for handling exceptions and errors
209
-         */
210
-        function espresso_load_error_handling()
211
-        {
212
-            // load debugging tools
213
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
214
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
215
-                EEH_Debug_Tools::instance();
216
-            }
217
-            // load error handling
218
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
219
-                require_once(EE_CORE . 'EE_Error.core.php');
220
-            } else {
221
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
222
-            }
223
-        }
205
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
206
+		/**
207
+		 *    espresso_load_error_handling
208
+		 *    this function loads EE's class for handling exceptions and errors
209
+		 */
210
+		function espresso_load_error_handling()
211
+		{
212
+			// load debugging tools
213
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
214
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
215
+				EEH_Debug_Tools::instance();
216
+			}
217
+			// load error handling
218
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
219
+				require_once(EE_CORE . 'EE_Error.core.php');
220
+			} else {
221
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
222
+			}
223
+		}
224 224
 
225
-        /**
226
-         *    espresso_load_required
227
-         *    given a class name and path, this function will load that file or throw an exception
228
-         *
229
-         * @param    string $classname
230
-         * @param    string $full_path_to_file
231
-         * @throws    EE_Error
232
-         */
233
-        function espresso_load_required($classname, $full_path_to_file)
234
-        {
235
-            static $error_handling_loaded = false;
236
-            if ( ! $error_handling_loaded) {
237
-                espresso_load_error_handling();
238
-                $error_handling_loaded = true;
239
-            }
240
-            if (is_readable($full_path_to_file)) {
241
-                require_once($full_path_to_file);
242
-            } else {
243
-                throw new EE_Error (
244
-                        sprintf(
245
-                                esc_html__(
246
-                                        'The %s class file could not be located or is not readable due to file permissions.',
247
-                                        'event_espresso'
248
-                                ),
249
-                                $classname
250
-                        )
251
-                );
252
-            }
253
-        }
225
+		/**
226
+		 *    espresso_load_required
227
+		 *    given a class name and path, this function will load that file or throw an exception
228
+		 *
229
+		 * @param    string $classname
230
+		 * @param    string $full_path_to_file
231
+		 * @throws    EE_Error
232
+		 */
233
+		function espresso_load_required($classname, $full_path_to_file)
234
+		{
235
+			static $error_handling_loaded = false;
236
+			if ( ! $error_handling_loaded) {
237
+				espresso_load_error_handling();
238
+				$error_handling_loaded = true;
239
+			}
240
+			if (is_readable($full_path_to_file)) {
241
+				require_once($full_path_to_file);
242
+			} else {
243
+				throw new EE_Error (
244
+						sprintf(
245
+								esc_html__(
246
+										'The %s class file could not be located or is not readable due to file permissions.',
247
+										'event_espresso'
248
+								),
249
+								$classname
250
+						)
251
+				);
252
+			}
253
+		}
254 254
 
255
-        espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
256
-        espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
257
-        espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
258
-        new EE_Bootstrap();
259
-    }
255
+		espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
256
+		espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
257
+		espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
258
+		new EE_Bootstrap();
259
+	}
260 260
 }
261 261
 if ( ! function_exists('espresso_deactivate_plugin')) {
262
-    /**
263
-     *    deactivate_plugin
264
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
265
-     *
266
-     * @access public
267
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
268
-     * @return    void
269
-     */
270
-    function espresso_deactivate_plugin($plugin_basename = '')
271
-    {
272
-        if ( ! function_exists('deactivate_plugins')) {
273
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
274
-        }
275
-        unset($_GET['activate'], $_REQUEST['activate']);
276
-        deactivate_plugins($plugin_basename);
277
-    }
262
+	/**
263
+	 *    deactivate_plugin
264
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
265
+	 *
266
+	 * @access public
267
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
268
+	 * @return    void
269
+	 */
270
+	function espresso_deactivate_plugin($plugin_basename = '')
271
+	{
272
+		if ( ! function_exists('deactivate_plugins')) {
273
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
274
+		}
275
+		unset($_GET['activate'], $_REQUEST['activate']);
276
+		deactivate_plugins($plugin_basename);
277
+	}
278 278
 }
Please login to merge, or discard this patch.