Completed
Branch FET/4986/11317/order-by-count (40fb33)
by
unknown
59:10 queued 47:34
created

EEM_Base::getCustomSelection()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 6
nc 5
nop 2
dl 0
loc 9
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
use EventEspresso\core\domain\values\model\CustomSelects;
4
use EventEspresso\core\exceptions\InvalidDataTypeException;
5
use EventEspresso\core\exceptions\InvalidInterfaceException;
6
use EventEspresso\core\interfaces\ResettableInterface;
7
use EventEspresso\core\services\orm\ModelFieldFactory;
8
use EventEspresso\core\services\loaders\LoaderFactory;
9
10
/**
11
 * Class EEM_Base
12
 * Multi-table model. Especially handles joins when querying.
13
 * An important note about values dealt with in models and model objects:
14
 * values used by models exist in basically 3 different domains, which the EE_Model_Fields help convert between:
15
 * 1. Client-code values (eg, controller code may refer to a date as "March 21, 2013")
16
 * 2. Model object values (eg, after the model object has called set() on the value and saves it onto the model object,
17
 * it may become a unix timestamp, eg 12312412412)
18
 * 3. Database values (eg, we may later decide to store dates as mysql dates, in which case they'd be stored as
19
 * '2013-03-21 00:00:00') Sometimes these values are the same, but often they are not. When your client code is using a
20
 * model's functions, you need to be aware which domain your data exists in. If it is client-code values (ie, it hasn't
21
 * had a EE_Model_Field call prepare_for_set on it) then use the model functions as normal. However, if you are calling
22
 * the model functions with values from the model object domain (ie, the code your writing is probably within a model
23
 * object, and all the values you're dealing with have had an EE_Model_Field call prepare_for_set on them), then you'll
24
 * want to set $values_already_prepared_by_model_object to FALSE within the argument-list of the functions you call (in
25
 * order to avoid re-processing those values). If your values are already in the database values domain, you'll either
26
 * way to convert them into the model object domain by creating model objects from those raw db values (ie,using
27
 * EEM_Base::_create_objects), or just use $wpdb directly.
28
 *
29
 * @package               Event Espresso
30
 * @subpackage            core
31
 * @author                Michael Nelson
32
 * @since                 EE4
33
 */
34
abstract class EEM_Base extends EE_Base implements ResettableInterface
35
{
36
37
    /**
38
     * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
     * They almost always WILL NOT, but it's not necessarily a requirement.
41
     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
     *
43
     * @var boolean
44
     */
45
    private $_values_already_prepared_by_model_object = 0;
46
47
    /**
48
     * when $_values_already_prepared_by_model_object equals this, we assume
49
     * the data is just like form input that needs to have the model fields'
50
     * prepare_for_set and prepare_for_use_in_db called on it
51
     */
52
    const not_prepared_by_model_object = 0;
53
54
    /**
55
     * when $_values_already_prepared_by_model_object equals this, we
56
     * assume this value is coming from a model object and doesn't need to have
57
     * prepare_for_set called on it, just prepare_for_use_in_db is used
58
     */
59
    const prepared_by_model_object = 1;
60
61
    /**
62
     * when $_values_already_prepared_by_model_object equals this, we assume
63
     * the values are already to be used in the database (ie no processing is done
64
     * on them by the model's fields)
65
     */
66
    const prepared_for_use_in_db = 2;
67
68
69
    protected $singular_item = 'Item';
70
71
    protected $plural_item   = 'Items';
72
73
    /**
74
     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
     */
76
    protected $_tables;
77
78
    /**
79
     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
     *
83
     * @var \EE_Model_Field_Base[][] $_fields
84
     */
85
    protected $_fields;
86
87
    /**
88
     * array of different kinds of relations
89
     *
90
     * @var \EE_Model_Relation_Base[] $_model_relations
91
     */
92
    protected $_model_relations;
93
94
    /**
95
     * @var \EE_Index[] $_indexes
96
     */
97
    protected $_indexes = array();
98
99
    /**
100
     * Default strategy for getting where conditions on this model. This strategy is used to get default
101
     * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
     * by setting the same columns as used in these queries in the query yourself.
103
     *
104
     * @var EE_Default_Where_Conditions
105
     */
106
    protected $_default_where_conditions_strategy;
107
108
    /**
109
     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
     * This is particularly useful when you want something between 'none' and 'default'
111
     *
112
     * @var EE_Default_Where_Conditions
113
     */
114
    protected $_minimum_where_conditions_strategy;
115
116
    /**
117
     * String describing how to find the "owner" of this model's objects.
118
     * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
     * But when there isn't, this indicates which related model, or transiently-related model,
120
     * has the foreign key to the wp_users table.
121
     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
     * related to events, and events have a foreign key to wp_users.
123
     * On EEM_Transaction, this would be 'Transaction.Event'
124
     *
125
     * @var string
126
     */
127
    protected $_model_chain_to_wp_user = '';
128
129
    /**
130
     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
     * don't need it (particularly CPT models)
132
     *
133
     * @var bool
134
     */
135
    protected $_ignore_where_strategy = false;
136
137
    /**
138
     * String used in caps relating to this model. Eg, if the caps relating to this
139
     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
     *
141
     * @var string. If null it hasn't been initialized yet. If false then we
142
     * have indicated capabilities don't apply to this
143
     */
144
    protected $_caps_slug = null;
145
146
    /**
147
     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
     * and next-level keys are capability names, and each's value is a
149
     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
     * they specify which context to use (ie, frontend, backend, edit or delete)
151
     * and then each capability in the corresponding sub-array that they're missing
152
     * adds the where conditions onto the query.
153
     *
154
     * @var array
155
     */
156
    protected $_cap_restrictions = array(
157
        self::caps_read       => array(),
158
        self::caps_read_admin => array(),
159
        self::caps_edit       => array(),
160
        self::caps_delete     => array(),
161
    );
162
163
    /**
164
     * Array defining which cap restriction generators to use to create default
165
     * cap restrictions to put in EEM_Base::_cap_restrictions.
166
     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
     * automatically set this to false (not just null).
169
     *
170
     * @var EE_Restriction_Generator_Base[]
171
     */
172
    protected $_cap_restriction_generators = array();
173
174
    /**
175
     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
     */
177
    const caps_read       = 'read';
178
179
    const caps_read_admin = 'read_admin';
180
181
    const caps_edit       = 'edit';
182
183
    const caps_delete     = 'delete';
184
185
    /**
186
     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
     * maps to 'read' because when looking for relevant permissions we're going to use
189
     * 'read' in teh capabilities names like 'ee_read_events' etc.
190
     *
191
     * @var array
192
     */
193
    protected $_cap_contexts_to_cap_action_map = array(
194
        self::caps_read       => 'read',
195
        self::caps_read_admin => 'read',
196
        self::caps_edit       => 'edit',
197
        self::caps_delete     => 'delete',
198
    );
199
200
    /**
201
     * Timezone
202
     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
     * EE_Datetime_Field data type will have access to it.
206
     *
207
     * @var string
208
     */
209
    protected $_timezone;
210
211
212
    /**
213
     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
     * multisite.
215
     *
216
     * @var int
217
     */
218
    protected static $_model_query_blog_id;
219
220
    /**
221
     * A copy of _fields, except the array keys are the model names pointed to by
222
     * the field
223
     *
224
     * @var EE_Model_Field_Base[]
225
     */
226
    private $_cache_foreign_key_to_fields = array();
227
228
    /**
229
     * Cached list of all the fields on the model, indexed by their name
230
     *
231
     * @var EE_Model_Field_Base[]
232
     */
233
    private $_cached_fields = null;
234
235
    /**
236
     * Cached list of all the fields on the model, except those that are
237
     * marked as only pertinent to the database
238
     *
239
     * @var EE_Model_Field_Base[]
240
     */
241
    private $_cached_fields_non_db_only = null;
242
243
    /**
244
     * A cached reference to the primary key for quick lookup
245
     *
246
     * @var EE_Model_Field_Base
247
     */
248
    private $_primary_key_field = null;
249
250
    /**
251
     * Flag indicating whether this model has a primary key or not
252
     *
253
     * @var boolean
254
     */
255
    protected $_has_primary_key_field = null;
256
257
    /**
258
     * Whether or not this model is based off a table in WP core only (CPTs should set
259
     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
     * This should be true for models that deal with data that should exist independent of EE.
261
     * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
     * It would be false, however, if you could guarantee the model would only interact with EE data,
263
     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
     * they can only read and insert events and venues custom post types, not arbitrary post types)
265
     * @var boolean
266
     */
267
    protected $_wp_core_model = false;
268
269
    /**
270
     *    List of valid operators that can be used for querying.
271
     * The keys are all operators we'll accept, the values are the real SQL
272
     * operators used
273
     *
274
     * @var array
275
     */
276
    protected $_valid_operators = array(
277
        '='           => '=',
278
        '<='          => '<=',
279
        '<'           => '<',
280
        '>='          => '>=',
281
        '>'           => '>',
282
        '!='          => '!=',
283
        'LIKE'        => 'LIKE',
284
        'like'        => 'LIKE',
285
        'NOT_LIKE'    => 'NOT LIKE',
286
        'not_like'    => 'NOT LIKE',
287
        'NOT LIKE'    => 'NOT LIKE',
288
        'not like'    => 'NOT LIKE',
289
        'IN'          => 'IN',
290
        'in'          => 'IN',
291
        'NOT_IN'      => 'NOT IN',
292
        'not_in'      => 'NOT IN',
293
        'NOT IN'      => 'NOT IN',
294
        'not in'      => 'NOT IN',
295
        'between'     => 'BETWEEN',
296
        'BETWEEN'     => 'BETWEEN',
297
        'IS_NOT_NULL' => 'IS NOT NULL',
298
        'is_not_null' => 'IS NOT NULL',
299
        'IS NOT NULL' => 'IS NOT NULL',
300
        'is not null' => 'IS NOT NULL',
301
        'IS_NULL'     => 'IS NULL',
302
        'is_null'     => 'IS NULL',
303
        'IS NULL'     => 'IS NULL',
304
        'is null'     => 'IS NULL',
305
        'REGEXP'      => 'REGEXP',
306
        'regexp'      => 'REGEXP',
307
        'NOT_REGEXP'  => 'NOT REGEXP',
308
        'not_regexp'  => 'NOT REGEXP',
309
        'NOT REGEXP'  => 'NOT REGEXP',
310
        'not regexp'  => 'NOT REGEXP',
311
    );
312
313
    /**
314
     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
     *
316
     * @var array
317
     */
318
    protected $_in_style_operators = array('IN', 'NOT IN');
319
320
    /**
321
     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
     * '12-31-2012'"
323
     *
324
     * @var array
325
     */
326
    protected $_between_style_operators = array('BETWEEN');
327
328
    /**
329
     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
     * @var array
331
     */
332
    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
    /**
334
     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
     * on a join table.
336
     *
337
     * @var array
338
     */
339
    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
341
    /**
342
     * Allowed values for $query_params['order'] for ordering in queries
343
     *
344
     * @var array
345
     */
346
    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
348
    /**
349
     * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
     * than regular field names. It is assumed that their values are an array of WHERE conditions
351
     *
352
     * @var array
353
     */
354
    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
356
    /**
357
     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
     * 'where', but 'where' clauses are so common that we thought we'd omit it
359
     *
360
     * @var array
361
     */
362
    private $_allowed_query_params = array(
363
        0,
364
        'limit',
365
        'order_by',
366
        'group_by',
367
        'having',
368
        'force_join',
369
        'order',
370
        'on_join_limit',
371
        'default_where_conditions',
372
        'caps',
373
        'extra_selects'
374
    );
375
376
    /**
377
     * All the data types that can be used in $wpdb->prepare statements.
378
     *
379
     * @var array
380
     */
381
    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
383
    /**
384
     * @var EE_Registry $EE
385
     */
386
    protected $EE = null;
387
388
389
    /**
390
     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
     *
392
     * @var int
393
     */
394
    protected $_show_next_x_db_queries = 0;
395
396
    /**
397
     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
     * WHERE, GROUP_BY, etc.
400
     *
401
     * @var CustomSelects
402
     */
403
    protected $_custom_selections = array();
404
405
    /**
406
     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
     * caches every model object we've fetched from the DB on this request
408
     *
409
     * @var array
410
     */
411
    protected $_entity_map;
412
413
    /**
414
     * @var LoaderInterface $loader
415
     */
416
    private static $loader;
417
418
419
    /**
420
     * constant used to show EEM_Base has not yet verified the db on this http request
421
     */
422
    const db_verified_none = 0;
423
424
    /**
425
     * constant used to show EEM_Base has verified the EE core db on this http request,
426
     * but not the addons' dbs
427
     */
428
    const db_verified_core = 1;
429
430
    /**
431
     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
     * the EE core db too)
433
     */
434
    const db_verified_addons = 2;
435
436
    /**
437
     * indicates whether an EEM_Base child has already re-verified the DB
438
     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
     * looking like EEM_Base::db_verified_*
440
     *
441
     * @var int - 0 = none, 1 = core, 2 = addons
442
     */
443
    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
445
    /**
446
     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
     *        registrations for non-trashed tickets for non-trashed datetimes)
449
     */
450
    const default_where_conditions_all = 'all';
451
452
    /**
453
     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
     *        models which share tables with other models, this can return data for the wrong model.
458
     */
459
    const default_where_conditions_this_only = 'this_model_only';
460
461
    /**
462
     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
     */
466
    const default_where_conditions_others_only = 'other_models_only';
467
468
    /**
469
     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
     *        (regardless of whether those events and venues are trashed)
474
     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
     *        events.
476
     */
477
    const default_where_conditions_minimum_all = 'minimum';
478
479
    /**
480
     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
     *        not)
484
     */
485
    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
487
    /**
488
     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
     *        it's possible it will return table entries for other models. You should use
491
     *        EEM_Base::default_where_conditions_minimum_all instead.
492
     */
493
    const default_where_conditions_none = 'none';
494
495
496
497
    /**
498
     * About all child constructors:
499
     * they should define the _tables, _fields and _model_relations arrays.
500
     * Should ALWAYS be called after child constructor.
501
     * In order to make the child constructors to be as simple as possible, this parent constructor
502
     * finalizes constructing all the object's attributes.
503
     * Generally, rather than requiring a child to code
504
     * $this->_tables = array(
505
     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
     *        ...);
507
     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
     * each EE_Table has a function to set the table's alias after the constructor, using
509
     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
     * do something similar.
511
     *
512
     * @param null $timezone
513
     * @throws EE_Error
514
     */
515
    protected function __construct($timezone = null)
516
    {
517
        // check that the model has not been loaded too soon
518
        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
            throw new EE_Error (
520
                sprintf(
521
                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
                        'event_espresso'),
523
                    get_class($this)
524
                )
525
            );
526
        }
527
        /**
528
         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
         */
530
        if (empty(EEM_Base::$_model_query_blog_id)) {
531
            EEM_Base::set_model_query_blog_id();
532
        }
533
        /**
534
         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
         * just use EE_Register_Model_Extension
536
         *
537
         * @var EE_Table_Base[] $_tables
538
         */
539
        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
        foreach ($this->_tables as $table_alias => $table_obj) {
541
            /** @var $table_obj EE_Table_Base */
542
            $table_obj->_construct_finalize_with_alias($table_alias);
543
            if ($table_obj instanceof EE_Secondary_Table) {
544
                /** @var $table_obj EE_Secondary_Table */
545
                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
            }
547
        }
548
        /**
549
         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
         * EE_Register_Model_Extension
551
         *
552
         * @param EE_Model_Field_Base[] $_fields
553
         */
554
        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
        $this->_invalidate_field_caches();
556
        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
            if (! array_key_exists($table_alias, $this->_tables)) {
558
                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
            }
561
            foreach ($fields_for_table as $field_name => $field_obj) {
562
                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
                //primary key field base has a slightly different _construct_finalize
564
                /** @var $field_obj EE_Model_Field_Base */
565
                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
            }
567
        }
568
        // everything is related to Extra_Meta
569
        if (get_class($this) !== 'EEM_Extra_Meta') {
570
            //make extra meta related to everything, but don't block deleting things just
571
            //because they have related extra meta info. For now just orphan those extra meta
572
            //in the future we should automatically delete them
573
            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
        }
575
        //and change logs
576
        if (get_class($this) !== 'EEM_Change_Log') {
577
            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
        }
579
        /**
580
         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
         * EE_Register_Model_Extension
582
         *
583
         * @param EE_Model_Relation_Base[] $_model_relations
584
         */
585
        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
            $this->_model_relations);
587
        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
            /** @var $relation_obj EE_Model_Relation_Base */
589
            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
        }
591
        foreach ($this->_indexes as $index_name => $index_obj) {
592
            /** @var $index_obj EE_Index */
593
            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
        }
595
        $this->set_timezone($timezone);
596
        //finalize default where condition strategy, or set default
597
        if (! $this->_default_where_conditions_strategy) {
598
            //nothing was set during child constructor, so set default
599
            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
        }
601
        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
        if (! $this->_minimum_where_conditions_strategy) {
603
            //nothing was set during child constructor, so set default
604
            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
        }
606
        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
        //to indicate to NOT set it, set it to the logical default
609
        if ($this->_caps_slug === null) {
610
            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
        }
612
        //initialize the standard cap restriction generators if none were specified by the child constructor
613
        if ($this->_cap_restriction_generators !== false) {
614
            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
                        new EE_Restriction_Generator_Protected(),
619
                        $cap_context,
620
                        $this
621
                    );
622
                }
623
            }
624
        }
625
        //if there are cap restriction generators, use them to make the default cap restrictions
626
        if ($this->_cap_restriction_generators !== false) {
627
            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
                if (! $generator_object) {
629
                    continue;
630
                }
631 View Code Duplication
                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
                    throw new EE_Error(
633
                        sprintf(
634
                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
                                'event_espresso'),
636
                            $context,
637
                            $this->get_this_model_name()
638
                        )
639
                    );
640
                }
641
                $action = $this->cap_action_for_context($context);
642
                if (! $generator_object->construction_finalized()) {
643
                    $generator_object->_construct_finalize($this, $action);
644
                }
645
            }
646
        }
647
        do_action('AHEE__' . get_class($this) . '__construct__end');
648
    }
649
650
651
652
    /**
653
     * Used to set the $_model_query_blog_id static property.
654
     *
655
     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
656
     *                      value for get_current_blog_id() will be used.
657
     */
658
    public static function set_model_query_blog_id($blog_id = 0)
659
    {
660
        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
661
    }
662
663
664
665
    /**
666
     * Returns whatever is set as the internal $model_query_blog_id.
667
     *
668
     * @return int
669
     */
670
    public static function get_model_query_blog_id()
671
    {
672
        return EEM_Base::$_model_query_blog_id;
673
    }
674
675
676
677
    /**
678
     * This function is a singleton method used to instantiate the Espresso_model object
679
     *
680
     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
681
     *                                (and any incoming timezone data that gets saved).
682
     *                                Note this just sends the timezone info to the date time model field objects.
683
     *                                Default is NULL
684
     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
685
     * @return static (as in the concrete child class)
686
     * @throws EE_Error
687
     * @throws InvalidArgumentException
688
     * @throws InvalidDataTypeException
689
     * @throws InvalidInterfaceException
690
     */
691
    public static function instance($timezone = null)
692
    {
693
        // check if instance of Espresso_model already exists
694
        if (! static::$_instance instanceof static) {
695
            // instantiate Espresso_model
696
            static::$_instance = new static(
697
                $timezone,
698
                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
699
            );
700
        }
701
        //we might have a timezone set, let set_timezone decide what to do with it
702
        static::$_instance->set_timezone($timezone);
703
        // Espresso_model object
704
        return static::$_instance;
705
    }
706
707
708
709
    /**
710
     * resets the model and returns it
711
     *
712
     * @param null | string $timezone
713
     * @return EEM_Base|null (if the model was already instantiated, returns it, with
714
     * all its properties reset; if it wasn't instantiated, returns null)
715
     * @throws EE_Error
716
     * @throws ReflectionException
717
     * @throws InvalidArgumentException
718
     * @throws InvalidDataTypeException
719
     * @throws InvalidInterfaceException
720
     */
721
    public static function reset($timezone = null)
722
    {
723
        if (static::$_instance instanceof EEM_Base) {
724
            //let's try to NOT swap out the current instance for a new one
725
            //because if someone has a reference to it, we can't remove their reference
726
            //so it's best to keep using the same reference, but change the original object
727
            //reset all its properties to their original values as defined in the class
728
            $r = new ReflectionClass(get_class(static::$_instance));
729
            $static_properties = $r->getStaticProperties();
730
            foreach ($r->getDefaultProperties() as $property => $value) {
731
                //don't set instance to null like it was originally,
732
                //but it's static anyways, and we're ignoring static properties (for now at least)
733
                if (! isset($static_properties[$property])) {
734
                    static::$_instance->{$property} = $value;
735
                }
736
            }
737
            //and then directly call its constructor again, like we would if we were creating a new one
738
            static::$_instance->__construct(
739
                $timezone,
740
                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
741
            );
742
            return self::instance();
743
        }
744
        return null;
745
    }
746
747
748
749
    /**
750
     * @return LoaderInterface
751
     * @throws InvalidArgumentException
752
     * @throws InvalidDataTypeException
753
     * @throws InvalidInterfaceException
754
     */
755
    private static function getLoader()
756
    {
757
        if(! EEM_Base::$loader instanceof LoaderInterface) {
758
            EEM_Base::$loader = LoaderFactory::getLoader();
759
        }
760
        return EEM_Base::$loader;
761
    }
762
763
764
765
    /**
766
     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
767
     *
768
     * @param  boolean $translated return localized strings or JUST the array.
769
     * @return array
770
     * @throws EE_Error
771
     * @throws InvalidArgumentException
772
     * @throws InvalidDataTypeException
773
     * @throws InvalidInterfaceException
774
     */
775
    public function status_array($translated = false)
776
    {
777
        if (! array_key_exists('Status', $this->_model_relations)) {
778
            return array();
779
        }
780
        $model_name = $this->get_this_model_name();
781
        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
782
        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
783
        $status_array = array();
784
        foreach ($stati as $status) {
785
            $status_array[$status->ID()] = $status->get('STS_code');
786
        }
787
        return $translated
788
            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
789
            : $status_array;
790
    }
791
792
793
794
    /**
795
     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
796
     *
797
     * @param array $query_params             {
798
     * @var array $0 (where) array {
799
     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
800
     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
801
     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
802
     *                                        conditions based on related models (and even
803
     *                                        models-related-to-related-models) prepend the model's name onto the field
804
     *                                        name. Eg,
805
     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
806
     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
807
     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
808
     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
809
     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
810
     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
811
     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
812
     *                                        to Venues (even when each of those models actually consisted of two
813
     *                                        tables). Also, you may chain the model relations together. Eg instead of
814
     *                                        just having
815
     *                                        "Venue.VNU_ID", you could have
816
     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
817
     *                                        events are related to Registrations, which are related to Attendees). You
818
     *                                        can take it even further with
819
     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
820
     *                                        (from the default of '='), change the value to an numerically-indexed
821
     *                                        array, where the first item in the list is the operator. eg: array(
822
     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
823
     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
824
     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
825
     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
826
     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
827
     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
828
     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
829
     *                                        the operator is IN. Also, values can actually be field names. To indicate
830
     *                                        the value is a field, simply provide a third array item (true) to the
831
     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
832
     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
833
     *                                        Note: you can also use related model field names like you would any other
834
     *                                        field name. eg:
835
     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
836
     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
837
     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
838
     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
839
     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
840
     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
841
     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
842
     *                                        to be what you last specified. IE, "AND"s by default, but if you had
843
     *                                        previously specified to use ORs to join, ORs will continue to be used.
844
     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
845
     *                                        "stick" until you specify an AND. eg
846
     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
847
     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
848
     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
849
     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
850
     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
851
     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
852
     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
853
     *                                        too, eg:
854
     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
855
     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
856
     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
857
     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
858
     *                                        Remember when you provide two numbers for the limit, the 1st number is
859
     *                                        the OFFSET, the 2nd is the LIMIT
860
     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
861
     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
862
     *                                        following format array('on_join_limit'
863
     *                                        => array( 'table_alias', array(1,2) ) ).
864
     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
865
     *                                        values are either 'ASC' or 'DESC'.
866
     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
867
     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
868
     *                                        DESC..." respectively. Like the
869
     *                                        'where' conditions, these fields can be on related models. Eg
870
     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
871
     *                                        perfectly valid from any model related to 'Registration' (like Event,
872
     *                                        Attendee, Price, Datetime, etc.)
873
     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
874
     *                                        'order' specifies whether to order the field specified in 'order_by' in
875
     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
876
     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
877
     *                                        order by the primary key. Eg,
878
     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
879
     *                                        //(will join with the Datetime model's table(s) and order by its field
880
     *                                        DTT_EVT_start) or
881
     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
882
     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
883
     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
884
     *                                        'group_by'=>'VNU_ID', or
885
     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
886
     *                                        if no
887
     *                                        $group_by is specified, and a limit is set, automatically groups by the
888
     *                                        model's primary key (or combined primary keys). This avoids some
889
     *                                        weirdness that results when using limits, tons of joins, and no group by,
890
     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
891
     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
892
     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
893
     *                                        results)
894
     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
895
     *                                        array where values are models to be joined in the query.Eg
896
     *                                        array('Attendee','Payment','Datetime'). You may join with transient
897
     *                                        models using period, eg "Registration.Transaction.Payment". You will
898
     *                                        probably only want to do this in hopes of increasing efficiency, as
899
     *                                        related models which belongs to the current model
900
     *                                        (ie, the current model has a foreign key to them, like how Registration
901
     *                                        belongs to Attendee) can be cached in order to avoid future queries
902
     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
903
     *                                        set this to 'none' to disable all default where conditions. Eg, usually
904
     *                                        soft-deleted objects are filtered-out if you want to include them, set
905
     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
906
     *                                        default where conditions set it to 'other_models_only'. If you only want
907
     *                                        this model's default where conditions added to the query, use
908
     *                                        'this_model_only'. If you want to use all default where conditions
909
     *                                        (default), set to 'all'.
910
     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
911
     *                                        we just NOT apply any capabilities/permissions/restrictions and return
912
     *                                        everything? Or should we only show the current user items they should be
913
     *                                        able to view on the frontend, backend, edit, or delete? can be set to
914
     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
915
     *                                        }
916
     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
917
     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
918
     *                                        again. Array keys are object IDs (if there is a primary key on the model.
919
     *                                        if not, numerically indexed) Some full examples: get 10 transactions
920
     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
921
     *                                        array( array(
922
     *                                        'OR'=>array(
923
     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
924
     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
925
     *                                        )
926
     *                                        ),
927
     *                                        'limit'=>10,
928
     *                                        'group_by'=>'TXN_ID'
929
     *                                        ));
930
     *                                        get all the answers to the question titled "shirt size" for event with id
931
     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
932
     *                                        'Question.QST_display_text'=>'shirt size',
933
     *                                        'Registration.Event.EVT_ID'=>12
934
     *                                        ),
935
     *                                        'order_by'=>array('ANS_value'=>'ASC')
936
     *                                        ));
937
     * @throws EE_Error
938
     */
939
    public function get_all($query_params = array())
940
    {
941
        if (isset($query_params['limit'])
942
            && ! isset($query_params['group_by'])
943
        ) {
944
            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
945
        }
946
        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
947
    }
948
949
950
951
    /**
952
     * Modifies the query parameters so we only get back model objects
953
     * that "belong" to the current user
954
     *
955
     * @param array $query_params @see EEM_Base::get_all()
956
     * @return array like EEM_Base::get_all
957
     */
958
    public function alter_query_params_to_only_include_mine($query_params = array())
959
    {
960
        $wp_user_field_name = $this->wp_user_field_name();
961
        if ($wp_user_field_name) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $wp_user_field_name of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
962
            $query_params[0][$wp_user_field_name] = get_current_user_id();
963
        }
964
        return $query_params;
965
    }
966
967
968
969
    /**
970
     * Returns the name of the field's name that points to the WP_User table
971
     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
972
     * foreign key to the WP_User table)
973
     *
974
     * @return string|boolean string on success, boolean false when there is no
975
     * foreign key to the WP_User table
976
     */
977
    public function wp_user_field_name()
978
    {
979
        try {
980
            if (! empty($this->_model_chain_to_wp_user)) {
981
                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982
                $last_model_name = end($models_to_follow_to_wp_users);
983
                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
985
            } else {
986
                $model_with_fk_to_wp_users = $this;
987
                $model_chain_to_wp_user = '';
988
            }
989
            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
            return $model_chain_to_wp_user . $wp_user_field->get_name();
991
        } catch (EE_Error $e) {
992
            return false;
993
        }
994
    }
995
996
997
998
    /**
999
     * Returns the _model_chain_to_wp_user string, which indicates which related model
1000
     * (or transiently-related model) has a foreign key to the wp_users table;
1001
     * useful for finding if model objects of this type are 'owned' by the current user.
1002
     * This is an empty string when the foreign key is on this model and when it isn't,
1003
     * but is only non-empty when this model's ownership is indicated by a RELATED model
1004
     * (or transiently-related model)
1005
     *
1006
     * @return string
1007
     */
1008
    public function model_chain_to_wp_user()
1009
    {
1010
        return $this->_model_chain_to_wp_user;
1011
    }
1012
1013
1014
1015
    /**
1016
     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1017
     * like how registrations don't have a foreign key to wp_users, but the
1018
     * events they are for are), or is unrelated to wp users.
1019
     * generally available
1020
     *
1021
     * @return boolean
1022
     */
1023
    public function is_owned()
1024
    {
1025
        if ($this->model_chain_to_wp_user()) {
1026
            return true;
1027
        }
1028
        try {
1029
            $this->get_foreign_key_to('WP_User');
1030
            return true;
1031
        } catch (EE_Error $e) {
1032
            return false;
1033
        }
1034
    }
1035
1036
1037
    /**
1038
     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1039
     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1040
     * the model)
1041
     *
1042
     * @param array  $query_params      like EEM_Base::get_all's $query_params
1043
     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1044
     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1045
     *                                  fields on the model, and the models we joined to in the query. However, you can
1046
     *                                  override this and set the select to "*", or a specific column name, like
1047
     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1048
     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1049
     *                                  the aliases used to refer to this selection, and values are to be
1050
     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1051
     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1052
     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1053
     * @throws EE_Error
1054
     * @throws InvalidArgumentException
1055
     */
1056
    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057
    {
1058
        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1059
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1060
        $select_expressions = $columns_to_select === null
1061
            ? $this->_construct_default_select_sql($model_query_info)
1062
            : '';
1063
        if ($this->_custom_selections instanceof CustomSelects) {
1064
            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065
            $select_expressions .= $select_expressions
1066
                ? ', ' . $custom_expressions
1067
                : $custom_expressions;
1068
        }
1069
1070
        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1071
        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072
    }
1073
1074
1075
    /**
1076
     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1077
     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1078
     * method of including extra select information.
1079
     *
1080
     * @param array             $query_params
1081
     * @param null|array|string $columns_to_select
1082
     * @return null|CustomSelects
1083
     * @throws InvalidArgumentException
1084
     */
1085
    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086
    {
1087
        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088
            return null;
1089
        }
1090
        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1091
        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1092
        return new CustomSelects($selects);
1093
    }
1094
1095
1096
1097
    /**
1098
     * Gets an array of rows from the database just like $wpdb->get_results would,
1099
     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1100
     * take care of joins, field preparation etc.
1101
     *
1102
     * @param array  $query_params      like EEM_Base::get_all's $query_params
1103
     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1104
     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1105
     *                                  fields on the model, and the models we joined to in the query. However, you can
1106
     *                                  override this and set the select to "*", or a specific column name, like
1107
     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1108
     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1109
     *                                  the aliases used to refer to this selection, and values are to be
1110
     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1111
     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1112
     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1113
     * @throws EE_Error
1114
     */
1115
    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1116
    {
1117
        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1118
    }
1119
1120
1121
1122
    /**
1123
     * For creating a custom select statement
1124
     *
1125
     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1126
     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1127
     *                                 SQL, and 1=>is the datatype
1128
     * @throws EE_Error
1129
     * @return string
1130
     */
1131
    private function _construct_select_from_input($columns_to_select)
1132
    {
1133
        if (is_array($columns_to_select)) {
1134
            $select_sql_array = array();
1135
            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137
                    throw new EE_Error(
1138
                        sprintf(
1139
                            __(
1140
                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1141
                                'event_espresso'
1142
                            ),
1143
                            $selection_and_datatype,
1144
                            $alias
1145
                        )
1146
                    );
1147
                }
1148 View Code Duplication
                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149
                    throw new EE_Error(
1150
                        sprintf(
1151
                            esc_html__(
1152
                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1153
                                'event_espresso'
1154
                            ),
1155
                            $selection_and_datatype[1],
1156
                            $selection_and_datatype[0],
1157
                            $alias,
1158
                            implode(', ', $this->_valid_wpdb_data_types)
1159
                        )
1160
                    );
1161
                }
1162
                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1163
            }
1164
            $columns_to_select_string = implode(', ', $select_sql_array);
1165
        } else {
1166
            $columns_to_select_string = $columns_to_select;
1167
        }
1168
        return $columns_to_select_string;
1169
    }
1170
1171
1172
1173
    /**
1174
     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1175
     *
1176
     * @return string
1177
     * @throws EE_Error
1178
     */
1179
    public function primary_key_name()
1180
    {
1181
        return $this->get_primary_key_field()->get_name();
1182
    }
1183
1184
1185
1186
    /**
1187
     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1188
     * If there is no primary key on this model, $id is treated as primary key string
1189
     *
1190
     * @param mixed $id int or string, depending on the type of the model's primary key
1191
     * @return EE_Base_Class
1192
     */
1193
    public function get_one_by_ID($id)
1194
    {
1195
        if ($this->get_from_entity_map($id)) {
1196
            return $this->get_from_entity_map($id);
1197
        }
1198
        return $this->get_one(
1199
            $this->alter_query_params_to_restrict_by_ID(
1200
                $id,
1201
                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1202
            )
1203
        );
1204
    }
1205
1206
1207
1208
    /**
1209
     * Alters query parameters to only get items with this ID are returned.
1210
     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1211
     * or could just be a simple primary key ID
1212
     *
1213
     * @param int   $id
1214
     * @param array $query_params
1215
     * @return array of normal query params, @see EEM_Base::get_all
1216
     * @throws EE_Error
1217
     */
1218
    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219
    {
1220
        if (! isset($query_params[0])) {
1221
            $query_params[0] = array();
1222
        }
1223
        $conditions_from_id = $this->parse_index_primary_key_string($id);
1224
        if ($conditions_from_id === null) {
1225
            $query_params[0][$this->primary_key_name()] = $id;
1226
        } else {
1227
            //no primary key, so the $id must be from the get_index_primary_key_string()
1228
            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
        }
1230
        return $query_params;
1231
    }
1232
1233
1234
1235
    /**
1236
     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1237
     * array. If no item is found, null is returned.
1238
     *
1239
     * @param array $query_params like EEM_Base's $query_params variable.
1240
     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1241
     * @throws EE_Error
1242
     */
1243 View Code Duplication
    public function get_one($query_params = array())
1244
    {
1245
        if (! is_array($query_params)) {
1246
            EE_Error::doing_it_wrong('EEM_Base::get_one',
1247
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248
                    gettype($query_params)), '4.6.0');
1249
            $query_params = array();
1250
        }
1251
        $query_params['limit'] = 1;
1252
        $items = $this->get_all($query_params);
1253
        if (empty($items)) {
1254
            return null;
1255
        }
1256
        return array_shift($items);
1257
    }
1258
1259
1260
1261
    /**
1262
     * Returns the next x number of items in sequence from the given value as
1263
     * found in the database matching the given query conditions.
1264
     *
1265
     * @param mixed $current_field_value    Value used for the reference point.
1266
     * @param null  $field_to_order_by      What field is used for the
1267
     *                                      reference point.
1268
     * @param int   $limit                  How many to return.
1269
     * @param array $query_params           Extra conditions on the query.
1270
     * @param null  $columns_to_select      If left null, then an array of
1271
     *                                      EE_Base_Class objects is returned,
1272
     *                                      otherwise you can indicate just the
1273
     *                                      columns you want returned.
1274
     * @return EE_Base_Class[]|array
1275
     * @throws EE_Error
1276
     */
1277
    public function next_x(
1278
        $current_field_value,
1279
        $field_to_order_by = null,
1280
        $limit = 1,
1281
        $query_params = array(),
1282
        $columns_to_select = null
1283
    ) {
1284
        return $this->_get_consecutive(
1285
            $current_field_value,
1286
            '>',
1287
            $field_to_order_by,
1288
            $limit,
1289
            $query_params,
1290
            $columns_to_select
1291
        );
1292
    }
1293
1294
1295
1296
    /**
1297
     * Returns the previous x number of items in sequence from the given value
1298
     * as found in the database matching the given query conditions.
1299
     *
1300
     * @param mixed $current_field_value    Value used for the reference point.
1301
     * @param null  $field_to_order_by      What field is used for the
1302
     *                                      reference point.
1303
     * @param int   $limit                  How many to return.
1304
     * @param array $query_params           Extra conditions on the query.
1305
     * @param null  $columns_to_select      If left null, then an array of
1306
     *                                      EE_Base_Class objects is returned,
1307
     *                                      otherwise you can indicate just the
1308
     *                                      columns you want returned.
1309
     * @return EE_Base_Class[]|array
1310
     * @throws EE_Error
1311
     */
1312
    public function previous_x(
1313
        $current_field_value,
1314
        $field_to_order_by = null,
1315
        $limit = 1,
1316
        $query_params = array(),
1317
        $columns_to_select = null
1318
    ) {
1319
        return $this->_get_consecutive(
1320
            $current_field_value,
1321
            '<',
1322
            $field_to_order_by,
1323
            $limit,
1324
            $query_params,
1325
            $columns_to_select
1326
        );
1327
    }
1328
1329
1330
1331
    /**
1332
     * Returns the next item in sequence from the given value as found in the
1333
     * database matching the given query conditions.
1334
     *
1335
     * @param mixed $current_field_value    Value used for the reference point.
1336
     * @param null  $field_to_order_by      What field is used for the
1337
     *                                      reference point.
1338
     * @param array $query_params           Extra conditions on the query.
1339
     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1340
     *                                      object is returned, otherwise you
1341
     *                                      can indicate just the columns you
1342
     *                                      want and a single array indexed by
1343
     *                                      the columns will be returned.
1344
     * @return EE_Base_Class|null|array()
1345
     * @throws EE_Error
1346
     */
1347 View Code Duplication
    public function next(
1348
        $current_field_value,
1349
        $field_to_order_by = null,
1350
        $query_params = array(),
1351
        $columns_to_select = null
1352
    ) {
1353
        $results = $this->_get_consecutive(
1354
            $current_field_value,
1355
            '>',
1356
            $field_to_order_by,
1357
            1,
1358
            $query_params,
1359
            $columns_to_select
1360
        );
1361
        return empty($results) ? null : reset($results);
1362
    }
1363
1364
1365
1366
    /**
1367
     * Returns the previous item in sequence from the given value as found in
1368
     * the database matching the given query conditions.
1369
     *
1370
     * @param mixed $current_field_value    Value used for the reference point.
1371
     * @param null  $field_to_order_by      What field is used for the
1372
     *                                      reference point.
1373
     * @param array $query_params           Extra conditions on the query.
1374
     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1375
     *                                      object is returned, otherwise you
1376
     *                                      can indicate just the columns you
1377
     *                                      want and a single array indexed by
1378
     *                                      the columns will be returned.
1379
     * @return EE_Base_Class|null|array()
1380
     * @throws EE_Error
1381
     */
1382 View Code Duplication
    public function previous(
1383
        $current_field_value,
1384
        $field_to_order_by = null,
1385
        $query_params = array(),
1386
        $columns_to_select = null
1387
    ) {
1388
        $results = $this->_get_consecutive(
1389
            $current_field_value,
1390
            '<',
1391
            $field_to_order_by,
1392
            1,
1393
            $query_params,
1394
            $columns_to_select
1395
        );
1396
        return empty($results) ? null : reset($results);
1397
    }
1398
1399
1400
1401
    /**
1402
     * Returns the a consecutive number of items in sequence from the given
1403
     * value as found in the database matching the given query conditions.
1404
     *
1405
     * @param mixed  $current_field_value   Value used for the reference point.
1406
     * @param string $operand               What operand is used for the sequence.
1407
     * @param string $field_to_order_by     What field is used for the reference point.
1408
     * @param int    $limit                 How many to return.
1409
     * @param array  $query_params          Extra conditions on the query.
1410
     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1411
     *                                      otherwise you can indicate just the columns you want returned.
1412
     * @return EE_Base_Class[]|array
1413
     * @throws EE_Error
1414
     */
1415
    protected function _get_consecutive(
1416
        $current_field_value,
1417
        $operand = '>',
1418
        $field_to_order_by = null,
1419
        $limit = 1,
1420
        $query_params = array(),
1421
        $columns_to_select = null
1422
    ) {
1423
        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1424
        if (empty($field_to_order_by)) {
1425
            if ($this->has_primary_key_field()) {
1426
                $field_to_order_by = $this->get_primary_key_field()->get_name();
1427
            } else {
1428
                if (WP_DEBUG) {
1429
                    throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1430
                        'event_espresso'));
1431
                }
1432
                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1433
                return array();
1434
            }
1435
        }
1436
        if (! is_array($query_params)) {
1437
            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439
                    gettype($query_params)), '4.6.0');
1440
            $query_params = array();
1441
        }
1442
        //let's add the where query param for consecutive look up.
1443
        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444
        $query_params['limit'] = $limit;
1445
        //set direction
1446
        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1447
        $query_params['order_by'] = $operand === '>'
1448
            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1449
            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1450
        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
        if (empty($columns_to_select)) {
1452
            return $this->get_all($query_params);
1453
        }
1454
        //getting just the fields
1455
        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
    }
1457
1458
1459
1460
    /**
1461
     * This sets the _timezone property after model object has been instantiated.
1462
     *
1463
     * @param null | string $timezone valid PHP DateTimeZone timezone string
1464
     */
1465
    public function set_timezone($timezone)
1466
    {
1467
        if ($timezone !== null) {
1468
            $this->_timezone = $timezone;
1469
        }
1470
        //note we need to loop through relations and set the timezone on those objects as well.
1471
        foreach ($this->_model_relations as $relation) {
1472
            $relation->set_timezone($timezone);
1473
        }
1474
        //and finally we do the same for any datetime fields
1475
        foreach ($this->_fields as $field) {
1476
            if ($field instanceof EE_Datetime_Field) {
1477
                $field->set_timezone($timezone);
1478
            }
1479
        }
1480
    }
1481
1482
1483
1484
    /**
1485
     * This just returns whatever is set for the current timezone.
1486
     *
1487
     * @access public
1488
     * @return string
1489
     */
1490
    public function get_timezone()
1491
    {
1492
        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1493
        if (empty($this->_timezone)) {
1494
            foreach ($this->_fields as $field) {
1495
                if ($field instanceof EE_Datetime_Field) {
1496
                    $this->set_timezone($field->get_timezone());
1497
                    break;
1498
                }
1499
            }
1500
        }
1501
        //if timezone STILL empty then return the default timezone for the site.
1502
        if (empty($this->_timezone)) {
1503
            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1504
        }
1505
        return $this->_timezone;
1506
    }
1507
1508
1509
1510
    /**
1511
     * This returns the date formats set for the given field name and also ensures that
1512
     * $this->_timezone property is set correctly.
1513
     *
1514
     * @since 4.6.x
1515
     * @param string $field_name The name of the field the formats are being retrieved for.
1516
     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1517
     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1518
     * @return array formats in an array with the date format first, and the time format last.
1519
     */
1520
    public function get_formats_for($field_name, $pretty = false)
1521
    {
1522
        $field_settings = $this->field_settings_for($field_name);
1523
        //if not a valid EE_Datetime_Field then throw error
1524
        if (! $field_settings instanceof EE_Datetime_Field) {
1525
            throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1526
                'event_espresso'), $field_name));
1527
        }
1528
        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1529
        //the field.
1530
        $this->_timezone = $field_settings->get_timezone();
1531
        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1532
    }
1533
1534
1535
1536
    /**
1537
     * This returns the current time in a format setup for a query on this model.
1538
     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
     * it will return:
1540
     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
     *  NOW
1542
     *  - or a unix timestamp (equivalent to time())
1543
     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
     * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
     * @since 4.6.x
1547
     * @param string $field_name       The field the current time is needed for.
1548
     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
     *                                 formatted string matching the set format for the field in the set timezone will
1550
     *                                 be returned.
1551
     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1553
     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1554
     *                                 exception is triggered.
1555
     */
1556
    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1557
    {
1558
        $formats = $this->get_formats_for($field_name);
1559
        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1560
        if ($timestamp) {
1561
            return $DateTime->format('U');
1562
        }
1563
        //not returning timestamp, so return formatted string in timezone.
1564
        switch ($what) {
1565
            case 'time' :
1566
                return $DateTime->format($formats[1]);
1567
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1568
            case 'date' :
1569
                return $DateTime->format($formats[0]);
1570
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1571
            default :
1572
                return $DateTime->format(implode(' ', $formats));
1573
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1574
        }
1575
    }
1576
1577
1578
1579
    /**
1580
     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
     * for the model are.  Returns a DateTime object.
1582
     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
     * ignored.
1585
     *
1586
     * @param string $field_name      The field being setup.
1587
     * @param string $timestring      The date time string being used.
1588
     * @param string $incoming_format The format for the time string.
1589
     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
     *                                format is
1592
     *                                'U', this is ignored.
1593
     * @return DateTime
1594
     * @throws EE_Error
1595
     */
1596
    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
    {
1598
        //just using this to ensure the timezone is set correctly internally
1599
        $this->get_formats_for($field_name);
1600
        //load EEH_DTT_Helper
1601
        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1604
    }
1605
1606
1607
1608
    /**
1609
     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1610
     *
1611
     * @return EE_Table_Base[]
1612
     */
1613
    public function get_tables()
1614
    {
1615
        return $this->_tables;
1616
    }
1617
1618
1619
1620
    /**
1621
     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1622
     * also updates all the model objects, where the criteria expressed in $query_params are met..
1623
     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1624
     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1625
     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1626
     * model object with EVT_ID = 1
1627
     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1628
     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1629
     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1630
     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1631
     * are not specified)
1632
     *
1633
     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1634
     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1635
     *                                         are to be serialized. Basically, the values are what you'd expect to be
1636
     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1637
     *                                         we wanted to update only the TXN_details on any Transactions where its
1638
     *                                         ID=34, we'd use this method as follows:
1639
     *                                         EEM_Transaction::instance()->update(
1640
     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1641
     *                                         array(array('TXN_ID'=>34)));
1642
     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1643
     *                                         in client code into what's expected to be stored on each field. Eg,
1644
     *                                         consider updating Question's QST_admin_label field is of type
1645
     *                                         Simple_HTML. If you use this function to update that field to $new_value
1646
     *                                         = (note replace 8's with appropriate opening and closing tags in the
1647
     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1648
     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1649
     *                                         TRUE, it is assumed that you've already called
1650
     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1651
     *                                         malicious javascript. However, if
1652
     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1653
     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1654
     *                                         and every other field, before insertion. We provide this parameter
1655
     *                                         because model objects perform their prepare_for_set function on all
1656
     *                                         their values, and so don't need to be called again (and in many cases,
1657
     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1658
     *                                         prepare_for_set method...)
1659
     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1660
     *                                         in this model's entity map according to $fields_n_values that match
1661
     *                                         $query_params. This obviously has some overhead, so you can disable it
1662
     *                                         by setting this to FALSE, but be aware that model objects being used
1663
     *                                         could get out-of-sync with the database
1664
     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1665
     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1666
     *                                         bad)
1667
     * @throws EE_Error
1668
     */
1669
    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1670
    {
1671
        if (! is_array($query_params)) {
1672
            EE_Error::doing_it_wrong('EEM_Base::update',
1673
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1674
                    gettype($query_params)), '4.6.0');
1675
            $query_params = array();
1676
        }
1677
        /**
1678
         * Action called before a model update call has been made.
1679
         *
1680
         * @param EEM_Base $model
1681
         * @param array    $fields_n_values the updated fields and their new values
1682
         * @param array    $query_params    @see EEM_Base::get_all()
1683
         */
1684
        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1685
        /**
1686
         * Filters the fields about to be updated given the query parameters. You can provide the
1687
         * $query_params to $this->get_all() to find exactly which records will be updated
1688
         *
1689
         * @param array    $fields_n_values fields and their new values
1690
         * @param EEM_Base $model           the model being queried
1691
         * @param array    $query_params    see EEM_Base::get_all()
1692
         */
1693
        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1694
            $query_params);
1695
        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1696
        //to do that, for each table, verify that it's PK isn't null.
1697
        $tables = $this->get_tables();
1698
        //and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1699
        //NOTE: we should make this code more efficient by NOT querying twice
1700
        //before the real update, but that needs to first go through ALPHA testing
1701
        //as it's dangerous. says Mike August 8 2014
1702
        //we want to make sure the default_where strategy is ignored
1703
        $this->_ignore_where_strategy = true;
1704
        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1705
        foreach ($wpdb_select_results as $wpdb_result) {
1706
            // type cast stdClass as array
1707
            $wpdb_result = (array)$wpdb_result;
1708
            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1709
            if ($this->has_primary_key_field()) {
1710
                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1711
            } else {
1712
                //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)
1713
                $main_table_pk_value = null;
1714
            }
1715
            //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
1716
            //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
1717
            if (count($tables) > 1) {
1718
                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1719
                //in that table, and so we'll want to insert one
1720
                foreach ($tables as $table_obj) {
1721
                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1722
                    //if there is no private key for this table on the results, it means there's no entry
1723
                    //in this table, right? so insert a row in the current table, using any fields available
1724
                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1725
                           && $wpdb_result[$this_table_pk_column])
1726
                    ) {
1727
                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1728
                            $main_table_pk_value);
1729
                        //if we died here, report the error
1730
                        if (! $success) {
1731
                            return false;
1732
                        }
1733
                    }
1734
                }
1735
            }
1736
            //				//and now check that if we have cached any models by that ID on the model, that
1737
            //				//they also get updated properly
1738
            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1739
            //				if( $model_object ){
1740
            //					foreach( $fields_n_values as $field => $value ){
1741
            //						$model_object->set($field, $value);
1742
            //let's make sure default_where strategy is followed now
1743
            $this->_ignore_where_strategy = false;
1744
        }
1745
        //if we want to keep model objects in sync, AND
1746
        //if this wasn't called from a model object (to update itself)
1747
        //then we want to make sure we keep all the existing
1748
        //model objects in sync with the db
1749
        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1750
            if ($this->has_primary_key_field()) {
1751
                $model_objs_affected_ids = $this->get_col($query_params);
1752
            } else {
1753
                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1754
                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1755
                $model_objs_affected_ids = array();
1756
                foreach ($models_affected_key_columns as $row) {
1757
                    $combined_index_key = $this->get_index_primary_key_string($row);
1758
                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1759
                }
1760
            }
1761
            if (! $model_objs_affected_ids) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $model_objs_affected_ids of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1762
                //wait wait wait- if nothing was affected let's stop here
1763
                return 0;
1764
            }
1765
            foreach ($model_objs_affected_ids as $id) {
1766
                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1767
                if ($model_obj_in_entity_map) {
1768
                    foreach ($fields_n_values as $field => $new_value) {
1769
                        $model_obj_in_entity_map->set($field, $new_value);
1770
                    }
1771
                }
1772
            }
1773
            //if there is a primary key on this model, we can now do a slight optimization
1774
            if ($this->has_primary_key_field()) {
1775
                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1776
                $query_params = array(
1777
                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1778
                    'limit'                    => count($model_objs_affected_ids),
1779
                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1780
                );
1781
            }
1782
        }
1783
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1784
        $SQL = "UPDATE "
1785
               . $model_query_info->get_full_join_sql()
1786
               . " SET "
1787
               . $this->_construct_update_sql($fields_n_values)
1788
               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1789
        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1790
        /**
1791
         * Action called after a model update call has been made.
1792
         *
1793
         * @param EEM_Base $model
1794
         * @param array    $fields_n_values the updated fields and their new values
1795
         * @param array    $query_params    @see EEM_Base::get_all()
1796
         * @param int      $rows_affected
1797
         */
1798
        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1799
        return $rows_affected;//how many supposedly got updated
1800
    }
1801
1802
1803
1804
    /**
1805
     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1806
     * are teh values of the field specified (or by default the primary key field)
1807
     * that matched the query params. Note that you should pass the name of the
1808
     * model FIELD, not the database table's column name.
1809
     *
1810
     * @param array  $query_params @see EEM_Base::get_all()
1811
     * @param string $field_to_select
1812
     * @return array just like $wpdb->get_col()
1813
     * @throws EE_Error
1814
     */
1815
    public function get_col($query_params = array(), $field_to_select = null)
1816
    {
1817
        if ($field_to_select) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $field_to_select of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1818
            $field = $this->field_settings_for($field_to_select);
1819
        } elseif ($this->has_primary_key_field()) {
1820
            $field = $this->get_primary_key_field();
1821
        } else {
1822
            //no primary key, just grab the first column
1823
            $field = reset($this->field_settings());
1824
        }
1825
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1826
        $select_expressions = $field->get_qualified_column();
1827
        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1828
        return $this->_do_wpdb_query('get_col', array($SQL));
1829
    }
1830
1831
1832
1833
    /**
1834
     * Returns a single column value for a single row from the database
1835
     *
1836
     * @param array  $query_params    @see EEM_Base::get_all()
1837
     * @param string $field_to_select @see EEM_Base::get_col()
1838
     * @return string
1839
     * @throws EE_Error
1840
     */
1841
    public function get_var($query_params = array(), $field_to_select = null)
1842
    {
1843
        $query_params['limit'] = 1;
1844
        $col = $this->get_col($query_params, $field_to_select);
1845
        if (! empty($col)) {
1846
            return reset($col);
1847
        }
1848
        return null;
1849
    }
1850
1851
1852
1853
    /**
1854
     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1855
     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1856
     * injection, but currently no further filtering is done
1857
     *
1858
     * @global      $wpdb
1859
     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1860
     *                               be updated to in the DB
1861
     * @return string of SQL
1862
     * @throws EE_Error
1863
     */
1864
    public function _construct_update_sql($fields_n_values)
1865
    {
1866
        /** @type WPDB $wpdb */
1867
        global $wpdb;
1868
        $cols_n_values = array();
1869
        foreach ($fields_n_values as $field_name => $value) {
1870
            $field_obj = $this->field_settings_for($field_name);
1871
            //if the value is NULL, we want to assign the value to that.
1872
            //wpdb->prepare doesn't really handle that properly
1873
            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1874
            $value_sql = $prepared_value === null ? 'NULL'
1875
                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1876
            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1877
        }
1878
        return implode(",", $cols_n_values);
1879
    }
1880
1881
1882
1883
    /**
1884
     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1885
     * Performs a HARD delete, meaning the database row should always be removed,
1886
     * not just have a flag field on it switched
1887
     * Wrapper for EEM_Base::delete_permanently()
1888
     *
1889
     * @param mixed $id
1890
     * @param boolean $allow_blocking
1891
     * @return int the number of rows deleted
1892
     * @throws EE_Error
1893
     */
1894 View Code Duplication
    public function delete_permanently_by_ID($id, $allow_blocking = true)
1895
    {
1896
        return $this->delete_permanently(
1897
            array(
1898
                array($this->get_primary_key_field()->get_name() => $id),
1899
                'limit' => 1,
1900
            ),
1901
            $allow_blocking
1902
        );
1903
    }
1904
1905
1906
1907
    /**
1908
     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1909
     * Wrapper for EEM_Base::delete()
1910
     *
1911
     * @param mixed $id
1912
     * @param boolean $allow_blocking
1913
     * @return int the number of rows deleted
1914
     * @throws EE_Error
1915
     */
1916 View Code Duplication
    public function delete_by_ID($id, $allow_blocking = true)
1917
    {
1918
        return $this->delete(
1919
            array(
1920
                array($this->get_primary_key_field()->get_name() => $id),
1921
                'limit' => 1,
1922
            ),
1923
            $allow_blocking
1924
        );
1925
    }
1926
1927
1928
1929
    /**
1930
     * Identical to delete_permanently, but does a "soft" delete if possible,
1931
     * meaning if the model has a field that indicates its been "trashed" or
1932
     * "soft deleted", we will just set that instead of actually deleting the rows.
1933
     *
1934
     * @see EEM_Base::delete_permanently
1935
     * @param array   $query_params
1936
     * @param boolean $allow_blocking
1937
     * @return int how many rows got deleted
1938
     * @throws EE_Error
1939
     */
1940
    public function delete($query_params, $allow_blocking = true)
1941
    {
1942
        return $this->delete_permanently($query_params, $allow_blocking);
1943
    }
1944
1945
1946
1947
    /**
1948
     * Deletes the model objects that meet the query params. Note: this method is overridden
1949
     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1950
     * as archived, not actually deleted
1951
     *
1952
     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1953
     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1954
     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1955
     *                                deletes regardless of other objects which may depend on it. Its generally
1956
     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1957
     *                                DB
1958
     * @return int how many rows got deleted
1959
     * @throws EE_Error
1960
     */
1961
    public function delete_permanently($query_params, $allow_blocking = true)
1962
    {
1963
        /**
1964
         * Action called just before performing a real deletion query. You can use the
1965
         * model and its $query_params to find exactly which items will be deleted
1966
         *
1967
         * @param EEM_Base $model
1968
         * @param array    $query_params   @see EEM_Base::get_all()
1969
         * @param boolean  $allow_blocking whether or not to allow related model objects
1970
         *                                 to block (prevent) this deletion
1971
         */
1972
        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1973
        //some MySQL databases may be running safe mode, which may restrict
1974
        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1975
        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1976
        //to delete them
1977
        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1978
        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1979
        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1980
            $columns_and_ids_for_deleting
1981
        );
1982
        /**
1983
         * Allows client code to act on the items being deleted before the query is actually executed.
1984
         *
1985
         * @param EEM_Base $this  The model instance being acted on.
1986
         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1987
         * @param bool     $allow_blocking @see param description in method phpdoc block.
1988
         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1989
         *                                                  derived from the incoming query parameters.
1990
         *                                                  @see details on the structure of this array in the phpdocs
1991
         *                                                  for the `_get_ids_for_delete_method`
1992
         *
1993
         */
1994
        do_action('AHEE__EEM_Base__delete__before_query',
1995
            $this,
1996
            $query_params,
1997
            $allow_blocking,
1998
            $columns_and_ids_for_deleting
1999
        );
2000
        if ($deletion_where_query_part) {
2001
            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2002
            $table_aliases = array_keys($this->_tables);
2003
            $SQL = "DELETE "
2004
                   . implode(", ", $table_aliases)
2005
                   . " FROM "
2006
                   . $model_query_info->get_full_join_sql()
2007
                   . " WHERE "
2008
                   . $deletion_where_query_part;
2009
            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2010
        } else {
2011
            $rows_deleted = 0;
2012
        }
2013
2014
        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2015
        //there was no error with the delete query.
2016
        if ($this->has_primary_key_field()
2017
            && $rows_deleted !== false
2018
            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2019
        ) {
2020
            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2021
            foreach ($ids_for_removal as $id) {
2022 View Code Duplication
                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2023
                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2024
                }
2025
            }
2026
2027
            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2028
            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2029
            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2030
            // (although it is possible).
2031
            //Note this can be skipped by using the provided filter and returning false.
2032
            if (apply_filters(
2033
                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2034
                ! $this instanceof EEM_Extra_Meta,
2035
                $this
2036
            )) {
2037
                EEM_Extra_Meta::instance()->delete_permanently(array(
2038
                    0 => array(
2039
                        'EXM_type' => $this->get_this_model_name(),
2040
                        'OBJ_ID'   => array(
2041
                            'IN',
2042
                            $ids_for_removal
2043
                        )
2044
                    )
2045
                ));
2046
            }
2047
        }
2048
2049
        /**
2050
         * Action called just after performing a real deletion query. Although at this point the
2051
         * items should have been deleted
2052
         *
2053
         * @param EEM_Base $model
2054
         * @param array    $query_params @see EEM_Base::get_all()
2055
         * @param int      $rows_deleted
2056
         */
2057
        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
        return $rows_deleted;//how many supposedly got deleted
2059
    }
2060
2061
2062
2063
    /**
2064
     * Checks all the relations that throw error messages when there are blocking related objects
2065
     * for related model objects. If there are any related model objects on those relations,
2066
     * adds an EE_Error, and return true
2067
     *
2068
     * @param EE_Base_Class|int $this_model_obj_or_id
2069
     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2070
     *                                                 should be ignored when determining whether there are related
2071
     *                                                 model objects which block this model object's deletion. Useful
2072
     *                                                 if you know A is related to B and are considering deleting A,
2073
     *                                                 but want to see if A has any other objects blocking its deletion
2074
     *                                                 before removing the relation between A and B
2075
     * @return boolean
2076
     * @throws EE_Error
2077
     */
2078
    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2079
    {
2080
        //first, if $ignore_this_model_obj was supplied, get its model
2081
        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2082
            $ignored_model = $ignore_this_model_obj->get_model();
2083
        } else {
2084
            $ignored_model = null;
2085
        }
2086
        //now check all the relations of $this_model_obj_or_id and see if there
2087
        //are any related model objects blocking it?
2088
        $is_blocked = false;
2089
        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2090
            if ($relation_obj->block_delete_if_related_models_exist()) {
2091
                //if $ignore_this_model_obj was supplied, then for the query
2092
                //on that model needs to be told to ignore $ignore_this_model_obj
2093
                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2094
                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2095
                        array(
2096
                            $ignored_model->get_primary_key_field()->get_name() => array(
2097
                                '!=',
2098
                                $ignore_this_model_obj->ID(),
0 ignored issues
show
Bug introduced by
It seems like $ignore_this_model_obj is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
2099
                            ),
2100
                        ),
2101
                    ));
2102
                } else {
2103
                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2104
                }
2105
                if ($related_model_objects) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $related_model_objects of type EE_Base_Class[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2106
                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2107
                    $is_blocked = true;
2108
                }
2109
            }
2110
        }
2111
        return $is_blocked;
2112
    }
2113
2114
2115
    /**
2116
     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2117
     * @param array $row_results_for_deleting
2118
     * @param bool  $allow_blocking
2119
     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2120
     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2121
     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2122
     *                 deleted. Example:
2123
     *                      array('Event.EVT_ID' => array( 1,2,3))
2124
     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2125
     *                 where each element is a group of columns and values that get deleted. Example:
2126
     *                      array(
2127
     *                          0 => array(
2128
     *                              'Term_Relationship.object_id' => 1
2129
     *                              'Term_Relationship.term_taxonomy_id' => 5
2130
     *                          ),
2131
     *                          1 => array(
2132
     *                              'Term_Relationship.object_id' => 1
2133
     *                              'Term_Relationship.term_taxonomy_id' => 6
2134
     *                          )
2135
     *                      )
2136
     * @throws EE_Error
2137
     */
2138
    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2139
    {
2140
        $ids_to_delete_indexed_by_column = array();
2141
        if ($this->has_primary_key_field()) {
2142
            $primary_table = $this->_get_main_table();
2143
            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
0 ignored issues
show
Unused Code introduced by
$primary_table_pk_field is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
2144
            $other_tables = $this->_get_other_tables();
0 ignored issues
show
Unused Code introduced by
$other_tables is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
2145
            $ids_to_delete_indexed_by_column = $query = array();
0 ignored issues
show
Unused Code introduced by
$query is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
2146
            foreach ($row_results_for_deleting as $item_to_delete) {
2147
                //before we mark this item for deletion,
2148
                //make sure there's no related entities blocking its deletion (if we're checking)
2149
                if (
2150
                    $allow_blocking
2151
                    && $this->delete_is_blocked_by_related_models(
2152
                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2153
                    )
2154
                ) {
2155
                    continue;
2156
                }
2157
                //primary table deletes
2158
                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2159
                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2160
                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2161
                }
2162
            }
2163
        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2164
            $fields = $this->get_combined_primary_key_fields();
2165
            foreach ($row_results_for_deleting as $item_to_delete) {
2166
                $ids_to_delete_indexed_by_column_for_row = array();
2167
                foreach ($fields as $cpk_field) {
2168
                    if ($cpk_field instanceof EE_Model_Field_Base) {
2169
                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2170
                            $item_to_delete[$cpk_field->get_qualified_column()];
2171
                    }
2172
                }
2173
                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2174
            }
2175
        } else {
2176
            //so there's no primary key and no combined key...
2177
            //sorry, can't help you
2178
            throw new EE_Error(
2179
                sprintf(
2180
                    __(
2181
                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2182
                        "event_espresso"
2183
                    ), get_class($this)
2184
                )
2185
            );
2186
        }
2187
        return $ids_to_delete_indexed_by_column;
2188
    }
2189
2190
2191
    /**
2192
     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2193
     * the corresponding query_part for the query performing the delete.
2194
     *
2195
     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2196
     * @return string
2197
     * @throws EE_Error
2198
     */
2199
    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2200
        $query_part = '';
2201
        if (empty($ids_to_delete_indexed_by_column)) {
2202
            return $query_part;
2203
        } elseif ($this->has_primary_key_field()) {
2204
            $query = array();
2205
            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2206
                //make sure we have unique $ids
2207
                $ids = array_unique($ids);
2208
                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2209
            }
2210
            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2211
        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2212
            $ways_to_identify_a_row = array();
2213
            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2214
                $values_for_each_combined_primary_key_for_a_row = array();
2215
                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2216
                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2217
                }
2218
                $ways_to_identify_a_row[] = '('
2219
                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2220
                                            . ')';
2221
            }
2222
            $query_part = implode(' OR ', $ways_to_identify_a_row);
2223
        }
2224
        return $query_part;
2225
    }
2226
2227
2228
2229
    /**
2230
     * Gets the model field by the fully qualified name
2231
     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2232
     * @return EE_Model_Field_Base
2233
     */
2234
    public function get_field_by_column($qualified_column_name)
2235
    {
2236
       foreach($this->field_settings(true) as $field_name => $field_obj){
2237
           if($field_obj->get_qualified_column() === $qualified_column_name){
2238
               return $field_obj;
2239
           }
2240
       }
2241
        throw new EE_Error(
2242
            sprintf(
2243
                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2244
                $this->get_this_model_name(),
2245
                $qualified_column_name
2246
            )
2247
        );
2248
    }
2249
2250
2251
2252
    /**
2253
     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2254
     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2255
     * column
2256
     *
2257
     * @param array  $query_params   like EEM_Base::get_all's
2258
     * @param string $field_to_count field on model to count by (not column name)
2259
     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2260
     *                               that by the setting $distinct to TRUE;
2261
     * @return int
2262
     * @throws EE_Error
2263
     */
2264
    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2265
    {
2266
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2267
        if ($field_to_count) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $field_to_count of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2268
            $field_obj = $this->field_settings_for($field_to_count);
2269
            $column_to_count = $field_obj->get_qualified_column();
2270
        } elseif ($this->has_primary_key_field()) {
2271
            $pk_field_obj = $this->get_primary_key_field();
2272
            $column_to_count = $pk_field_obj->get_qualified_column();
2273
        } else {
2274
            //there's no primary key
2275
            //if we're counting distinct items, and there's no primary key,
2276
            //we need to list out the columns for distinction;
2277
            //otherwise we can just use star
2278
            if ($distinct) {
2279
                $columns_to_use = array();
2280
                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2281
                    $columns_to_use[] = $field_obj->get_qualified_column();
2282
                }
2283
                $column_to_count = implode(',', $columns_to_use);
2284
            } else {
2285
                $column_to_count = '*';
2286
            }
2287
        }
2288
        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2289
        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2290
        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2291
    }
2292
2293
2294
2295
    /**
2296
     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2297
     *
2298
     * @param array  $query_params like EEM_Base::get_all
2299
     * @param string $field_to_sum name of field (array key in $_fields array)
2300
     * @return float
2301
     * @throws EE_Error
2302
     */
2303
    public function sum($query_params, $field_to_sum = null)
2304
    {
2305
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2306
        if ($field_to_sum) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $field_to_sum of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2307
            $field_obj = $this->field_settings_for($field_to_sum);
2308
        } else {
2309
            $field_obj = $this->get_primary_key_field();
2310
        }
2311
        $column_to_count = $field_obj->get_qualified_column();
2312
        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2313
        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2314
        $data_type = $field_obj->get_wpdb_data_type();
2315
        if ($data_type === '%d' || $data_type === '%s') {
2316
            return (float)$return_value;
2317
        }
2318
        //must be %f
2319
        return (float)$return_value;
2320
    }
2321
2322
2323
2324
    /**
2325
     * Just calls the specified method on $wpdb with the given arguments
2326
     * Consolidates a little extra error handling code
2327
     *
2328
     * @param string $wpdb_method
2329
     * @param array  $arguments_to_provide
2330
     * @throws EE_Error
2331
     * @global wpdb  $wpdb
2332
     * @return mixed
2333
     */
2334
    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2335
    {
2336
        //if we're in maintenance mode level 2, DON'T run any queries
2337
        //because level 2 indicates the database needs updating and
2338
        //is probably out of sync with the code
2339
        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2340
            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.",
2341
                "event_espresso")));
2342
        }
2343
        /** @type WPDB $wpdb */
2344
        global $wpdb;
2345 View Code Duplication
        if (! method_exists($wpdb, $wpdb_method)) {
2346
            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2347
                'event_espresso'), $wpdb_method));
2348
        }
2349
        if (WP_DEBUG) {
2350
            $old_show_errors_value = $wpdb->show_errors;
2351
            $wpdb->show_errors(false);
2352
        }
2353
        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2354
        $this->show_db_query_if_previously_requested($wpdb->last_query);
2355
        if (WP_DEBUG) {
2356
            $wpdb->show_errors($old_show_errors_value);
2357
            if (! empty($wpdb->last_error)) {
2358
                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2359
            }
2360
            if ($result === false) {
2361
                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"',
2362
                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2363
            }
2364
        } elseif ($result === false) {
2365
            EE_Error::add_error(
2366
                sprintf(
2367
                    __('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"',
2368
                        'event_espresso'),
2369
                    $wpdb_method,
2370
                    var_export($arguments_to_provide, true),
2371
                    $wpdb->last_error
2372
                ),
2373
                __FILE__,
2374
                __FUNCTION__,
2375
                __LINE__
2376
            );
2377
        }
2378
        return $result;
2379
    }
2380
2381
2382
2383
    /**
2384
     * Attempts to run the indicated WPDB method with the provided arguments,
2385
     * and if there's an error tries to verify the DB is correct. Uses
2386
     * the static property EEM_Base::$_db_verification_level to determine whether
2387
     * we should try to fix the EE core db, the addons, or just give up
2388
     *
2389
     * @param string $wpdb_method
2390
     * @param array  $arguments_to_provide
2391
     * @return mixed
2392
     */
2393
    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2394
    {
2395
        /** @type WPDB $wpdb */
2396
        global $wpdb;
2397
        $wpdb->last_error = null;
2398
        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2399
        // was there an error running the query? but we don't care on new activations
2400
        // (we're going to setup the DB anyway on new activations)
2401
        if (($result === false || ! empty($wpdb->last_error))
2402
            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2403
        ) {
2404
            switch (EEM_Base::$_db_verification_level) {
2405
                case EEM_Base::db_verified_none :
2406
                    // let's double-check core's DB
2407
                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2408
                    break;
2409
                case EEM_Base::db_verified_core :
2410
                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2411
                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2412
                    break;
2413
                case EEM_Base::db_verified_addons :
2414
                    // ummmm... you in trouble
2415
                    return $result;
2416
                    break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
2417
            }
2418
            if (! empty($error_message)) {
2419
                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2420
                trigger_error($error_message);
2421
            }
2422
            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2423
        }
2424
        return $result;
2425
    }
2426
2427
2428
2429
    /**
2430
     * Verifies the EE core database is up-to-date and records that we've done it on
2431
     * EEM_Base::$_db_verification_level
2432
     *
2433
     * @param string $wpdb_method
2434
     * @param array  $arguments_to_provide
2435
     * @return string
2436
     */
2437 View Code Duplication
    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2438
    {
2439
        /** @type WPDB $wpdb */
2440
        global $wpdb;
2441
        //ok remember that we've already attempted fixing the core db, in case the problem persists
2442
        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2443
        $error_message = sprintf(
2444
            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2445
                'event_espresso'),
2446
            $wpdb->last_error,
2447
            $wpdb_method,
2448
            wp_json_encode($arguments_to_provide)
2449
        );
2450
        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2451
        return $error_message;
2452
    }
2453
2454
2455
2456
    /**
2457
     * Verifies the EE addons' database is up-to-date and records that we've done it on
2458
     * EEM_Base::$_db_verification_level
2459
     *
2460
     * @param $wpdb_method
2461
     * @param $arguments_to_provide
2462
     * @return string
2463
     */
2464 View Code Duplication
    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2465
    {
2466
        /** @type WPDB $wpdb */
2467
        global $wpdb;
2468
        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2469
        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2470
        $error_message = sprintf(
2471
            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2472
                'event_espresso'),
2473
            $wpdb->last_error,
2474
            $wpdb_method,
2475
            wp_json_encode($arguments_to_provide)
2476
        );
2477
        EE_System::instance()->initialize_addons();
2478
        return $error_message;
2479
    }
2480
2481
2482
2483
    /**
2484
     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2485
     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2486
     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2487
     * ..."
2488
     *
2489
     * @param EE_Model_Query_Info_Carrier $model_query_info
2490
     * @return string
2491
     */
2492
    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2493
    {
2494
        return " FROM " . $model_query_info->get_full_join_sql() .
2495
               $model_query_info->get_where_sql() .
2496
               $model_query_info->get_group_by_sql() .
2497
               $model_query_info->get_having_sql() .
2498
               $model_query_info->get_order_by_sql() .
2499
               $model_query_info->get_limit_sql();
2500
    }
2501
2502
2503
2504
    /**
2505
     * Set to easily debug the next X queries ran from this model.
2506
     *
2507
     * @param int $count
2508
     */
2509
    public function show_next_x_db_queries($count = 1)
2510
    {
2511
        $this->_show_next_x_db_queries = $count;
2512
    }
2513
2514
2515
2516
    /**
2517
     * @param $sql_query
2518
     */
2519
    public function show_db_query_if_previously_requested($sql_query)
2520
    {
2521
        if ($this->_show_next_x_db_queries > 0) {
2522
            echo $sql_query;
2523
            $this->_show_next_x_db_queries--;
2524
        }
2525
    }
2526
2527
2528
2529
    /**
2530
     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2531
     * There are the 3 cases:
2532
     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2533
     * $otherModelObject has no ID, it is first saved.
2534
     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2535
     * has no ID, it is first saved.
2536
     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2537
     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2538
     * join table
2539
     *
2540
     * @param        EE_Base_Class                     /int $thisModelObject
2541
     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2542
     * @param string $relationName                     , key in EEM_Base::_relations
2543
     *                                                 an attendee to a group, you also want to specify which role they
2544
     *                                                 will have in that group. So you would use this parameter to
2545
     *                                                 specify array('role-column-name'=>'role-id')
2546
     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2547
     *                                                 to for relation to methods that allow you to further specify
2548
     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2549
     *                                                 only acceptable query_params is strict "col" => "value" pairs
2550
     *                                                 because these will be inserted in any new rows created as well.
2551
     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2552
     * @throws EE_Error
2553
     */
2554
    public function add_relationship_to(
2555
        $id_or_obj,
2556
        $other_model_id_or_obj,
2557
        $relationName,
2558
        $extra_join_model_fields_n_values = array()
2559
    ) {
2560
        $relation_obj = $this->related_settings_for($relationName);
2561
        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2562
    }
2563
2564
2565
2566
    /**
2567
     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2568
     * There are the 3 cases:
2569
     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2570
     * error
2571
     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2572
     * an error
2573
     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2574
     *
2575
     * @param        EE_Base_Class /int $id_or_obj
2576
     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2577
     * @param string $relationName key in EEM_Base::_relations
2578
     * @return boolean of success
2579
     * @throws EE_Error
2580
     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2581
     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2582
     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2583
     *                             because these will be inserted in any new rows created as well.
2584
     */
2585
    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2586
    {
2587
        $relation_obj = $this->related_settings_for($relationName);
2588
        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2589
    }
2590
2591
2592
2593
    /**
2594
     * @param mixed           $id_or_obj
2595
     * @param string          $relationName
2596
     * @param array           $where_query_params
2597
     * @param EE_Base_Class[] objects to which relations were removed
2598
     * @return \EE_Base_Class[]
2599
     * @throws EE_Error
2600
     */
2601
    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2602
    {
2603
        $relation_obj = $this->related_settings_for($relationName);
2604
        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2605
    }
2606
2607
2608
2609
    /**
2610
     * Gets all the related items of the specified $model_name, using $query_params.
2611
     * Note: by default, we remove the "default query params"
2612
     * because we want to get even deleted items etc.
2613
     *
2614
     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2615
     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2616
     * @param array  $query_params like EEM_Base::get_all
2617
     * @return EE_Base_Class[]
2618
     * @throws EE_Error
2619
     */
2620
    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2621
    {
2622
        $model_obj = $this->ensure_is_obj($id_or_obj);
2623
        $relation_settings = $this->related_settings_for($model_name);
2624
        return $relation_settings->get_all_related($model_obj, $query_params);
2625
    }
2626
2627
2628
2629
    /**
2630
     * Deletes all the model objects across the relation indicated by $model_name
2631
     * which are related to $id_or_obj which meet the criteria set in $query_params.
2632
     * However, if the model objects can't be deleted because of blocking related model objects, then
2633
     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2634
     *
2635
     * @param EE_Base_Class|int|string $id_or_obj
2636
     * @param string                   $model_name
2637
     * @param array                    $query_params
2638
     * @return int how many deleted
2639
     * @throws EE_Error
2640
     */
2641
    public function delete_related($id_or_obj, $model_name, $query_params = array())
2642
    {
2643
        $model_obj = $this->ensure_is_obj($id_or_obj);
2644
        $relation_settings = $this->related_settings_for($model_name);
2645
        return $relation_settings->delete_all_related($model_obj, $query_params);
2646
    }
2647
2648
2649
2650
    /**
2651
     * Hard deletes all the model objects across the relation indicated by $model_name
2652
     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2653
     * the model objects can't be hard deleted because of blocking related model objects,
2654
     * just does a soft-delete on them instead.
2655
     *
2656
     * @param EE_Base_Class|int|string $id_or_obj
2657
     * @param string                   $model_name
2658
     * @param array                    $query_params
2659
     * @return int how many deleted
2660
     * @throws EE_Error
2661
     */
2662
    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2663
    {
2664
        $model_obj = $this->ensure_is_obj($id_or_obj);
2665
        $relation_settings = $this->related_settings_for($model_name);
2666
        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2667
    }
2668
2669
2670
2671
    /**
2672
     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2673
     * unless otherwise specified in the $query_params
2674
     *
2675
     * @param        int             /EE_Base_Class $id_or_obj
2676
     * @param string $model_name     like 'Event', or 'Registration'
2677
     * @param array  $query_params   like EEM_Base::get_all's
2678
     * @param string $field_to_count name of field to count by. By default, uses primary key
2679
     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2680
     *                               that by the setting $distinct to TRUE;
2681
     * @return int
2682
     * @throws EE_Error
2683
     */
2684
    public function count_related(
2685
        $id_or_obj,
2686
        $model_name,
2687
        $query_params = array(),
2688
        $field_to_count = null,
2689
        $distinct = false
2690
    ) {
2691
        $related_model = $this->get_related_model_obj($model_name);
2692
        //we're just going to use the query params on the related model's normal get_all query,
2693
        //except add a condition to say to match the current mod
2694
        if (! isset($query_params['default_where_conditions'])) {
2695
            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2696
        }
2697
        $this_model_name = $this->get_this_model_name();
2698
        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2699
        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2700
        return $related_model->count($query_params, $field_to_count, $distinct);
2701
    }
2702
2703
2704
2705
    /**
2706
     * Instead of getting the related model objects, simply sums up the values of the specified field.
2707
     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2708
     *
2709
     * @param        int           /EE_Base_Class $id_or_obj
2710
     * @param string $model_name   like 'Event', or 'Registration'
2711
     * @param array  $query_params like EEM_Base::get_all's
2712
     * @param string $field_to_sum name of field to count by. By default, uses primary key
2713
     * @return float
2714
     * @throws EE_Error
2715
     */
2716
    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2717
    {
2718
        $related_model = $this->get_related_model_obj($model_name);
2719
        if (! is_array($query_params)) {
2720
            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2721
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2722
                    gettype($query_params)), '4.6.0');
2723
            $query_params = array();
2724
        }
2725
        //we're just going to use the query params on the related model's normal get_all query,
2726
        //except add a condition to say to match the current mod
2727
        if (! isset($query_params['default_where_conditions'])) {
2728
            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2729
        }
2730
        $this_model_name = $this->get_this_model_name();
2731
        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2732
        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2733
        return $related_model->sum($query_params, $field_to_sum);
2734
    }
2735
2736
2737
2738
    /**
2739
     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2740
     * $modelObject
2741
     *
2742
     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2743
     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2744
     * @param array               $query_params     like EEM_Base::get_all's
2745
     * @return EE_Base_Class
2746
     * @throws EE_Error
2747
     */
2748
    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2749
    {
2750
        $query_params['limit'] = 1;
2751
        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2752
        if ($results) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type EE_Base_Class[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2753
            return array_shift($results);
2754
        }
2755
        return null;
2756
    }
2757
2758
2759
2760
    /**
2761
     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2762
     *
2763
     * @return string
2764
     */
2765
    public function get_this_model_name()
2766
    {
2767
        return str_replace("EEM_", "", get_class($this));
2768
    }
2769
2770
2771
2772
    /**
2773
     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2774
     *
2775
     * @return EE_Any_Foreign_Model_Name_Field
2776
     * @throws EE_Error
2777
     */
2778
    public function get_field_containing_related_model_name()
2779
    {
2780
        foreach ($this->field_settings(true) as $field) {
2781
            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2782
                $field_with_model_name = $field;
2783
            }
2784
        }
2785 View Code Duplication
        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2786
            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2787
                $this->get_this_model_name()));
2788
        }
2789
        return $field_with_model_name;
2790
    }
2791
2792
2793
2794
    /**
2795
     * Inserts a new entry into the database, for each table.
2796
     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2797
     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2798
     * we also know there is no model object with the newly inserted item's ID at the moment (because
2799
     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2800
     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2801
     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2802
     *
2803
     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2804
     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2805
     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2806
     *                              of EEM_Base)
2807
     * @return int new primary key on main table that got inserted
2808
     * @throws EE_Error
2809
     */
2810
    public function insert($field_n_values)
2811
    {
2812
        /**
2813
         * Filters the fields and their values before inserting an item using the models
2814
         *
2815
         * @param array    $fields_n_values keys are the fields and values are their new values
2816
         * @param EEM_Base $model           the model used
2817
         */
2818
        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2819
        if ($this->_satisfies_unique_indexes($field_n_values)) {
2820
            $main_table = $this->_get_main_table();
2821
            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2822
            if ($new_id !== false) {
2823
                foreach ($this->_get_other_tables() as $other_table) {
2824
                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2825
                }
2826
            }
2827
            /**
2828
             * Done just after attempting to insert a new model object
2829
             *
2830
             * @param EEM_Base   $model           used
2831
             * @param array      $fields_n_values fields and their values
2832
             * @param int|string the              ID of the newly-inserted model object
2833
             */
2834
            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2835
            return $new_id;
2836
        }
2837
        return false;
2838
    }
2839
2840
2841
2842
    /**
2843
     * Checks that the result would satisfy the unique indexes on this model
2844
     *
2845
     * @param array  $field_n_values
2846
     * @param string $action
2847
     * @return boolean
2848
     * @throws EE_Error
2849
     */
2850
    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2851
    {
2852
        foreach ($this->unique_indexes() as $index_name => $index) {
2853
            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2854
            if ($this->exists(array($uniqueness_where_params))) {
2855
                EE_Error::add_error(
2856
                    sprintf(
2857
                        __(
2858
                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2859
                            "event_espresso"
2860
                        ),
2861
                        $action,
2862
                        $this->_get_class_name(),
2863
                        $index_name,
2864
                        implode(",", $index->field_names()),
2865
                        http_build_query($uniqueness_where_params)
2866
                    ),
2867
                    __FILE__,
2868
                    __FUNCTION__,
2869
                    __LINE__
2870
                );
2871
                return false;
2872
            }
2873
        }
2874
        return true;
2875
    }
2876
2877
2878
2879
    /**
2880
     * Checks the database for an item that conflicts (ie, if this item were
2881
     * saved to the DB would break some uniqueness requirement, like a primary key
2882
     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2883
     * can be either an EE_Base_Class or an array of fields n values
2884
     *
2885
     * @param EE_Base_Class|array $obj_or_fields_array
2886
     * @param boolean             $include_primary_key whether to use the model object's primary key
2887
     *                                                 when looking for conflicts
2888
     *                                                 (ie, if false, we ignore the model object's primary key
2889
     *                                                 when finding "conflicts". If true, it's also considered).
2890
     *                                                 Only works for INT primary key,
2891
     *                                                 STRING primary keys cannot be ignored
2892
     * @throws EE_Error
2893
     * @return EE_Base_Class|array
2894
     */
2895
    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2896
    {
2897 View Code Duplication
        if ($obj_or_fields_array instanceof EE_Base_Class) {
2898
            $fields_n_values = $obj_or_fields_array->model_field_array();
2899
        } elseif (is_array($obj_or_fields_array)) {
2900
            $fields_n_values = $obj_or_fields_array;
2901
        } else {
2902
            throw new EE_Error(
2903
                sprintf(
2904
                    __(
2905
                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2906
                        "event_espresso"
2907
                    ),
2908
                    get_class($this),
2909
                    $obj_or_fields_array
2910
                )
2911
            );
2912
        }
2913
        $query_params = array();
2914
        if ($this->has_primary_key_field()
2915
            && ($include_primary_key
2916
                || $this->get_primary_key_field()
2917
                   instanceof
2918
                   EE_Primary_Key_String_Field)
2919
            && isset($fields_n_values[$this->primary_key_name()])
2920
        ) {
2921
            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2922
        }
2923
        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2924
            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2925
            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2926
        }
2927
        //if there is nothing to base this search on, then we shouldn't find anything
2928
        if (empty($query_params)) {
2929
            return array();
2930
        }
2931
        return $this->get_one($query_params);
2932
    }
2933
2934
2935
2936
    /**
2937
     * Like count, but is optimized and returns a boolean instead of an int
2938
     *
2939
     * @param array $query_params
2940
     * @return boolean
2941
     * @throws EE_Error
2942
     */
2943
    public function exists($query_params)
2944
    {
2945
        $query_params['limit'] = 1;
2946
        return $this->count($query_params) > 0;
2947
    }
2948
2949
2950
2951
    /**
2952
     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2953
     *
2954
     * @param int|string $id
2955
     * @return boolean
2956
     * @throws EE_Error
2957
     */
2958
    public function exists_by_ID($id)
2959
    {
2960
        return $this->exists(
2961
            array(
2962
                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2963
                array(
2964
                    $this->primary_key_name() => $id,
2965
                ),
2966
            )
2967
        );
2968
    }
2969
2970
2971
2972
    /**
2973
     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2974
     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2975
     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2976
     * on the main table)
2977
     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2978
     * cases where we want to call it directly rather than via insert().
2979
     *
2980
     * @access   protected
2981
     * @param EE_Table_Base $table
2982
     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2983
     *                                       float
2984
     * @param int           $new_id          for now we assume only int keys
2985
     * @throws EE_Error
2986
     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2987
     * @return int ID of new row inserted, or FALSE on failure
2988
     */
2989
    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2990
    {
2991
        global $wpdb;
2992
        $insertion_col_n_values = array();
2993
        $format_for_insertion = array();
2994
        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2995
        foreach ($fields_on_table as $field_name => $field_obj) {
2996
            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2997
            if ($field_obj->is_auto_increment()) {
2998
                continue;
2999
            }
3000
            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3001
            //if the value we want to assign it to is NULL, just don't mention it for the insertion
3002
            if ($prepared_value !== null) {
3003
                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3004
                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3005
            }
3006
        }
3007
        if ($table instanceof EE_Secondary_Table && $new_id) {
3008
            //its not the main table, so we should have already saved the main table's PK which we just inserted
3009
            //so add the fk to the main table as a column
3010
            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3011
            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3012
        }
3013
        //insert the new entry
3014
        $result = $this->_do_wpdb_query('insert',
3015
            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
3016
        if ($result === false) {
3017
            return false;
3018
        }
3019
        //ok, now what do we return for the ID of the newly-inserted thing?
3020
        if ($this->has_primary_key_field()) {
3021
            if ($this->get_primary_key_field()->is_auto_increment()) {
3022
                return $wpdb->insert_id;
3023
            }
3024
            //it's not an auto-increment primary key, so
3025
            //it must have been supplied
3026
            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3027
        }
3028
        //we can't return a  primary key because there is none. instead return
3029
        //a unique string indicating this model
3030
        return $this->get_index_primary_key_string($fields_n_values);
3031
    }
3032
3033
3034
3035
    /**
3036
     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3037
     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3038
     * and there is no default, we pass it along. WPDB will take care of it)
3039
     *
3040
     * @param EE_Model_Field_Base $field_obj
3041
     * @param array               $fields_n_values
3042
     * @return mixed string|int|float depending on what the table column will be expecting
3043
     * @throws EE_Error
3044
     */
3045
    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3046
    {
3047
        //if this field doesn't allow nullable, don't allow it
3048
        if (
3049
            ! $field_obj->is_nullable()
3050
            && (
3051
                ! isset($fields_n_values[$field_obj->get_name()])
3052
                || $fields_n_values[$field_obj->get_name()] === null
3053
            )
3054
        ) {
3055
            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3056
        }
3057
        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3058
            ? $fields_n_values[$field_obj->get_name()]
3059
            : null;
3060
        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3061
    }
3062
3063
3064
3065
    /**
3066
     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3067
     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3068
     * the field's prepare_for_set() method.
3069
     *
3070
     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3071
     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3072
     *                                   top of file)
3073
     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3074
     *                                   $value is a custom selection
3075
     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3076
     */
3077
    private function _prepare_value_for_use_in_db($value, $field)
3078
    {
3079
        if ($field && $field instanceof EE_Model_Field_Base) {
3080
            switch ($this->_values_already_prepared_by_model_object) {
3081
                /** @noinspection PhpMissingBreakStatementInspection */
3082
                case self::not_prepared_by_model_object:
3083
                    $value = $field->prepare_for_set($value);
3084
                //purposefully left out "return"
3085
                case self::prepared_by_model_object:
3086
                    /** @noinspection SuspiciousAssignmentsInspection */
3087
                    $value = $field->prepare_for_use_in_db($value);
3088
                case self::prepared_for_use_in_db:
3089
                    //leave the value alone
3090
            }
3091
            return $value;
3092
        }
3093
        return $value;
3094
    }
3095
3096
3097
3098
    /**
3099
     * Returns the main table on this model
3100
     *
3101
     * @return EE_Primary_Table
3102
     * @throws EE_Error
3103
     */
3104
    protected function _get_main_table()
3105
    {
3106
        foreach ($this->_tables as $table) {
3107
            if ($table instanceof EE_Primary_Table) {
3108
                return $table;
3109
            }
3110
        }
3111
        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3112
            'event_espresso'), get_class($this)));
3113
    }
3114
3115
3116
3117
    /**
3118
     * table
3119
     * returns EE_Primary_Table table name
3120
     *
3121
     * @return string
3122
     * @throws EE_Error
3123
     */
3124
    public function table()
3125
    {
3126
        return $this->_get_main_table()->get_table_name();
3127
    }
3128
3129
3130
3131
    /**
3132
     * table
3133
     * returns first EE_Secondary_Table table name
3134
     *
3135
     * @return string
3136
     */
3137
    public function second_table()
3138
    {
3139
        // grab second table from tables array
3140
        $second_table = end($this->_tables);
3141
        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3142
    }
3143
3144
3145
3146
    /**
3147
     * get_table_obj_by_alias
3148
     * returns table name given it's alias
3149
     *
3150
     * @param string $table_alias
3151
     * @return EE_Primary_Table | EE_Secondary_Table
3152
     */
3153
    public function get_table_obj_by_alias($table_alias = '')
3154
    {
3155
        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3156
    }
3157
3158
3159
3160
    /**
3161
     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3162
     *
3163
     * @return EE_Secondary_Table[]
3164
     */
3165
    protected function _get_other_tables()
3166
    {
3167
        $other_tables = array();
3168
        foreach ($this->_tables as $table_alias => $table) {
3169
            if ($table instanceof EE_Secondary_Table) {
3170
                $other_tables[$table_alias] = $table;
3171
            }
3172
        }
3173
        return $other_tables;
3174
    }
3175
3176
3177
3178
    /**
3179
     * Finds all the fields that correspond to the given table
3180
     *
3181
     * @param string $table_alias , array key in EEM_Base::_tables
3182
     * @return EE_Model_Field_Base[]
3183
     */
3184
    public function _get_fields_for_table($table_alias)
3185
    {
3186
        return $this->_fields[$table_alias];
3187
    }
3188
3189
3190
3191
    /**
3192
     * Recurses through all the where parameters, and finds all the related models we'll need
3193
     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3194
     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3195
     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3196
     * related Registration, Transaction, and Payment models.
3197
     *
3198
     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3199
     * @return EE_Model_Query_Info_Carrier
3200
     * @throws EE_Error
3201
     */
3202
    public function _extract_related_models_from_query($query_params)
3203
    {
3204
        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3205
        if (array_key_exists(0, $query_params)) {
3206
            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3207
        }
3208 View Code Duplication
        if (array_key_exists('group_by', $query_params)) {
3209
            if (is_array($query_params['group_by'])) {
3210
                $this->_extract_related_models_from_sub_params_array_values(
3211
                    $query_params['group_by'],
3212
                    $query_info_carrier,
3213
                    'group_by'
3214
                );
3215
            } elseif (! empty ($query_params['group_by'])) {
3216
                $this->_extract_related_model_info_from_query_param(
3217
                    $query_params['group_by'],
3218
                    $query_info_carrier,
3219
                    'group_by'
3220
                );
3221
            }
3222
        }
3223
        if (array_key_exists('having', $query_params)) {
3224
            $this->_extract_related_models_from_sub_params_array_keys(
3225
                $query_params[0],
3226
                $query_info_carrier,
3227
                'having'
3228
            );
3229
        }
3230 View Code Duplication
        if (array_key_exists('order_by', $query_params)) {
3231
            if (is_array($query_params['order_by'])) {
3232
                $this->_extract_related_models_from_sub_params_array_keys(
3233
                    $query_params['order_by'],
3234
                    $query_info_carrier,
3235
                    'order_by'
3236
                );
3237
            } elseif (! empty($query_params['order_by'])) {
3238
                $this->_extract_related_model_info_from_query_param(
3239
                    $query_params['order_by'],
3240
                    $query_info_carrier,
3241
                    'order_by'
3242
                );
3243
            }
3244
        }
3245
        if (array_key_exists('force_join', $query_params)) {
3246
            $this->_extract_related_models_from_sub_params_array_values(
3247
                $query_params['force_join'],
3248
                $query_info_carrier,
3249
                'force_join'
3250
            );
3251
        }
3252
        return $query_info_carrier;
3253
    }
3254
3255
3256
3257
    /**
3258
     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3259
     *
3260
     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3261
     *                                                      $query_params['having']
3262
     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3263
     * @param string                      $query_param_type one of $this->_allowed_query_params
3264
     * @throws EE_Error
3265
     * @return \EE_Model_Query_Info_Carrier
3266
     */
3267
    private function _extract_related_models_from_sub_params_array_keys(
3268
        $sub_query_params,
3269
        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3270
        $query_param_type
3271
    ) {
3272
        if (! empty($sub_query_params)) {
3273
            $sub_query_params = (array)$sub_query_params;
3274
            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3275
                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3276
                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3277
                    $query_param_type);
3278
                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3279
                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3280
                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3281
                //of array('Registration.TXN_ID'=>23)
3282
                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3283
                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3284
                    if (! is_array($possibly_array_of_params)) {
3285
                        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'))",
3286
                            "event_espresso"),
3287
                            $param, $possibly_array_of_params));
3288
                    }
3289
                    $this->_extract_related_models_from_sub_params_array_keys(
3290
                        $possibly_array_of_params,
3291
                        $model_query_info_carrier, $query_param_type
3292
                    );
3293
                } elseif ($query_param_type === 0 //ie WHERE
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $query_param_type (string) and 0 (integer) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
3294
                          && is_array($possibly_array_of_params)
3295
                          && isset($possibly_array_of_params[2])
3296
                          && $possibly_array_of_params[2] == true
3297
                ) {
3298
                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3299
                    //indicating that $possible_array_of_params[1] is actually a field name,
3300
                    //from which we should extract query parameters!
3301 View Code Duplication
                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3302
                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3303
                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3304
                    }
3305
                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3306
                        $model_query_info_carrier, $query_param_type);
3307
                }
3308
            }
3309
        }
3310
        return $model_query_info_carrier;
3311
    }
3312
3313
3314
3315
    /**
3316
     * For extracting related models from forced_joins, where the array values contain the info about what
3317
     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3318
     *
3319
     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3320
     *                                                      $query_params['having']
3321
     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3322
     * @param string                      $query_param_type one of $this->_allowed_query_params
3323
     * @throws EE_Error
3324
     * @return \EE_Model_Query_Info_Carrier
3325
     */
3326
    private function _extract_related_models_from_sub_params_array_values(
3327
        $sub_query_params,
3328
        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3329
        $query_param_type
3330
    ) {
3331
        if (! empty($sub_query_params)) {
3332
            if (! is_array($sub_query_params)) {
3333
                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3334
                    $sub_query_params));
3335
            }
3336
            foreach ($sub_query_params as $param) {
3337
                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3338
                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3339
                    $query_param_type);
3340
            }
3341
        }
3342
        return $model_query_info_carrier;
3343
    }
3344
3345
3346
3347
    /**
3348
     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3349
     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3350
     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3351
     * but use them in a different order. Eg, we need to know what models we are querying
3352
     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3353
     * other models before we can finalize the where clause SQL.
3354
     *
3355
     * @param array $query_params
3356
     * @throws EE_Error
3357
     * @return EE_Model_Query_Info_Carrier
3358
     */
3359
    public function _create_model_query_info_carrier($query_params)
3360
    {
3361
        if (! is_array($query_params)) {
3362
            EE_Error::doing_it_wrong(
3363
                'EEM_Base::_create_model_query_info_carrier',
3364
                sprintf(
3365
                    __(
3366
                        '$query_params should be an array, you passed a variable of type %s',
3367
                        'event_espresso'
3368
                    ),
3369
                    gettype($query_params)
3370
                ),
3371
                '4.6.0'
3372
            );
3373
            $query_params = array();
3374
        }
3375
        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3376
        //first check if we should alter the query to account for caps or not
3377
        //because the caps might require us to do extra joins
3378
        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3379
            $query_params[0] = $where_query_params = array_replace_recursive(
3380
                $where_query_params,
3381
                $this->caps_where_conditions(
3382
                    $query_params['caps']
3383
                )
3384
            );
3385
        }
3386
        $query_object = $this->_extract_related_models_from_query($query_params);
3387
        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3388
        foreach ($where_query_params as $key => $value) {
3389
            if (is_int($key)) {
3390
                throw new EE_Error(
3391
                    sprintf(
3392
                        __(
3393
                            "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.",
3394
                            "event_espresso"
3395
                        ),
3396
                        $key,
3397
                        var_export($value, true),
3398
                        var_export($query_params, true),
3399
                        get_class($this)
3400
                    )
3401
                );
3402
            }
3403
        }
3404
        if (
3405
            array_key_exists('default_where_conditions', $query_params)
3406
            && ! empty($query_params['default_where_conditions'])
3407
        ) {
3408
            $use_default_where_conditions = $query_params['default_where_conditions'];
3409
        } else {
3410
            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3411
        }
3412
        $where_query_params = array_merge(
3413
            $this->_get_default_where_conditions_for_models_in_query(
3414
                $query_object,
3415
                $use_default_where_conditions,
3416
                $where_query_params
3417
            ),
3418
            $where_query_params
3419
        );
3420
        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3421
        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3422
        // So we need to setup a subquery and use that for the main join.
3423
        // Note for now this only works on the primary table for the model.
3424
        // So for instance, you could set the limit array like this:
3425
        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3426
        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3427
            $query_object->set_main_model_join_sql(
3428
                $this->_construct_limit_join_select(
3429
                    $query_params['on_join_limit'][0],
3430
                    $query_params['on_join_limit'][1]
3431
                )
3432
            );
3433
        }
3434
        //set limit
3435
        if (array_key_exists('limit', $query_params)) {
3436
            if (is_array($query_params['limit'])) {
3437
                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3438
                    $e = sprintf(
3439
                        __(
3440
                            "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)",
3441
                            "event_espresso"
3442
                        ),
3443
                        http_build_query($query_params['limit'])
3444
                    );
3445
                    throw new EE_Error($e . "|" . $e);
3446
                }
3447
                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3448
                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3449
            } elseif (! empty ($query_params['limit'])) {
3450
                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3451
            }
3452
        }
3453
        //set order by
3454
        if (array_key_exists('order_by', $query_params)) {
3455
            if (is_array($query_params['order_by'])) {
3456
                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3457
                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3458
                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3459
                if (array_key_exists('order', $query_params)) {
3460
                    throw new EE_Error(
3461
                        sprintf(
3462
                            __(
3463
                                "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 ",
3464
                                "event_espresso"
3465
                            ),
3466
                            get_class($this),
3467
                            implode(", ", array_keys($query_params['order_by'])),
3468
                            implode(", ", $query_params['order_by']),
3469
                            $query_params['order']
3470
                        )
3471
                    );
3472
                }
3473
                $this->_extract_related_models_from_sub_params_array_keys(
3474
                    $query_params['order_by'],
3475
                    $query_object,
3476
                    'order_by'
3477
                );
3478
                //assume it's an array of fields to order by
3479
                $order_array = array();
3480
                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3481
                    $order = $this->_extract_order($order);
3482
                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3483
                }
3484
                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3485
            } elseif (! empty ($query_params['order_by'])) {
3486
                $this->_extract_related_model_info_from_query_param(
3487
                    $query_params['order_by'],
3488
                    $query_object,
3489
                    'order',
3490
                    $query_params['order_by']
3491
                );
3492
                $order = isset($query_params['order'])
3493
                    ? $this->_extract_order($query_params['order'])
3494
                    : 'DESC';
3495
                $query_object->set_order_by_sql(
3496
                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3497
                );
3498
            }
3499
        }
3500
        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3501
        if (! array_key_exists('order_by', $query_params)
3502
            && array_key_exists('order', $query_params)
3503
            && ! empty($query_params['order'])
3504
        ) {
3505
            $pk_field = $this->get_primary_key_field();
3506
            $order = $this->_extract_order($query_params['order']);
3507
            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3508
        }
3509
        //set group by
3510
        if (array_key_exists('group_by', $query_params)) {
3511
            if (is_array($query_params['group_by'])) {
3512
                //it's an array, so assume we'll be grouping by a bunch of stuff
3513
                $group_by_array = array();
3514
                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3515
                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3516
                }
3517
                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3518
            } elseif (! empty ($query_params['group_by'])) {
3519
                $query_object->set_group_by_sql(
3520
                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3521
                );
3522
            }
3523
        }
3524
        //set having
3525
        if (array_key_exists('having', $query_params) && $query_params['having']) {
3526
            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3527
        }
3528
        //now, just verify they didn't pass anything wack
3529
        foreach ($query_params as $query_key => $query_value) {
3530
            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3531
                throw new EE_Error(
3532
                    sprintf(
3533
                        __(
3534
                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3535
                            'event_espresso'
3536
                        ),
3537
                        $query_key,
3538
                        get_class($this),
3539
                        //						print_r( $this->_allowed_query_params, TRUE )
3540
                        implode(',', $this->_allowed_query_params)
3541
                    )
3542
                );
3543
            }
3544
        }
3545
        $main_model_join_sql = $query_object->get_main_model_join_sql();
3546
        if (empty($main_model_join_sql)) {
3547
            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3548
        }
3549
        return $query_object;
3550
    }
3551
3552
3553
3554
    /**
3555
     * Gets the where conditions that should be imposed on the query based on the
3556
     * context (eg reading frontend, backend, edit or delete).
3557
     *
3558
     * @param string $context one of EEM_Base::valid_cap_contexts()
3559
     * @return array like EEM_Base::get_all() 's $query_params[0]
3560
     * @throws EE_Error
3561
     */
3562
    public function caps_where_conditions($context = self::caps_read)
3563
    {
3564
        EEM_Base::verify_is_valid_cap_context($context);
3565
        $cap_where_conditions = array();
3566
        $cap_restrictions = $this->caps_missing($context);
3567
        /**
3568
         * @var $cap_restrictions EE_Default_Where_Conditions[]
3569
         */
3570
        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3571
            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3572
                $restriction_if_no_cap->get_default_where_conditions());
3573
        }
3574
        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3575
            $cap_restrictions);
3576
    }
3577
3578
3579
3580
    /**
3581
     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3582
     * otherwise throws an exception
3583
     *
3584
     * @param string $should_be_order_string
3585
     * @return string either ASC, asc, DESC or desc
3586
     * @throws EE_Error
3587
     */
3588 View Code Duplication
    private function _extract_order($should_be_order_string)
3589
    {
3590
        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3591
            return $should_be_order_string;
3592
        }
3593
        throw new EE_Error(
3594
            sprintf(
3595
                __(
3596
                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3597
                    "event_espresso"
3598
                ), get_class($this), $should_be_order_string
3599
            )
3600
        );
3601
    }
3602
3603
3604
3605
    /**
3606
     * Looks at all the models which are included in this query, and asks each
3607
     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3608
     * so they can be merged
3609
     *
3610
     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3611
     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3612
     *                                                                  'none' means NO default where conditions will
3613
     *                                                                  be used AT ALL during this query.
3614
     *                                                                  'other_models_only' means default where
3615
     *                                                                  conditions from other models will be used, but
3616
     *                                                                  not for this primary model. 'all', the default,
3617
     *                                                                  means default where conditions will apply as
3618
     *                                                                  normal
3619
     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3620
     * @throws EE_Error
3621
     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3622
     */
3623
    private function _get_default_where_conditions_for_models_in_query(
3624
        EE_Model_Query_Info_Carrier $query_info_carrier,
3625
        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3626
        $where_query_params = array()
3627
    ) {
3628
        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3629
        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3630
            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3631
                "event_espresso"), $use_default_where_conditions,
3632
                implode(", ", $allowed_used_default_where_conditions_values)));
3633
        }
3634
        $universal_query_params = array();
3635
        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3636
            $universal_query_params = $this->_get_default_where_conditions();
3637
        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3638
            $universal_query_params = $this->_get_minimum_where_conditions();
3639
        }
3640
        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3641
            $related_model = $this->get_related_model_obj($model_name);
3642
            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3643
                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3644
            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3645
                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3646
            } else {
3647
                //we don't want to add full or even minimum default where conditions from this model, so just continue
3648
                continue;
3649
            }
3650
            $overrides = $this->_override_defaults_or_make_null_friendly(
3651
                $related_model_universal_where_params,
3652
                $where_query_params,
3653
                $related_model,
3654
                $model_relation_path
3655
            );
3656
            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3657
                $universal_query_params,
3658
                $overrides
3659
            );
3660
        }
3661
        return $universal_query_params;
3662
    }
3663
3664
3665
3666
    /**
3667
     * Determines whether or not we should use default where conditions for the model in question
3668
     * (this model, or other related models).
3669
     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3670
     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3671
     * We should use default where conditions on related models when they requested to use default where conditions
3672
     * on all models, or specifically just on other related models
3673
     * @param      $default_where_conditions_value
3674
     * @param bool $for_this_model false means this is for OTHER related models
3675
     * @return bool
3676
     */
3677
    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3678
    {
3679
        return (
3680
                   $for_this_model
3681
                   && in_array(
3682
                       $default_where_conditions_value,
3683
                       array(
3684
                           EEM_Base::default_where_conditions_all,
3685
                           EEM_Base::default_where_conditions_this_only,
3686
                           EEM_Base::default_where_conditions_minimum_others,
3687
                       ),
3688
                       true
3689
                   )
3690
               )
3691
               || (
3692
                   ! $for_this_model
3693
                   && in_array(
3694
                       $default_where_conditions_value,
3695
                       array(
3696
                           EEM_Base::default_where_conditions_all,
3697
                           EEM_Base::default_where_conditions_others_only,
3698
                       ),
3699
                       true
3700
                   )
3701
               );
3702
    }
3703
3704
    /**
3705
     * Determines whether or not we should use default minimum conditions for the model in question
3706
     * (this model, or other related models).
3707
     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3708
     * where conditions.
3709
     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3710
     * on this model or others
3711
     * @param      $default_where_conditions_value
3712
     * @param bool $for_this_model false means this is for OTHER related models
3713
     * @return bool
3714
     */
3715
    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3716
    {
3717
        return (
3718
                   $for_this_model
3719
                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3720
               )
3721
               || (
3722
                   ! $for_this_model
3723
                   && in_array(
3724
                       $default_where_conditions_value,
3725
                       array(
3726
                           EEM_Base::default_where_conditions_minimum_others,
3727
                           EEM_Base::default_where_conditions_minimum_all,
3728
                       ),
3729
                       true
3730
                   )
3731
               );
3732
    }
3733
3734
3735
    /**
3736
     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3737
     * then we also add a special where condition which allows for that model's primary key
3738
     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3739
     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3740
     *
3741
     * @param array    $default_where_conditions
3742
     * @param array    $provided_where_conditions
3743
     * @param EEM_Base $model
3744
     * @param string   $model_relation_path like 'Transaction.Payment.'
3745
     * @return array like EEM_Base::get_all's $query_params[0]
3746
     * @throws EE_Error
3747
     */
3748
    private function _override_defaults_or_make_null_friendly(
3749
        $default_where_conditions,
3750
        $provided_where_conditions,
3751
        $model,
3752
        $model_relation_path
3753
    ) {
3754
        $null_friendly_where_conditions = array();
3755
        $none_overridden = true;
3756
        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3757
        foreach ($default_where_conditions as $key => $val) {
3758
            if (isset($provided_where_conditions[$key])) {
3759
                $none_overridden = false;
3760
            } else {
3761
                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3762
            }
3763
        }
3764
        if ($none_overridden && $default_where_conditions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $default_where_conditions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
3765
            if ($model->has_primary_key_field()) {
3766
                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3767
                                                                                . "."
3768
                                                                                . $model->primary_key_name()] = array('IS NULL');
3769
            }/*else{
3770
				//@todo NO PK, use other defaults
3771
			}*/
3772
        }
3773
        return $null_friendly_where_conditions;
3774
    }
3775
3776
3777
3778
    /**
3779
     * Uses the _default_where_conditions_strategy set during __construct() to get
3780
     * default where conditions on all get_all, update, and delete queries done by this model.
3781
     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3782
     * NOT array('Event_CPT.post_type'=>'esp_event').
3783
     *
3784
     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3785
     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3786
     */
3787
    private function _get_default_where_conditions($model_relation_path = null)
3788
    {
3789
        if ($this->_ignore_where_strategy) {
3790
            return array();
3791
        }
3792
        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3793
    }
3794
3795
3796
3797
    /**
3798
     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3799
     * minimum where conditions on all get_all, update, and delete queries done by this model.
3800
     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3801
     * NOT array('Event_CPT.post_type'=>'esp_event').
3802
     * Similar to _get_default_where_conditions
3803
     *
3804
     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3805
     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3806
     */
3807
    protected function _get_minimum_where_conditions($model_relation_path = null)
3808
    {
3809
        if ($this->_ignore_where_strategy) {
3810
            return array();
3811
        }
3812
        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3813
    }
3814
3815
3816
3817
    /**
3818
     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3819
     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3820
     *
3821
     * @param EE_Model_Query_Info_Carrier $model_query_info
3822
     * @return string
3823
     * @throws EE_Error
3824
     */
3825
    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3826
    {
3827
        $selects = $this->_get_columns_to_select_for_this_model();
3828
        foreach (
3829
            $model_query_info->get_model_names_included() as $model_relation_chain =>
3830
            $name_of_other_model_included
3831
        ) {
3832
            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3833
            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3834
            foreach ($other_model_selects as $key => $value) {
3835
                $selects[] = $value;
3836
            }
3837
        }
3838
        return implode(", ", $selects);
3839
    }
3840
3841
3842
3843
    /**
3844
     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3845
     * So that's going to be the columns for all the fields on the model
3846
     *
3847
     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3848
     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3849
     */
3850
    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3851
    {
3852
        $fields = $this->field_settings();
3853
        $selects = array();
3854
        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3855
            $this->get_this_model_name());
3856
        foreach ($fields as $field_obj) {
3857
            $selects[] = $table_alias_with_model_relation_chain_prefix
3858
                         . $field_obj->get_table_alias()
3859
                         . "."
3860
                         . $field_obj->get_table_column()
3861
                         . " AS '"
3862
                         . $table_alias_with_model_relation_chain_prefix
3863
                         . $field_obj->get_table_alias()
3864
                         . "."
3865
                         . $field_obj->get_table_column()
3866
                         . "'";
3867
        }
3868
        //make sure we are also getting the PKs of each table
3869
        $tables = $this->get_tables();
3870
        if (count($tables) > 1) {
3871
            foreach ($tables as $table_obj) {
3872
                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3873
                                       . $table_obj->get_fully_qualified_pk_column();
3874
                if (! in_array($qualified_pk_column, $selects)) {
3875
                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3876
                }
3877
            }
3878
        }
3879
        return $selects;
3880
    }
3881
3882
3883
3884
    /**
3885
     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3886
     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3887
     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3888
     * SQL for joining, and the data types
3889
     *
3890
     * @param null|string                 $original_query_param
3891
     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3892
     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3893
     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3894
     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3895
     *                                                          column name. We only want model names, eg 'Event.Venue'
3896
     *                                                          or 'Registration's
3897
     * @param string                      $original_query_param what it originally was (eg
3898
     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3899
     *                                                          matches $query_param
3900
     * @throws EE_Error
3901
     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3902
     */
3903
    private function _extract_related_model_info_from_query_param(
3904
        $query_param,
3905
        EE_Model_Query_Info_Carrier $passed_in_query_info,
3906
        $query_param_type,
3907
        $original_query_param = null
3908
    ) {
3909
        if ($original_query_param === null) {
3910
            $original_query_param = $query_param;
3911
        }
3912
        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3913
        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3914
        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3915
        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3916
        //check to see if we have a field on this model
3917
        $this_model_fields = $this->field_settings(true);
3918 View Code Duplication
        if (array_key_exists($query_param, $this_model_fields)) {
3919
            if ($allow_fields) {
3920
                return;
3921
            }
3922
            throw new EE_Error(
3923
                sprintf(
3924
                    __(
3925
                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3926
                        "event_espresso"
3927
                    ),
3928
                    $query_param, get_class($this), $query_param_type, $original_query_param
3929
                )
3930
            );
3931
        }
3932
        //check if this is a special logic query param
3933
        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3934
            if ($allow_logic_query_params) {
3935
                return;
3936
            }
3937
            throw new EE_Error(
3938
                sprintf(
3939
                    __(
3940
                        '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',
3941
                        'event_espresso'
3942
                    ),
3943
                    implode('", "', $this->_logic_query_param_keys),
3944
                    $query_param,
3945
                    get_class($this),
3946
                    '<br />',
3947
                    "\t"
3948
                    . ' $passed_in_query_info = <pre>'
3949
                    . print_r($passed_in_query_info, true)
3950
                    . '</pre>'
3951
                    . "\n\t"
3952
                    . ' $query_param_type = '
3953
                    . $query_param_type
3954
                    . "\n\t"
3955
                    . ' $original_query_param = '
3956
                    . $original_query_param
3957
                )
3958
            );
3959
        }
3960
        //check if it's a custom selection
3961
        if ($this->_custom_selections instanceof CustomSelects
3962
            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
3963
        ) {
3964
            return;
3965
        }
3966
        //check if has a model name at the beginning
3967
        //and
3968
        //check if it's a field on a related model
3969
        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3970
            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3971
                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3972
                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3973
                if ($query_param === '') {
3974
                    //nothing left to $query_param
3975
                    //we should actually end in a field name, not a model like this!
3976
                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3977
                        "event_espresso"),
3978
                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3979
                }
3980
                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3981
                $related_model_obj->_extract_related_model_info_from_query_param(
3982
                    $query_param,
3983
                    $passed_in_query_info, $query_param_type, $original_query_param
3984
                );
3985
                return;
3986
            }
3987
            if ($query_param === $valid_related_model_name) {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $query_param (string) and $valid_related_model_name (integer) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
3988
                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3989
                return;
3990
            }
3991
        }
3992
        //ok so $query_param didn't start with a model name
3993
        //and we previously confirmed it wasn't a logic query param or field on the current model
3994
        //it's wack, that's what it is
3995
        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",
3996
            "event_espresso"),
3997
            $query_param, get_class($this), $query_param_type, $original_query_param));
3998
    }
3999
4000
4001
4002
    /**
4003
     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4004
     * and store it on $passed_in_query_info
4005
     *
4006
     * @param string                      $model_name
4007
     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4008
     * @param string                      $original_query_param used to extract the relation chain between the queried
4009
     *                                                          model and $model_name. Eg, if we are querying Event,
4010
     *                                                          and are adding a join to 'Payment' with the original
4011
     *                                                          query param key
4012
     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4013
     *                                                          to extract 'Registration.Transaction.Payment', in case
4014
     *                                                          Payment wants to add default query params so that it
4015
     *                                                          will know what models to prepend onto its default query
4016
     *                                                          params or in case it wants to rename tables (in case
4017
     *                                                          there are multiple joins to the same table)
4018
     * @return void
4019
     * @throws EE_Error
4020
     */
4021
    private function _add_join_to_model(
4022
        $model_name,
4023
        EE_Model_Query_Info_Carrier $passed_in_query_info,
4024
        $original_query_param
4025
    ) {
4026
        $relation_obj = $this->related_settings_for($model_name);
4027
        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4028
        //check if the relation is HABTM, because then we're essentially doing two joins
4029
        //If so, join first to the JOIN table, and add its data types, and then continue as normal
4030
        if ($relation_obj instanceof EE_HABTM_Relation) {
4031
            $join_model_obj = $relation_obj->get_join_model();
4032
            //replace the model specified with the join model for this relation chain, whi
4033
            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4034
                $join_model_obj->get_this_model_name(), $model_relation_chain);
4035
            $passed_in_query_info->merge(
4036
                new EE_Model_Query_Info_Carrier(
4037
                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4038
                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4039
                )
4040
            );
4041
        }
4042
        //now just join to the other table pointed to by the relation object, and add its data types
4043
        $passed_in_query_info->merge(
4044
            new EE_Model_Query_Info_Carrier(
4045
                array($model_relation_chain => $model_name),
4046
                $relation_obj->get_join_statement($model_relation_chain)
4047
            )
4048
        );
4049
    }
4050
4051
4052
4053
    /**
4054
     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4055
     *
4056
     * @param array $where_params like EEM_Base::get_all
4057
     * @return string of SQL
4058
     * @throws EE_Error
4059
     */
4060
    private function _construct_where_clause($where_params)
4061
    {
4062
        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4063
        if ($SQL) {
4064
            return " WHERE " . $SQL;
4065
        }
4066
        return '';
4067
    }
4068
4069
4070
4071
    /**
4072
     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4073
     * and should be passed HAVING parameters, not WHERE parameters
4074
     *
4075
     * @param array $having_params
4076
     * @return string
4077
     * @throws EE_Error
4078
     */
4079
    private function _construct_having_clause($having_params)
4080
    {
4081
        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4082
        if ($SQL) {
4083
            return " HAVING " . $SQL;
4084
        }
4085
        return '';
4086
    }
4087
4088
4089
    /**
4090
     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4091
     * Event_Meta.meta_value = 'foo'))"
4092
     *
4093
     * @param array  $where_params see EEM_Base::get_all for documentation
4094
     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4095
     * @throws EE_Error
4096
     * @return string of SQL
4097
     */
4098
    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4099
    {
4100
        $where_clauses = array();
4101
        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4102
            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4103
            if (in_array($query_param, $this->_logic_query_param_keys)) {
4104
                switch ($query_param) {
4105
                    case 'not':
4106
                    case 'NOT':
4107
                        $where_clauses[] = "! ("
4108
                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4109
                                $glue)
4110
                                           . ")";
4111
                        break;
4112
                    case 'and':
4113
                    case 'AND':
4114
                        $where_clauses[] = " ("
4115
                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4116
                                ' AND ')
4117
                                           . ")";
4118
                        break;
4119
                    case 'or':
4120
                    case 'OR':
4121
                        $where_clauses[] = " ("
4122
                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4123
                                ' OR ')
4124
                                           . ")";
4125
                        break;
4126
                }
4127
            } else {
4128
                $field_obj = $this->_deduce_field_from_query_param($query_param);
4129
                //if it's not a normal field, maybe it's a custom selection?
4130
                if (! $field_obj) {
4131
                    if ($this->_custom_selections instanceof CustomSelects) {
4132
                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4133
                    } else {
4134
                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4135
                            "event_espresso"), $query_param));
4136
                    }
4137
                }
4138
                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4139
                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4140
            }
4141
        }
4142
        return $where_clauses ? implode($glue, $where_clauses) : '';
4143
    }
4144
4145
4146
4147
    /**
4148
     * Takes the input parameter and extract the table name (alias) and column name
4149
     *
4150
     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4151
     * @throws EE_Error
4152
     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4153
     */
4154
    private function _deduce_column_name_from_query_param($query_param)
4155
    {
4156
        $field = $this->_deduce_field_from_query_param($query_param);
4157
        if ($field) {
4158
            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4159
                $query_param);
4160
            return $table_alias_prefix . $field->get_qualified_column();
4161
        }
4162
        if ($this->_custom_selections instanceof CustomSelects
4163
            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4164
        ) {
4165
            //maybe it's custom selection item?
4166
            //if so, just use it as the "column name"
4167
            return $query_param;
4168
        }
4169
        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4170
            ? implode(',', $this->_custom_selections->columnAliases())
4171
            : '';
4172
        throw new EE_Error(
4173
            sprintf(
4174
                __(
4175
                    "%s is not a valid field on this model, nor a custom selection (%s)",
4176
                    "event_espresso"
4177
                ), $query_param, $custom_select_aliases
4178
            )
4179
        );
4180
    }
4181
4182
4183
4184
    /**
4185
     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4186
     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4187
     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4188
     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4189
     *
4190
     * @param string $condition_query_param_key
4191
     * @return string
4192
     */
4193 View Code Duplication
    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4194
    {
4195
        $pos_of_star = strpos($condition_query_param_key, '*');
4196
        if ($pos_of_star === false) {
4197
            return $condition_query_param_key;
4198
        }
4199
        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4200
        return $condition_query_param_sans_star;
4201
    }
4202
4203
4204
4205
    /**
4206
     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4207
     *
4208
     * @param                            mixed      array | string    $op_and_value
4209
     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4210
     * @throws EE_Error
4211
     * @return string
4212
     */
4213
    private function _construct_op_and_value($op_and_value, $field_obj)
4214
    {
4215
        if (is_array($op_and_value)) {
4216
            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4217
            if (! $operator) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $operator of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
4218
                $php_array_like_string = array();
4219
                foreach ($op_and_value as $key => $value) {
4220
                    $php_array_like_string[] = "$key=>$value";
4221
                }
4222
                throw new EE_Error(
4223
                    sprintf(
4224
                        __(
4225
                            "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))",
4226
                            "event_espresso"
4227
                        ),
4228
                        implode(",", $php_array_like_string)
4229
                    )
4230
                );
4231
            }
4232
            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4233
        } else {
4234
            $operator = '=';
4235
            $value = $op_and_value;
4236
        }
4237
        //check to see if the value is actually another field
4238
        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4239
            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4240
        }
4241
        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4242
            //in this case, the value should be an array, or at least a comma-separated list
4243
            //it will need to handle a little differently
4244
            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4245
            //note: $cleaned_value has already been run through $wpdb->prepare()
4246
            return $operator . SP . $cleaned_value;
4247
        }
4248
        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4249
            //the value should be an array with count of two.
4250
            if (count($value) !== 2) {
4251
                throw new EE_Error(
4252
                    sprintf(
4253
                        __(
4254
                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4255
                            'event_espresso'
4256
                        ),
4257
                        "BETWEEN"
4258
                    )
4259
                );
4260
            }
4261
            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4262
            return $operator . SP . $cleaned_value;
4263
        }
4264
        if (in_array($operator, $this->valid_null_style_operators())) {
4265
            if ($value !== null) {
4266
                throw new EE_Error(
4267
                    sprintf(
4268
                        __(
4269
                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4270
                            "event_espresso"
4271
                        ),
4272
                        $value,
4273
                        $operator
4274
                    )
4275
                );
4276
            }
4277
            return $operator;
4278
        }
4279 View Code Duplication
        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4280
            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4281
            //remove other junk. So just treat it as a string.
4282
            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4283
        }
4284 View Code Duplication
        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4285
            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4286
        }
4287
        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4288
            throw new EE_Error(
4289
                sprintf(
4290
                    __(
4291
                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4292
                        'event_espresso'
4293
                    ),
4294
                    $operator,
4295
                    $operator
4296
                )
4297
            );
4298
        }
4299
        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4300
            throw new EE_Error(
4301
                sprintf(
4302
                    __(
4303
                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4304
                        'event_espresso'
4305
                    ),
4306
                    $operator,
4307
                    $operator
4308
                )
4309
            );
4310
        }
4311
        throw new EE_Error(
4312
            sprintf(
4313
                __(
4314
                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4315
                    "event_espresso"
4316
                ),
4317
                http_build_query($op_and_value)
4318
            )
4319
        );
4320
    }
4321
4322
4323
4324
    /**
4325
     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4326
     *
4327
     * @param array                      $values
4328
     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4329
     *                                              '%s'
4330
     * @return string
4331
     * @throws EE_Error
4332
     */
4333
    public function _construct_between_value($values, $field_obj)
4334
    {
4335
        $cleaned_values = array();
4336
        foreach ($values as $value) {
4337
            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4338
        }
4339
        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4340
    }
4341
4342
4343
4344
    /**
4345
     * Takes an array or a comma-separated list of $values and cleans them
4346
     * according to $data_type using $wpdb->prepare, and then makes the list a
4347
     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4348
     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4349
     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4350
     *
4351
     * @param mixed                      $values    array or comma-separated string
4352
     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4353
     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4354
     * @throws EE_Error
4355
     */
4356
    public function _construct_in_value($values, $field_obj)
4357
    {
4358
        //check if the value is a CSV list
4359
        if (is_string($values)) {
4360
            //in which case, turn it into an array
4361
            $values = explode(",", $values);
4362
        }
4363
        $cleaned_values = array();
4364
        foreach ($values as $value) {
0 ignored issues
show
Bug introduced by
The expression $values of type object|integer|double|null|array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
4365
            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4366
        }
4367
        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4368
        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4369
        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4370
        if (empty($cleaned_values)) {
4371
            $all_fields = $this->field_settings();
4372
            $a_field = array_shift($all_fields);
4373
            $main_table = $this->_get_main_table();
4374
            $cleaned_values[] = "SELECT "
4375
                                . $a_field->get_table_column()
4376
                                . " FROM "
4377
                                . $main_table->get_table_name()
4378
                                . " WHERE FALSE";
4379
        }
4380
        return "(" . implode(",", $cleaned_values) . ")";
4381
    }
4382
4383
4384
4385
    /**
4386
     * @param mixed                      $value
4387
     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4388
     * @throws EE_Error
4389
     * @return false|null|string
4390
     */
4391
    private function _wpdb_prepare_using_field($value, $field_obj)
4392
    {
4393
        /** @type WPDB $wpdb */
4394
        global $wpdb;
4395
        if ($field_obj instanceof EE_Model_Field_Base) {
4396
            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4397
                $this->_prepare_value_for_use_in_db($value, $field_obj));
4398
        } //$field_obj should really just be a data type
4399
        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4400
            throw new EE_Error(
4401
                sprintf(
4402
                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4403
                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4404
                )
4405
            );
4406
        }
4407
        return $wpdb->prepare($field_obj, $value);
4408
    }
4409
4410
4411
4412
    /**
4413
     * Takes the input parameter and finds the model field that it indicates.
4414
     *
4415
     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4416
     * @throws EE_Error
4417
     * @return EE_Model_Field_Base
4418
     */
4419
    protected function _deduce_field_from_query_param($query_param_name)
4420
    {
4421
        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4422
        //which will help us find the database table and column
4423
        $query_param_parts = explode(".", $query_param_name);
4424
        if (empty($query_param_parts)) {
4425
            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4426
                'event_espresso'), $query_param_name));
4427
        }
4428
        $number_of_parts = count($query_param_parts);
4429
        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4430
        if ($number_of_parts === 1) {
4431
            $field_name = $last_query_param_part;
4432
            $model_obj = $this;
4433
        } else {// $number_of_parts >= 2
4434
            //the last part is the column name, and there are only 2parts. therefore...
4435
            $field_name = $last_query_param_part;
4436
            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4437
        }
4438
        try {
4439
            return $model_obj->field_settings_for($field_name);
4440
        } catch (EE_Error $e) {
4441
            return null;
4442
        }
4443
    }
4444
4445
4446
4447
    /**
4448
     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4449
     * alias and column which corresponds to it
4450
     *
4451
     * @param string $field_name
4452
     * @throws EE_Error
4453
     * @return string
4454
     */
4455
    public function _get_qualified_column_for_field($field_name)
4456
    {
4457
        $all_fields = $this->field_settings();
4458
        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4459
        if ($field) {
4460
            return $field->get_qualified_column();
4461
        }
4462
        throw new EE_Error(
4463
            sprintf(
4464
                __(
4465
                    "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.",
4466
                    'event_espresso'
4467
                ), $field_name, get_class($this)
4468
            )
4469
        );
4470
    }
4471
4472
4473
4474
    /**
4475
     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4476
     * Example usage:
4477
     * EEM_Ticket::instance()->get_all_wpdb_results(
4478
     *      array(),
4479
     *      ARRAY_A,
4480
     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4481
     *  );
4482
     * is equivalent to
4483
     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4484
     * and
4485
     *  EEM_Event::instance()->get_all_wpdb_results(
4486
     *      array(
4487
     *          array(
4488
     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4489
     *          ),
4490
     *          ARRAY_A,
4491
     *          implode(
4492
     *              ', ',
4493
     *              array_merge(
4494
     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4495
     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4496
     *              )
4497
     *          )
4498
     *      )
4499
     *  );
4500
     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4501
     *
4502
     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4503
     *                                            and the one whose fields you are selecting for example: when querying
4504
     *                                            tickets model and selecting fields from the tickets model you would
4505
     *                                            leave this parameter empty, because no models are needed to join
4506
     *                                            between the queried model and the selected one. Likewise when
4507
     *                                            querying the datetime model and selecting fields from the tickets
4508
     *                                            model, it would also be left empty, because there is a direct
4509
     *                                            relation from datetimes to tickets, so no model is needed to join
4510
     *                                            them together. However, when querying from the event model and
4511
     *                                            selecting fields from the ticket model, you should provide the string
4512
     *                                            'Datetime', indicating that the event model must first join to the
4513
     *                                            datetime model in order to find its relation to ticket model.
4514
     *                                            Also, when querying from the venue model and selecting fields from
4515
     *                                            the ticket model, you should provide the string 'Event.Datetime',
4516
     *                                            indicating you need to join the venue model to the event model,
4517
     *                                            to the datetime model, in order to find its relation to the ticket model.
4518
     *                                            This string is used to deduce the prefix that gets added onto the
4519
     *                                            models' tables qualified columns
4520
     * @param bool   $return_string               if true, will return a string with qualified column names separated
4521
     *                                            by ', ' if false, will simply return a numerically indexed array of
4522
     *                                            qualified column names
4523
     * @return array|string
4524
     */
4525
    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4526
    {
4527
        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4528
        $qualified_columns = array();
4529
        foreach ($this->field_settings() as $field_name => $field) {
4530
            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4531
        }
4532
        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4533
    }
4534
4535
4536
4537
    /**
4538
     * constructs the select use on special limit joins
4539
     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4540
     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4541
     * (as that is typically where the limits would be set).
4542
     *
4543
     * @param  string       $table_alias The table the select is being built for
4544
     * @param  mixed|string $limit       The limit for this select
4545
     * @return string                The final select join element for the query.
4546
     */
4547
    public function _construct_limit_join_select($table_alias, $limit)
4548
    {
4549
        $SQL = '';
4550
        foreach ($this->_tables as $table_obj) {
4551
            if ($table_obj instanceof EE_Primary_Table) {
4552
                $SQL .= $table_alias === $table_obj->get_table_alias()
4553
                    ? $table_obj->get_select_join_limit($limit)
4554
                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4555
            } elseif ($table_obj instanceof EE_Secondary_Table) {
4556
                $SQL .= $table_alias === $table_obj->get_table_alias()
4557
                    ? $table_obj->get_select_join_limit_join($limit)
4558
                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4559
            }
4560
        }
4561
        return $SQL;
4562
    }
4563
4564
4565
4566
    /**
4567
     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4568
     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4569
     *
4570
     * @return string SQL
4571
     * @throws EE_Error
4572
     */
4573
    public function _construct_internal_join()
4574
    {
4575
        $SQL = $this->_get_main_table()->get_table_sql();
4576
        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4577
        return $SQL;
4578
    }
4579
4580
4581
4582
    /**
4583
     * Constructs the SQL for joining all the tables on this model.
4584
     * Normally $alias should be the primary table's alias, but in cases where
4585
     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4586
     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4587
     * alias, this will construct SQL like:
4588
     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4589
     * With $alias being a secondary table's alias, this will construct SQL like:
4590
     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4591
     *
4592
     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4593
     * @return string
4594
     */
4595
    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4596
    {
4597
        $SQL = '';
4598
        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4599
        foreach ($this->_tables as $table_obj) {
4600
            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4601
                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4602
                    //so we're joining to this table, meaning the table is already in
4603
                    //the FROM statement, BUT the primary table isn't. So we want
4604
                    //to add the inverse join sql
4605
                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4606
                } else {
4607
                    //just add a regular JOIN to this table from the primary table
4608
                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4609
                }
4610
            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4611
        }
4612
        return $SQL;
4613
    }
4614
4615
4616
4617
    /**
4618
     * Gets an array for storing all the data types on the next-to-be-executed-query.
4619
     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4620
     * their data type (eg, '%s', '%d', etc)
4621
     *
4622
     * @return array
4623
     */
4624
    public function _get_data_types()
4625
    {
4626
        $data_types = array();
4627
        foreach ($this->field_settings() as $field_obj) {
4628
            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4629
            /** @var $field_obj EE_Model_Field_Base */
4630
            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4631
        }
4632
        return $data_types;
4633
    }
4634
4635
4636
4637
    /**
4638
     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4639
     *
4640
     * @param string $model_name
4641
     * @throws EE_Error
4642
     * @return EEM_Base
4643
     */
4644
    public function get_related_model_obj($model_name)
4645
    {
4646
        $model_classname = "EEM_" . $model_name;
4647
        if (! class_exists($model_classname)) {
4648
            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",
4649
                'event_espresso'), $model_name, $model_classname));
4650
        }
4651
        return call_user_func($model_classname . "::instance");
4652
    }
4653
4654
4655
4656
    /**
4657
     * Returns the array of EE_ModelRelations for this model.
4658
     *
4659
     * @return EE_Model_Relation_Base[]
4660
     */
4661
    public function relation_settings()
4662
    {
4663
        return $this->_model_relations;
4664
    }
4665
4666
4667
4668
    /**
4669
     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4670
     * because without THOSE models, this model probably doesn't have much purpose.
4671
     * (Eg, without an event, datetimes have little purpose.)
4672
     *
4673
     * @return EE_Belongs_To_Relation[]
4674
     */
4675
    public function belongs_to_relations()
4676
    {
4677
        $belongs_to_relations = array();
4678
        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4679
            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4680
                $belongs_to_relations[$model_name] = $relation_obj;
4681
            }
4682
        }
4683
        return $belongs_to_relations;
4684
    }
4685
4686
4687
4688
    /**
4689
     * Returns the specified EE_Model_Relation, or throws an exception
4690
     *
4691
     * @param string $relation_name name of relation, key in $this->_relatedModels
4692
     * @throws EE_Error
4693
     * @return EE_Model_Relation_Base
4694
     */
4695
    public function related_settings_for($relation_name)
4696
    {
4697
        $relatedModels = $this->relation_settings();
4698 View Code Duplication
        if (! array_key_exists($relation_name, $relatedModels)) {
4699
            throw new EE_Error(
4700
                sprintf(
4701
                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4702
                        'event_espresso'),
4703
                    $relation_name,
4704
                    $this->_get_class_name(),
4705
                    implode(', ', array_keys($relatedModels))
4706
                )
4707
            );
4708
        }
4709
        return $relatedModels[$relation_name];
4710
    }
4711
4712
4713
4714
    /**
4715
     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4716
     * fields
4717
     *
4718
     * @param string $fieldName
4719
     * @param boolean $include_db_only_fields
4720
     * @throws EE_Error
4721
     * @return EE_Model_Field_Base
4722
     */
4723 View Code Duplication
    public function field_settings_for($fieldName, $include_db_only_fields = true)
4724
    {
4725
        $fieldSettings = $this->field_settings($include_db_only_fields);
4726
        if (! array_key_exists($fieldName, $fieldSettings)) {
4727
            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4728
                get_class($this)));
4729
        }
4730
        return $fieldSettings[$fieldName];
4731
    }
4732
4733
4734
4735
    /**
4736
     * Checks if this field exists on this model
4737
     *
4738
     * @param string $fieldName a key in the model's _field_settings array
4739
     * @return boolean
4740
     */
4741
    public function has_field($fieldName)
4742
    {
4743
        $fieldSettings = $this->field_settings(true);
4744
        if (isset($fieldSettings[$fieldName])) {
4745
            return true;
4746
        }
4747
        return false;
4748
    }
4749
4750
4751
4752
    /**
4753
     * Returns whether or not this model has a relation to the specified model
4754
     *
4755
     * @param string $relation_name possibly one of the keys in the relation_settings array
4756
     * @return boolean
4757
     */
4758
    public function has_relation($relation_name)
4759
    {
4760
        $relations = $this->relation_settings();
4761
        if (isset($relations[$relation_name])) {
4762
            return true;
4763
        }
4764
        return false;
4765
    }
4766
4767
4768
4769
    /**
4770
     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4771
     * Eg, on EE_Answer that would be ANS_ID field object
4772
     *
4773
     * @param $field_obj
4774
     * @return boolean
4775
     */
4776
    public function is_primary_key_field($field_obj)
4777
    {
4778
        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4779
    }
4780
4781
4782
4783
    /**
4784
     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4785
     * Eg, on EE_Answer that would be ANS_ID field object
4786
     *
4787
     * @return EE_Model_Field_Base
4788
     * @throws EE_Error
4789
     */
4790
    public function get_primary_key_field()
4791
    {
4792
        if ($this->_primary_key_field === null) {
4793
            foreach ($this->field_settings(true) as $field_obj) {
4794
                if ($this->is_primary_key_field($field_obj)) {
4795
                    $this->_primary_key_field = $field_obj;
4796
                    break;
4797
                }
4798
            }
4799
            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4800
                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4801
                    get_class($this)));
4802
            }
4803
        }
4804
        return $this->_primary_key_field;
4805
    }
4806
4807
4808
4809
    /**
4810
     * Returns whether or not not there is a primary key on this model.
4811
     * Internally does some caching.
4812
     *
4813
     * @return boolean
4814
     */
4815
    public function has_primary_key_field()
4816
    {
4817
        if ($this->_has_primary_key_field === null) {
4818
            try {
4819
                $this->get_primary_key_field();
4820
                $this->_has_primary_key_field = true;
4821
            } catch (EE_Error $e) {
4822
                $this->_has_primary_key_field = false;
4823
            }
4824
        }
4825
        return $this->_has_primary_key_field;
4826
    }
4827
4828
4829
4830
    /**
4831
     * Finds the first field of type $field_class_name.
4832
     *
4833
     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4834
     *                                 EE_Foreign_Key_Field, etc
4835
     * @return EE_Model_Field_Base or null if none is found
4836
     */
4837
    public function get_a_field_of_type($field_class_name)
4838
    {
4839
        foreach ($this->field_settings() as $field) {
4840
            if ($field instanceof $field_class_name) {
4841
                return $field;
4842
            }
4843
        }
4844
        return null;
4845
    }
4846
4847
4848
4849
    /**
4850
     * Gets a foreign key field pointing to model.
4851
     *
4852
     * @param string $model_name eg Event, Registration, not EEM_Event
4853
     * @return EE_Foreign_Key_Field_Base
4854
     * @throws EE_Error
4855
     */
4856
    public function get_foreign_key_to($model_name)
4857
    {
4858
        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4859
            foreach ($this->field_settings() as $field) {
4860
                if (
4861
                    $field instanceof EE_Foreign_Key_Field_Base
4862
                    && in_array($model_name, $field->get_model_names_pointed_to())
4863
                ) {
4864
                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4865
                    break;
4866
                }
4867
            }
4868 View Code Duplication
            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4869
                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4870
                    'event_espresso'), $model_name, get_class($this)));
4871
            }
4872
        }
4873
        return $this->_cache_foreign_key_to_fields[$model_name];
4874
    }
4875
4876
4877
4878
    /**
4879
     * Gets the table name (including $wpdb->prefix) for the table alias
4880
     *
4881
     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4882
     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4883
     *                            Either one works
4884
     * @return string
4885
     */
4886
    public function get_table_for_alias($table_alias)
4887
    {
4888
        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4889
        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4890
    }
4891
4892
4893
4894
    /**
4895
     * Returns a flat array of all field son this model, instead of organizing them
4896
     * by table_alias as they are in the constructor.
4897
     *
4898
     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4899
     * @return EE_Model_Field_Base[] where the keys are the field's name
4900
     */
4901
    public function field_settings($include_db_only_fields = false)
4902
    {
4903
        if ($include_db_only_fields) {
4904
            if ($this->_cached_fields === null) {
4905
                $this->_cached_fields = array();
4906
                foreach ($this->_fields as $fields_corresponding_to_table) {
4907
                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4908
                        $this->_cached_fields[$field_name] = $field_obj;
4909
                    }
4910
                }
4911
            }
4912
            return $this->_cached_fields;
4913
        }
4914
        if ($this->_cached_fields_non_db_only === null) {
4915
            $this->_cached_fields_non_db_only = array();
4916
            foreach ($this->_fields as $fields_corresponding_to_table) {
4917
                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4918
                    /** @var $field_obj EE_Model_Field_Base */
4919
                    if (! $field_obj->is_db_only_field()) {
4920
                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4921
                    }
4922
                }
4923
            }
4924
        }
4925
        return $this->_cached_fields_non_db_only;
4926
    }
4927
4928
4929
4930
    /**
4931
     *        cycle though array of attendees and create objects out of each item
4932
     *
4933
     * @access        private
4934
     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4935
     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4936
     *                           numerically indexed)
4937
     * @throws EE_Error
4938
     */
4939
    protected function _create_objects($rows = array())
4940
    {
4941
        $array_of_objects = array();
4942
        if (empty($rows)) {
4943
            return array();
4944
        }
4945
        $count_if_model_has_no_primary_key = 0;
4946
        $has_primary_key = $this->has_primary_key_field();
4947
        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4948
        foreach ((array)$rows as $row) {
4949
            if (empty($row)) {
4950
                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4951
                return array();
4952
            }
4953
            //check if we've already set this object in the results array,
4954
            //in which case there's no need to process it further (again)
4955
            if ($has_primary_key) {
4956
                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4957
                    $row,
4958
                    $primary_key_field->get_qualified_column(),
4959
                    $primary_key_field->get_table_column()
4960
                );
4961
                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4962
                    continue;
4963
                }
4964
            }
4965
            $classInstance = $this->instantiate_class_from_array_or_object($row);
4966 View Code Duplication
            if (! $classInstance) {
4967
                throw new EE_Error(
4968
                    sprintf(
4969
                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4970
                        $this->get_this_model_name(),
4971
                        http_build_query($row)
4972
                    )
4973
                );
4974
            }
4975
            //set the timezone on the instantiated objects
4976
            $classInstance->set_timezone($this->_timezone);
4977
            //make sure if there is any timezone setting present that we set the timezone for the object
4978
            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4979
            $array_of_objects[$key] = $classInstance;
4980
            //also, for all the relations of type BelongsTo, see if we can cache
4981
            //those related models
4982
            //(we could do this for other relations too, but if there are conditions
4983
            //that filtered out some fo the results, then we'd be caching an incomplete set
4984
            //so it requires a little more thought than just caching them immediately...)
4985
            foreach ($this->_model_relations as $modelName => $relation_obj) {
4986
                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4987
                    //check if this model's INFO is present. If so, cache it on the model
4988
                    $other_model = $relation_obj->get_other_model();
4989
                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4990
                    //if we managed to make a model object from the results, cache it on the main model object
4991
                    if ($other_model_obj_maybe) {
4992
                        //set timezone on these other model objects if they are present
4993
                        $other_model_obj_maybe->set_timezone($this->_timezone);
4994
                        $classInstance->cache($modelName, $other_model_obj_maybe);
4995
                    }
4996
                }
4997
            }
4998
        }
4999
        return $array_of_objects;
5000
    }
5001
5002
5003
5004
    /**
5005
     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5006
     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5007
     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5008
     * object (as set in the model_field!).
5009
     *
5010
     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5011
     */
5012
    public function create_default_object()
5013
    {
5014
        $this_model_fields_and_values = array();
5015
        //setup the row using default values;
5016
        foreach ($this->field_settings() as $field_name => $field_obj) {
5017
            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5018
        }
5019
        $className = $this->_get_class_name();
5020
        $classInstance = EE_Registry::instance()
5021
                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5022
        return $classInstance;
5023
    }
5024
5025
5026
5027
    /**
5028
     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5029
     *                             or an stdClass where each property is the name of a column,
5030
     * @return EE_Base_Class
5031
     * @throws EE_Error
5032
     */
5033
    public function instantiate_class_from_array_or_object($cols_n_values)
5034
    {
5035
        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5036
            $cols_n_values = get_object_vars($cols_n_values);
5037
        }
5038
        $primary_key = null;
5039
        //make sure the array only has keys that are fields/columns on this model
5040
        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5041
        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5042
            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5043
        }
5044
        $className = $this->_get_class_name();
5045
        //check we actually found results that we can use to build our model object
5046
        //if not, return null
5047
        if ($this->has_primary_key_field()) {
5048
            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5049
                return null;
5050
            }
5051
        } else if ($this->unique_indexes()) {
5052
            $first_column = reset($this_model_fields_n_values);
5053
            if (empty($first_column)) {
5054
                return null;
5055
            }
5056
        }
5057
        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5058
        if ($primary_key) {
5059
            $classInstance = $this->get_from_entity_map($primary_key);
5060
            if (! $classInstance) {
5061
                $classInstance = EE_Registry::instance()
5062
                                            ->load_class($className,
5063
                                                array($this_model_fields_n_values, $this->_timezone), true, false);
5064
                // add this new object to the entity map
5065
                $classInstance = $this->add_to_entity_map($classInstance);
0 ignored issues
show
Bug introduced by
It seems like $classInstance can be null; however, add_to_entity_map() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
5066
            }
5067
        } else {
5068
            $classInstance = EE_Registry::instance()
5069
                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5070
                                            true, false);
5071
        }
5072
        return $classInstance;
5073
    }
5074
5075
5076
5077
    /**
5078
     * Gets the model object from the  entity map if it exists
5079
     *
5080
     * @param int|string $id the ID of the model object
5081
     * @return EE_Base_Class
5082
     */
5083
    public function get_from_entity_map($id)
5084
    {
5085
        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5086
            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5087
    }
5088
5089
5090
5091
    /**
5092
     * add_to_entity_map
5093
     * Adds the object to the model's entity mappings
5094
     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5095
     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5096
     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5097
     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5098
     *        then this method should be called immediately after the update query
5099
     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5100
     * so on multisite, the entity map is specific to the query being done for a specific site.
5101
     *
5102
     * @param    EE_Base_Class $object
5103
     * @throws EE_Error
5104
     * @return \EE_Base_Class
5105
     */
5106
    public function add_to_entity_map(EE_Base_Class $object)
5107
    {
5108
        $className = $this->_get_class_name();
5109 View Code Duplication
        if (! $object instanceof $className) {
5110
            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5111
                is_object($object) ? get_class($object) : $object, $className));
5112
        }
5113
        /** @var $object EE_Base_Class */
5114
        if (! $object->ID()) {
5115
            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5116
                "event_espresso"), get_class($this)));
5117
        }
5118
        // double check it's not already there
5119
        $classInstance = $this->get_from_entity_map($object->ID());
5120
        if ($classInstance) {
5121
            return $classInstance;
5122
        }
5123
        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5124
        return $object;
5125
    }
5126
5127
5128
5129
    /**
5130
     * if a valid identifier is provided, then that entity is unset from the entity map,
5131
     * if no identifier is provided, then the entire entity map is emptied
5132
     *
5133
     * @param int|string $id the ID of the model object
5134
     * @return boolean
5135
     */
5136
    public function clear_entity_map($id = null)
5137
    {
5138
        if (empty($id)) {
5139
            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5140
            return true;
5141
        }
5142 View Code Duplication
        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5143
            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5144
            return true;
5145
        }
5146
        return false;
5147
    }
5148
5149
5150
5151
    /**
5152
     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5153
     * Given an array where keys are column (or column alias) names and values,
5154
     * returns an array of their corresponding field names and database values
5155
     *
5156
     * @param array $cols_n_values
5157
     * @return array
5158
     */
5159
    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5160
    {
5161
        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5162
    }
5163
5164
5165
5166
    /**
5167
     * _deduce_fields_n_values_from_cols_n_values
5168
     * Given an array where keys are column (or column alias) names and values,
5169
     * returns an array of their corresponding field names and database values
5170
     *
5171
     * @param string $cols_n_values
5172
     * @return array
5173
     */
5174
    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5175
    {
5176
        $this_model_fields_n_values = array();
5177
        foreach ($this->get_tables() as $table_alias => $table_obj) {
5178
            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $table_pk_value is correct as $this->_get_column_value...e_obj->get_pk_column()) (which targets EEM_Base::_get_column_va...th_table_alias_or_not()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
5179
                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5180
            //there is a primary key on this table and its not set. Use defaults for all its columns
5181
            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5182
                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5183
                    if (! $field_obj->is_db_only_field()) {
5184
                        //prepare field as if its coming from db
5185
                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5186
                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5187
                    }
5188
                }
5189
            } else {
5190
                //the table's rows existed. Use their values
5191
                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5192
                    if (! $field_obj->is_db_only_field()) {
5193
                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $this_model_fields_n_values[$field_name] is correct as $this->_get_column_value...bj->get_table_column()) (which targets EEM_Base::_get_column_va...th_table_alias_or_not()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
5194
                            $cols_n_values, $field_obj->get_qualified_column(),
5195
                            $field_obj->get_table_column()
5196
                        );
5197
                    }
5198
                }
5199
            }
5200
        }
5201
        return $this_model_fields_n_values;
5202
    }
5203
5204
5205
5206
    /**
5207
     * @param $cols_n_values
5208
     * @param $qualified_column
5209
     * @param $regular_column
5210
     * @return null
5211
     */
5212
    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5213
    {
5214
        $value = null;
5215
        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5216
        //does the field on the model relate to this column retrieved from the db?
5217
        //or is it a db-only field? (not relating to the model)
5218
        if (isset($cols_n_values[$qualified_column])) {
5219
            $value = $cols_n_values[$qualified_column];
5220
        } elseif (isset($cols_n_values[$regular_column])) {
5221
            $value = $cols_n_values[$regular_column];
5222
        }
5223
        return $value;
5224
    }
5225
5226
5227
5228
    /**
5229
     * refresh_entity_map_from_db
5230
     * Makes sure the model object in the entity map at $id assumes the values
5231
     * of the database (opposite of EE_base_Class::save())
5232
     *
5233
     * @param int|string $id
5234
     * @return EE_Base_Class
5235
     * @throws EE_Error
5236
     */
5237
    public function refresh_entity_map_from_db($id)
5238
    {
5239
        $obj_in_map = $this->get_from_entity_map($id);
5240
        if ($obj_in_map) {
5241
            $wpdb_results = $this->_get_all_wpdb_results(
5242
                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5243
            );
5244
            if ($wpdb_results && is_array($wpdb_results)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $wpdb_results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
5245
                $one_row = reset($wpdb_results);
5246
                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5247
                    $obj_in_map->set_from_db($field_name, $db_value);
5248
                }
5249
                //clear the cache of related model objects
5250
                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5251
                    $obj_in_map->clear_cache($relation_name, null, true);
5252
                }
5253
            }
5254
            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5255
            return $obj_in_map;
5256
        }
5257
        return $this->get_one_by_ID($id);
5258
    }
5259
5260
5261
5262
    /**
5263
     * refresh_entity_map_with
5264
     * Leaves the entry in the entity map alone, but updates it to match the provided
5265
     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5266
     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5267
     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5268
     *
5269
     * @param int|string    $id
5270
     * @param EE_Base_Class $replacing_model_obj
5271
     * @return \EE_Base_Class
5272
     * @throws EE_Error
5273
     */
5274
    public function refresh_entity_map_with($id, $replacing_model_obj)
5275
    {
5276
        $obj_in_map = $this->get_from_entity_map($id);
5277
        if ($obj_in_map) {
5278
            if ($replacing_model_obj instanceof EE_Base_Class) {
5279
                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5280
                    $obj_in_map->set($field_name, $value);
5281
                }
5282
                //make the model object in the entity map's cache match the $replacing_model_obj
5283
                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5284
                    $obj_in_map->clear_cache($relation_name, null, true);
5285
                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5286
                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5287
                    }
5288
                }
5289
            }
5290
            return $obj_in_map;
5291
        }
5292
        $this->add_to_entity_map($replacing_model_obj);
5293
        return $replacing_model_obj;
5294
    }
5295
5296
5297
5298
    /**
5299
     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5300
     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5301
     * require_once($this->_getClassName().".class.php");
5302
     *
5303
     * @return string
5304
     */
5305
    private function _get_class_name()
5306
    {
5307
        return "EE_" . $this->get_this_model_name();
5308
    }
5309
5310
5311
5312
    /**
5313
     * Get the name of the items this model represents, for the quantity specified. Eg,
5314
     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5315
     * it would be 'Events'.
5316
     *
5317
     * @param int $quantity
5318
     * @return string
5319
     */
5320
    public function item_name($quantity = 1)
5321
    {
5322
        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5323
    }
5324
5325
5326
5327
    /**
5328
     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5329
     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5330
     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5331
     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5332
     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5333
     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5334
     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5335
     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5336
     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5337
     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5338
     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5339
     *        return $previousReturnValue.$returnString;
5340
     * }
5341
     * require('EEM_Answer.model.php');
5342
     * $answer=EEM_Answer::instance();
5343
     * echo $answer->my_callback('monkeys',100);
5344
     * //will output "you called my_callback! and passed args:monkeys,100"
5345
     *
5346
     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5347
     * @param array  $args       array of original arguments passed to the function
5348
     * @throws EE_Error
5349
     * @return mixed whatever the plugin which calls add_filter decides
5350
     */
5351 View Code Duplication
    public function __call($methodName, $args)
5352
    {
5353
        $className = get_class($this);
5354
        $tagName = "FHEE__{$className}__{$methodName}";
5355
        if (! has_filter($tagName)) {
5356
            throw new EE_Error(
5357
                sprintf(
5358
                    __('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 );',
5359
                        'event_espresso'),
5360
                    $methodName,
5361
                    $className,
5362
                    $tagName,
5363
                    '<br />'
5364
                )
5365
            );
5366
        }
5367
        return apply_filters($tagName, null, $this, $args);
5368
    }
5369
5370
5371
5372
    /**
5373
     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5374
     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5375
     *
5376
     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5377
     *                                                       the EE_Base_Class object that corresponds to this Model,
5378
     *                                                       the object's class name
5379
     *                                                       or object's ID
5380
     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5381
     *                                                       exists in the database. If it does not, we add it
5382
     * @throws EE_Error
5383
     * @return EE_Base_Class
5384
     */
5385
    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5386
    {
5387
        $className = $this->_get_class_name();
5388
        if ($base_class_obj_or_id instanceof $className) {
5389
            $model_object = $base_class_obj_or_id;
5390
        } else {
5391
            $primary_key_field = $this->get_primary_key_field();
5392
            if (
5393
                $primary_key_field instanceof EE_Primary_Key_Int_Field
5394
                && (
5395
                    is_int($base_class_obj_or_id)
5396
                    || is_string($base_class_obj_or_id)
5397
                )
5398
            ) {
5399
                // assume it's an ID.
5400
                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5401
                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5402
            } else if (
5403
                $primary_key_field instanceof EE_Primary_Key_String_Field
5404
                && is_string($base_class_obj_or_id)
5405
            ) {
5406
                // assume its a string representation of the object
5407
                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5408
            } else {
5409
                throw new EE_Error(
5410
                    sprintf(
5411
                        __(
5412
                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5413
                            'event_espresso'
5414
                        ),
5415
                        $base_class_obj_or_id,
5416
                        $this->_get_class_name(),
5417
                        print_r($base_class_obj_or_id, true)
5418
                    )
5419
                );
5420
            }
5421
        }
5422
        if ($ensure_is_in_db && $model_object->ID() !== null) {
5423
            $model_object->save();
5424
        }
5425
        return $model_object;
5426
    }
5427
5428
5429
5430
    /**
5431
     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5432
     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5433
     * returns it ID.
5434
     *
5435
     * @param EE_Base_Class|int|string $base_class_obj_or_id
5436
     * @return int|string depending on the type of this model object's ID
5437
     * @throws EE_Error
5438
     */
5439
    public function ensure_is_ID($base_class_obj_or_id)
5440
    {
5441
        $className = $this->_get_class_name();
5442
        if ($base_class_obj_or_id instanceof $className) {
5443
            /** @var $base_class_obj_or_id EE_Base_Class */
5444
            $id = $base_class_obj_or_id->ID();
5445
        } elseif (is_int($base_class_obj_or_id)) {
5446
            //assume it's an ID
5447
            $id = $base_class_obj_or_id;
5448
        } elseif (is_string($base_class_obj_or_id)) {
5449
            //assume its a string representation of the object
5450
            $id = $base_class_obj_or_id;
5451
        } else {
5452
            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5453
                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5454
                print_r($base_class_obj_or_id, true)));
5455
        }
5456
        return $id;
5457
    }
5458
5459
5460
5461
    /**
5462
     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5463
     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5464
     * been sanitized and converted into the appropriate domain.
5465
     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5466
     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5467
     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5468
     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5469
     * $EVT = EEM_Event::instance(); $old_setting =
5470
     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5471
     * $EVT->assume_values_already_prepared_by_model_object(true);
5472
     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5473
     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5474
     *
5475
     * @param int $values_already_prepared like one of the constants on EEM_Base
5476
     * @return void
5477
     */
5478
    public function assume_values_already_prepared_by_model_object(
5479
        $values_already_prepared = self::not_prepared_by_model_object
5480
    ) {
5481
        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5482
    }
5483
5484
5485
5486
    /**
5487
     * Read comments for assume_values_already_prepared_by_model_object()
5488
     *
5489
     * @return int
5490
     */
5491
    public function get_assumption_concerning_values_already_prepared_by_model_object()
5492
    {
5493
        return $this->_values_already_prepared_by_model_object;
5494
    }
5495
5496
5497
5498
    /**
5499
     * Gets all the indexes on this model
5500
     *
5501
     * @return EE_Index[]
5502
     */
5503
    public function indexes()
5504
    {
5505
        return $this->_indexes;
5506
    }
5507
5508
5509
5510
    /**
5511
     * Gets all the Unique Indexes on this model
5512
     *
5513
     * @return EE_Unique_Index[]
5514
     */
5515
    public function unique_indexes()
5516
    {
5517
        $unique_indexes = array();
5518
        foreach ($this->_indexes as $name => $index) {
5519
            if ($index instanceof EE_Unique_Index) {
5520
                $unique_indexes [$name] = $index;
5521
            }
5522
        }
5523
        return $unique_indexes;
5524
    }
5525
5526
5527
5528
    /**
5529
     * Gets all the fields which, when combined, make the primary key.
5530
     * This is usually just an array with 1 element (the primary key), but in cases
5531
     * where there is no primary key, it's a combination of fields as defined
5532
     * on a primary index
5533
     *
5534
     * @return EE_Model_Field_Base[] indexed by the field's name
5535
     * @throws EE_Error
5536
     */
5537
    public function get_combined_primary_key_fields()
5538
    {
5539
        foreach ($this->indexes() as $index) {
5540
            if ($index instanceof EE_Primary_Key_Index) {
5541
                return $index->fields();
5542
            }
5543
        }
5544
        return array($this->primary_key_name() => $this->get_primary_key_field());
5545
    }
5546
5547
5548
5549
    /**
5550
     * Used to build a primary key string (when the model has no primary key),
5551
     * which can be used a unique string to identify this model object.
5552
     *
5553
     * @param array $cols_n_values keys are field names, values are their values
5554
     * @return string
5555
     * @throws EE_Error
5556
     */
5557
    public function get_index_primary_key_string($cols_n_values)
5558
    {
5559
        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5560
            $this->get_combined_primary_key_fields());
5561
        return http_build_query($cols_n_values_for_primary_key_index);
5562
    }
5563
5564
5565
5566
    /**
5567
     * Gets the field values from the primary key string
5568
     *
5569
     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5570
     * @param string $index_primary_key_string
5571
     * @return null|array
5572
     * @throws EE_Error
5573
     */
5574
    public function parse_index_primary_key_string($index_primary_key_string)
5575
    {
5576
        $key_fields = $this->get_combined_primary_key_fields();
5577
        //check all of them are in the $id
5578
        $key_vals_in_combined_pk = array();
5579
        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5580
        foreach ($key_fields as $key_field_name => $field_obj) {
5581
            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5582
                return null;
5583
            }
5584
        }
5585
        return $key_vals_in_combined_pk;
5586
    }
5587
5588
5589
5590
    /**
5591
     * verifies that an array of key-value pairs for model fields has a key
5592
     * for each field comprising the primary key index
5593
     *
5594
     * @param array $key_vals
5595
     * @return boolean
5596
     * @throws EE_Error
5597
     */
5598
    public function has_all_combined_primary_key_fields($key_vals)
5599
    {
5600
        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5601
        foreach ($keys_it_should_have as $key) {
5602
            if (! isset($key_vals[$key])) {
5603
                return false;
5604
            }
5605
        }
5606
        return true;
5607
    }
5608
5609
5610
5611
    /**
5612
     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5613
     * We consider something to be a copy if all the attributes match (except the ID, of course).
5614
     *
5615
     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5616
     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5617
     * @throws EE_Error
5618
     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5619
     *                                                              indexed)
5620
     */
5621
    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5622
    {
5623 View Code Duplication
        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5624
            $attributes_array = $model_object_or_attributes_array->model_field_array();
5625
        } elseif (is_array($model_object_or_attributes_array)) {
5626
            $attributes_array = $model_object_or_attributes_array;
5627
        } else {
5628
            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",
5629
                "event_espresso"), $model_object_or_attributes_array));
5630
        }
5631
        //even copies obviously won't have the same ID, so remove the primary key
5632
        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5633
        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5634
            unset($attributes_array[$this->primary_key_name()]);
5635
        }
5636
        if (isset($query_params[0])) {
5637
            $query_params[0] = array_merge($attributes_array, $query_params);
5638
        } else {
5639
            $query_params[0] = $attributes_array;
5640
        }
5641
        return $this->get_all($query_params);
5642
    }
5643
5644
5645
5646
    /**
5647
     * Gets the first copy we find. See get_all_copies for more details
5648
     *
5649
     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5650
     * @param array $query_params
5651
     * @return EE_Base_Class
5652
     * @throws EE_Error
5653
     */
5654 View Code Duplication
    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5655
    {
5656
        if (! is_array($query_params)) {
5657
            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5658
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5659
                    gettype($query_params)), '4.6.0');
5660
            $query_params = array();
5661
        }
5662
        $query_params['limit'] = 1;
5663
        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5664
        if (is_array($copies)) {
5665
            return array_shift($copies);
5666
        }
5667
        return null;
5668
    }
5669
5670
5671
5672
    /**
5673
     * Updates the item with the specified id. Ignores default query parameters because
5674
     * we have specified the ID, and its assumed we KNOW what we're doing
5675
     *
5676
     * @param array      $fields_n_values keys are field names, values are their new values
5677
     * @param int|string $id              the value of the primary key to update
5678
     * @return int number of rows updated
5679
     * @throws EE_Error
5680
     */
5681
    public function update_by_ID($fields_n_values, $id)
5682
    {
5683
        $query_params = array(
5684
            0                          => array($this->get_primary_key_field()->get_name() => $id),
5685
            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5686
        );
5687
        return $this->update($fields_n_values, $query_params);
5688
    }
5689
5690
5691
5692
    /**
5693
     * Changes an operator which was supplied to the models into one usable in SQL
5694
     *
5695
     * @param string $operator_supplied
5696
     * @return string an operator which can be used in SQL
5697
     * @throws EE_Error
5698
     */
5699
    private function _prepare_operator_for_sql($operator_supplied)
5700
    {
5701
        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5702
            : null;
5703
        if ($sql_operator) {
5704
            return $sql_operator;
5705
        }
5706
        throw new EE_Error(
5707
            sprintf(
5708
                __(
5709
                    "The operator '%s' is not in the list of valid operators: %s",
5710
                    "event_espresso"
5711
                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5712
            )
5713
        );
5714
    }
5715
5716
5717
5718
    /**
5719
     * Gets the valid operators
5720
     * @return array keys are accepted strings, values are the SQL they are converted to
5721
     */
5722
    public function valid_operators(){
5723
        return $this->_valid_operators;
5724
    }
5725
5726
5727
5728
    /**
5729
     * Gets the between-style operators (take 2 arguments).
5730
     * @return array keys are accepted strings, values are the SQL they are converted to
5731
     */
5732
    public function valid_between_style_operators()
5733
    {
5734
        return array_intersect(
5735
            $this->valid_operators(),
5736
            $this->_between_style_operators
5737
        );
5738
    }
5739
5740
    /**
5741
     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5742
     * @return array keys are accepted strings, values are the SQL they are converted to
5743
     */
5744
    public function valid_like_style_operators()
5745
    {
5746
        return array_intersect(
5747
            $this->valid_operators(),
5748
            $this->_like_style_operators
5749
        );
5750
    }
5751
5752
    /**
5753
     * Gets the "in"-style operators
5754
     * @return array keys are accepted strings, values are the SQL they are converted to
5755
     */
5756
    public function valid_in_style_operators()
5757
    {
5758
        return array_intersect(
5759
            $this->valid_operators(),
5760
            $this->_in_style_operators
5761
        );
5762
    }
5763
5764
    /**
5765
     * Gets the "null"-style operators (accept no arguments)
5766
     * @return array keys are accepted strings, values are the SQL they are converted to
5767
     */
5768
    public function valid_null_style_operators()
5769
    {
5770
        return array_intersect(
5771
            $this->valid_operators(),
5772
            $this->_null_style_operators
5773
        );
5774
    }
5775
5776
    /**
5777
     * Gets an array where keys are the primary keys and values are their 'names'
5778
     * (as determined by the model object's name() function, which is often overridden)
5779
     *
5780
     * @param array $query_params like get_all's
5781
     * @return string[]
5782
     * @throws EE_Error
5783
     */
5784
    public function get_all_names($query_params = array())
5785
    {
5786
        $objs = $this->get_all($query_params);
5787
        $names = array();
5788
        foreach ($objs as $obj) {
5789
            $names[$obj->ID()] = $obj->name();
5790
        }
5791
        return $names;
5792
    }
5793
5794
5795
5796
    /**
5797
     * Gets an array of primary keys from the model objects. If you acquired the model objects
5798
     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5799
     * this is duplicated effort and reduces efficiency) you would be better to use
5800
     * array_keys() on $model_objects.
5801
     *
5802
     * @param \EE_Base_Class[] $model_objects
5803
     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5804
     *                                               in the returned array
5805
     * @return array
5806
     * @throws EE_Error
5807
     */
5808
    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5809
    {
5810
        if (! $this->has_primary_key_field()) {
5811
            if (WP_DEBUG) {
5812
                EE_Error::add_error(
5813
                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5814
                    __FILE__,
5815
                    __FUNCTION__,
5816
                    __LINE__
5817
                );
5818
            }
5819
        }
5820
        $IDs = array();
5821
        foreach ($model_objects as $model_object) {
5822
            $id = $model_object->ID();
5823
            if (! $id) {
5824
                if ($filter_out_empty_ids) {
5825
                    continue;
5826
                }
5827
                if (WP_DEBUG) {
5828
                    EE_Error::add_error(
5829
                        __(
5830
                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5831
                            'event_espresso'
5832
                        ),
5833
                        __FILE__,
5834
                        __FUNCTION__,
5835
                        __LINE__
5836
                    );
5837
                }
5838
            }
5839
            $IDs[] = $id;
5840
        }
5841
        return $IDs;
5842
    }
5843
5844
5845
5846
    /**
5847
     * Returns the string used in capabilities relating to this model. If there
5848
     * are no capabilities that relate to this model returns false
5849
     *
5850
     * @return string|false
5851
     */
5852
    public function cap_slug()
5853
    {
5854
        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5855
    }
5856
5857
5858
5859
    /**
5860
     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5861
     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5862
     * only returns the cap restrictions array in that context (ie, the array
5863
     * at that key)
5864
     *
5865
     * @param string $context
5866
     * @return EE_Default_Where_Conditions[] indexed by associated capability
5867
     * @throws EE_Error
5868
     */
5869
    public function cap_restrictions($context = EEM_Base::caps_read)
5870
    {
5871
        EEM_Base::verify_is_valid_cap_context($context);
5872
        //check if we ought to run the restriction generator first
5873
        if (
5874
            isset($this->_cap_restriction_generators[$context])
5875
            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5876
            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5877
        ) {
5878
            $this->_cap_restrictions[$context] = array_merge(
5879
                $this->_cap_restrictions[$context],
5880
                $this->_cap_restriction_generators[$context]->generate_restrictions()
5881
            );
5882
        }
5883
        //and make sure we've finalized the construction of each restriction
5884
        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5885
            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5886
                $where_conditions_obj->_finalize_construct($this);
5887
            }
5888
        }
5889
        return $this->_cap_restrictions[$context];
5890
    }
5891
5892
5893
5894
    /**
5895
     * Indicating whether or not this model thinks its a wp core model
5896
     *
5897
     * @return boolean
5898
     */
5899
    public function is_wp_core_model()
5900
    {
5901
        return $this->_wp_core_model;
5902
    }
5903
5904
5905
5906
    /**
5907
     * Gets all the caps that are missing which impose a restriction on
5908
     * queries made in this context
5909
     *
5910
     * @param string $context one of EEM_Base::caps_ constants
5911
     * @return EE_Default_Where_Conditions[] indexed by capability name
5912
     * @throws EE_Error
5913
     */
5914
    public function caps_missing($context = EEM_Base::caps_read)
5915
    {
5916
        $missing_caps = array();
5917
        $cap_restrictions = $this->cap_restrictions($context);
5918
        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5919
            if (! EE_Capabilities::instance()
5920
                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5921
            ) {
5922
                $missing_caps[$cap] = $restriction_if_no_cap;
5923
            }
5924
        }
5925
        return $missing_caps;
5926
    }
5927
5928
5929
5930
    /**
5931
     * Gets the mapping from capability contexts to action strings used in capability names
5932
     *
5933
     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5934
     * one of 'read', 'edit', or 'delete'
5935
     */
5936
    public function cap_contexts_to_cap_action_map()
5937
    {
5938
        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5939
            $this);
5940
    }
5941
5942
5943
5944
    /**
5945
     * Gets the action string for the specified capability context
5946
     *
5947
     * @param string $context
5948
     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5949
     * @throws EE_Error
5950
     */
5951
    public function cap_action_for_context($context)
5952
    {
5953
        $mapping = $this->cap_contexts_to_cap_action_map();
5954
        if (isset($mapping[$context])) {
5955
            return $mapping[$context];
5956
        }
5957
        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5958
            return $action;
5959
        }
5960
        throw new EE_Error(
5961
            sprintf(
5962
                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5963
                $context,
5964
                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5965
            )
5966
        );
5967
    }
5968
5969
5970
5971
    /**
5972
     * Returns all the capability contexts which are valid when querying models
5973
     *
5974
     * @return array
5975
     */
5976
    public static function valid_cap_contexts()
5977
    {
5978
        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5979
            self::caps_read,
5980
            self::caps_read_admin,
5981
            self::caps_edit,
5982
            self::caps_delete,
5983
        ));
5984
    }
5985
5986
5987
5988
    /**
5989
     * Returns all valid options for 'default_where_conditions'
5990
     *
5991
     * @return array
5992
     */
5993
    public static function valid_default_where_conditions()
5994
    {
5995
        return array(
5996
            EEM_Base::default_where_conditions_all,
5997
            EEM_Base::default_where_conditions_this_only,
5998
            EEM_Base::default_where_conditions_others_only,
5999
            EEM_Base::default_where_conditions_minimum_all,
6000
            EEM_Base::default_where_conditions_minimum_others,
6001
            EEM_Base::default_where_conditions_none
6002
        );
6003
    }
6004
6005
    // public static function default_where_conditions_full
6006
    /**
6007
     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6008
     *
6009
     * @param string $context
6010
     * @return bool
6011
     * @throws EE_Error
6012
     */
6013
    static public function verify_is_valid_cap_context($context)
6014
    {
6015
        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6016
        if (in_array($context, $valid_cap_contexts)) {
6017
            return true;
6018
        }
6019
        throw new EE_Error(
6020
            sprintf(
6021
                __(
6022
                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6023
                    'event_espresso'
6024
                ),
6025
                $context,
6026
                'EEM_Base',
6027
                implode(',', $valid_cap_contexts)
6028
            )
6029
        );
6030
    }
6031
6032
6033
6034
    /**
6035
     * Clears all the models field caches. This is only useful when a sub-class
6036
     * might have added a field or something and these caches might be invalidated
6037
     */
6038
    protected function _invalidate_field_caches()
6039
    {
6040
        $this->_cache_foreign_key_to_fields = array();
6041
        $this->_cached_fields = null;
6042
        $this->_cached_fields_non_db_only = null;
6043
    }
6044
6045
6046
6047
    /**
6048
     * Gets the list of all the where query param keys that relate to logic instead of field names
6049
     * (eg "and", "or", "not").
6050
     *
6051
     * @return array
6052
     */
6053
    public function logic_query_param_keys()
6054
    {
6055
        return $this->_logic_query_param_keys;
6056
    }
6057
6058
6059
6060
    /**
6061
     * Determines whether or not the where query param array key is for a logic query param.
6062
     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6063
     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6064
     *
6065
     * @param $query_param_key
6066
     * @return bool
6067
     */
6068
    public function is_logic_query_param_key($query_param_key)
6069
    {
6070
        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6071
            if ($query_param_key === $logic_query_param_key
6072
                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6073
            ) {
6074
                return true;
6075
            }
6076
        }
6077
        return false;
6078
    }
6079
6080
6081
6082
}
6083