Completed
Branch FET-9222-rest-api-writes (9a0487)
by
unknown
71:42 queued 58:38
created

EEM_Base::get_one()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 11

Duplication

Lines 15
Ratio 100 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 4
nop 1
dl 15
loc 15
rs 9.4285
c 0
b 0
f 0
1
<?php
2
use EventEspresso\core\exceptions\InvalidDataTypeException;
3
use EventEspresso\core\exceptions\InvalidInterfaceException;
4
use EventEspresso\core\interfaces\ResettableInterface;
5
use EventEspresso\core\services\orm\ModelFieldFactory;
6
use EventEspresso\core\services\loaders\LoaderFactory;
7
8
/**
9
 * Class EEM_Base
10
 * Multi-table model. Especially handles joins when querying.
11
 * An important note about values dealt with in models and model objects:
12
 * values used by models exist in basically 3 different domains, which the EE_Model_Fields help convert between:
13
 * 1. Client-code values (eg, controller code may refer to a date as "March 21, 2013")
14
 * 2. Model object values (eg, after the model object has called set() on the value and saves it onto the model object,
15
 * it may become a unix timestamp, eg 12312412412)
16
 * 3. Database values (eg, we may later decide to store dates as mysql dates, in which case they'd be stored as
17
 * '2013-03-21 00:00:00') Sometimes these values are the same, but often they are not. When your client code is using a
18
 * model's functions, you need to be aware which domain your data exists in. If it is client-code values (ie, it hasn't
19
 * had a EE_Model_Field call prepare_for_set on it) then use the model functions as normal. However, if you are calling
20
 * the model functions with values from the model object domain (ie, the code your writing is probably within a model
21
 * object, and all the values you're dealing with have had an EE_Model_Field call prepare_for_set on them), then you'll
22
 * want to set $values_already_prepared_by_model_object to FALSE within the argument-list of the functions you call (in
23
 * order to avoid re-processing those values). If your values are already in the database values domain, you'll either
24
 * way to convert them into the model object domain by creating model objects from those raw db values (ie,using
25
 * EEM_Base::_create_objects), or just use $wpdb directly.
26
 *
27
 * @package               Event Espresso
28
 * @subpackage            core
29
 * @author                Michael Nelson
30
 * @since                 EE4
31
 */
32
abstract class EEM_Base extends EE_Base implements ResettableInterface
33
{
34
35
    /**
36
     * Flag to indicate whether the values provided to EEM_Base have already been prepared
37
     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
38
     * They almost always WILL NOT, but it's not necessarily a requirement.
39
     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
40
     *
41
     * @var boolean
42
     */
43
    private $_values_already_prepared_by_model_object = 0;
44
45
    /**
46
     * when $_values_already_prepared_by_model_object equals this, we assume
47
     * the data is just like form input that needs to have the model fields'
48
     * prepare_for_set and prepare_for_use_in_db called on it
49
     */
50
    const not_prepared_by_model_object = 0;
51
52
    /**
53
     * when $_values_already_prepared_by_model_object equals this, we
54
     * assume this value is coming from a model object and doesn't need to have
55
     * prepare_for_set called on it, just prepare_for_use_in_db is used
56
     */
57
    const prepared_by_model_object = 1;
58
59
    /**
60
     * when $_values_already_prepared_by_model_object equals this, we assume
61
     * the values are already to be used in the database (ie no processing is done
62
     * on them by the model's fields)
63
     */
64
    const prepared_for_use_in_db = 2;
65
66
67
    protected $singular_item = 'Item';
68
69
    protected $plural_item   = 'Items';
70
71
    /**
72
     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
73
     */
74
    protected $_tables;
75
76
    /**
77
     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
78
     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
79
     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
80
     *
81
     * @var \EE_Model_Field_Base[][] $_fields
82
     */
83
    protected $_fields;
84
85
    /**
86
     * array of different kinds of relations
87
     *
88
     * @var \EE_Model_Relation_Base[] $_model_relations
89
     */
90
    protected $_model_relations;
91
92
    /**
93
     * @var \EE_Index[] $_indexes
94
     */
95
    protected $_indexes = array();
96
97
    /**
98
     * Default strategy for getting where conditions on this model. This strategy is used to get default
99
     * where conditions which are added to get_all, update, and delete queries. They can be overridden
100
     * by setting the same columns as used in these queries in the query yourself.
101
     *
102
     * @var EE_Default_Where_Conditions
103
     */
104
    protected $_default_where_conditions_strategy;
105
106
    /**
107
     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
108
     * This is particularly useful when you want something between 'none' and 'default'
109
     *
110
     * @var EE_Default_Where_Conditions
111
     */
112
    protected $_minimum_where_conditions_strategy;
113
114
    /**
115
     * String describing how to find the "owner" of this model's objects.
116
     * When there is a foreign key on this model to the wp_users table, this isn't needed.
117
     * But when there isn't, this indicates which related model, or transiently-related model,
118
     * has the foreign key to the wp_users table.
119
     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
120
     * related to events, and events have a foreign key to wp_users.
121
     * On EEM_Transaction, this would be 'Transaction.Event'
122
     *
123
     * @var string
124
     */
125
    protected $_model_chain_to_wp_user = '';
126
127
    /**
128
     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
129
     * don't need it (particularly CPT models)
130
     *
131
     * @var bool
132
     */
133
    protected $_ignore_where_strategy = false;
134
135
    /**
136
     * String used in caps relating to this model. Eg, if the caps relating to this
137
     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
138
     *
139
     * @var string. If null it hasn't been initialized yet. If false then we
140
     * have indicated capabilities don't apply to this
141
     */
142
    protected $_caps_slug = null;
143
144
    /**
145
     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
146
     * and next-level keys are capability names, and each's value is a
147
     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
148
     * they specify which context to use (ie, frontend, backend, edit or delete)
149
     * and then each capability in the corresponding sub-array that they're missing
150
     * adds the where conditions onto the query.
151
     *
152
     * @var array
153
     */
154
    protected $_cap_restrictions = array(
155
        self::caps_read       => array(),
156
        self::caps_read_admin => array(),
157
        self::caps_edit       => array(),
158
        self::caps_delete     => array(),
159
    );
160
161
    /**
162
     * Array defining which cap restriction generators to use to create default
163
     * cap restrictions to put in EEM_Base::_cap_restrictions.
164
     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
165
     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
166
     * automatically set this to false (not just null).
167
     *
168
     * @var EE_Restriction_Generator_Base[]
169
     */
170
    protected $_cap_restriction_generators = array();
171
172
    /**
173
     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
174
     */
175
    const caps_read       = 'read';
176
177
    const caps_read_admin = 'read_admin';
178
179
    const caps_edit       = 'edit';
180
181
    const caps_delete     = 'delete';
182
183
    /**
184
     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
185
     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
186
     * maps to 'read' because when looking for relevant permissions we're going to use
187
     * 'read' in teh capabilities names like 'ee_read_events' etc.
188
     *
189
     * @var array
190
     */
191
    protected $_cap_contexts_to_cap_action_map = array(
192
        self::caps_read       => 'read',
193
        self::caps_read_admin => 'read',
194
        self::caps_edit       => 'edit',
195
        self::caps_delete     => 'delete',
196
    );
197
198
    /**
199
     * Timezone
200
     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
201
     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
202
     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
203
     * EE_Datetime_Field data type will have access to it.
204
     *
205
     * @var string
206
     */
207
    protected $_timezone;
208
209
210
    /**
211
     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
212
     * multisite.
213
     *
214
     * @var int
215
     */
216
    protected static $_model_query_blog_id;
217
218
    /**
219
     * A copy of _fields, except the array keys are the model names pointed to by
220
     * the field
221
     *
222
     * @var EE_Model_Field_Base[]
223
     */
224
    private $_cache_foreign_key_to_fields = array();
225
226
    /**
227
     * Cached list of all the fields on the model, indexed by their name
228
     *
229
     * @var EE_Model_Field_Base[]
230
     */
231
    private $_cached_fields = null;
232
233
    /**
234
     * Cached list of all the fields on the model, except those that are
235
     * marked as only pertinent to the database
236
     *
237
     * @var EE_Model_Field_Base[]
238
     */
239
    private $_cached_fields_non_db_only = null;
240
241
    /**
242
     * A cached reference to the primary key for quick lookup
243
     *
244
     * @var EE_Model_Field_Base
245
     */
246
    private $_primary_key_field = null;
247
248
    /**
249
     * Flag indicating whether this model has a primary key or not
250
     *
251
     * @var boolean
252
     */
253
    protected $_has_primary_key_field = null;
254
255
    /**
256
     * Whether or not this model is based off a table in WP core only (CPTs should set
257
     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
258
     * This should be true for models that deal with data that should exist independent of EE.
259
     * For example, if the model can read and insert data that isn't used by EE, this should be true.
260
     * It would be false, however, if you could guarantee the model would only interact with EE data,
261
     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
262
     * they can only read and insert events and venues custom post types, not arbitrary post types)
263
     * @var boolean
264
     */
265
    protected $_wp_core_model = false;
266
267
    /**
268
     *    List of valid operators that can be used for querying.
269
     * The keys are all operators we'll accept, the values are the real SQL
270
     * operators used
271
     *
272
     * @var array
273
     */
274
    protected $_valid_operators = array(
275
        '='           => '=',
276
        '<='          => '<=',
277
        '<'           => '<',
278
        '>='          => '>=',
279
        '>'           => '>',
280
        '!='          => '!=',
281
        'LIKE'        => 'LIKE',
282
        'like'        => 'LIKE',
283
        'NOT_LIKE'    => 'NOT LIKE',
284
        'not_like'    => 'NOT LIKE',
285
        'NOT LIKE'    => 'NOT LIKE',
286
        'not like'    => 'NOT LIKE',
287
        'IN'          => 'IN',
288
        'in'          => 'IN',
289
        'NOT_IN'      => 'NOT IN',
290
        'not_in'      => 'NOT IN',
291
        'NOT IN'      => 'NOT IN',
292
        'not in'      => 'NOT IN',
293
        'between'     => 'BETWEEN',
294
        'BETWEEN'     => 'BETWEEN',
295
        'IS_NOT_NULL' => 'IS NOT NULL',
296
        'is_not_null' => 'IS NOT NULL',
297
        'IS NOT NULL' => 'IS NOT NULL',
298
        'is not null' => 'IS NOT NULL',
299
        'IS_NULL'     => 'IS NULL',
300
        'is_null'     => 'IS NULL',
301
        'IS NULL'     => 'IS NULL',
302
        'is null'     => 'IS NULL',
303
        'REGEXP'      => 'REGEXP',
304
        'regexp'      => 'REGEXP',
305
        'NOT_REGEXP'  => 'NOT REGEXP',
306
        'not_regexp'  => 'NOT REGEXP',
307
        'NOT REGEXP'  => 'NOT REGEXP',
308
        'not regexp'  => 'NOT REGEXP',
309
    );
310
311
    /**
312
     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
313
     *
314
     * @var array
315
     */
316
    protected $_in_style_operators = array('IN', 'NOT IN');
317
318
    /**
319
     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
320
     * '12-31-2012'"
321
     *
322
     * @var array
323
     */
324
    protected $_between_style_operators = array('BETWEEN');
325
326
    /**
327
     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
328
     * @var array
329
     */
330
    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
331
    /**
332
     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
333
     * on a join table.
334
     *
335
     * @var array
336
     */
337
    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
338
339
    /**
340
     * Allowed values for $query_params['order'] for ordering in queries
341
     *
342
     * @var array
343
     */
344
    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
345
346
    /**
347
     * When these are keys in a WHERE or HAVING clause, they are handled much differently
348
     * than regular field names. It is assumed that their values are an array of WHERE conditions
349
     *
350
     * @var array
351
     */
352
    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
353
354
    /**
355
     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
356
     * 'where', but 'where' clauses are so common that we thought we'd omit it
357
     *
358
     * @var array
359
     */
360
    private $_allowed_query_params = array(
361
        0,
362
        'limit',
363
        'order_by',
364
        'group_by',
365
        'having',
366
        'force_join',
367
        'order',
368
        'on_join_limit',
369
        'default_where_conditions',
370
        'caps',
371
    );
372
373
    /**
374
     * All the data types that can be used in $wpdb->prepare statements.
375
     *
376
     * @var array
377
     */
378
    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
379
380
    /**
381
     * @var EE_Registry $EE
382
     */
383
    protected $EE = null;
384
385
386
    /**
387
     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
388
     *
389
     * @var int
390
     */
391
    protected $_show_next_x_db_queries = 0;
392
393
    /**
394
     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
395
     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
396
     *
397
     * @var array
398
     */
399
    protected $_custom_selections = array();
400
401
    /**
402
     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
403
     * caches every model object we've fetched from the DB on this request
404
     *
405
     * @var array
406
     */
407
    protected $_entity_map;
408
409
    /**
410
     * @var LoaderInterface $loader
411
     */
412
    private static $loader;
413
414
415
    /**
416
     * constant used to show EEM_Base has not yet verified the db on this http request
417
     */
418
    const db_verified_none = 0;
419
420
    /**
421
     * constant used to show EEM_Base has verified the EE core db on this http request,
422
     * but not the addons' dbs
423
     */
424
    const db_verified_core = 1;
425
426
    /**
427
     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
428
     * the EE core db too)
429
     */
430
    const db_verified_addons = 2;
431
432
    /**
433
     * indicates whether an EEM_Base child has already re-verified the DB
434
     * is ok (we don't want to do it repetitively). Should be set to one the constants
435
     * looking like EEM_Base::db_verified_*
436
     *
437
     * @var int - 0 = none, 1 = core, 2 = addons
438
     */
439
    protected static $_db_verification_level = EEM_Base::db_verified_none;
440
441
    /**
442
     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
443
     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
444
     *        registrations for non-trashed tickets for non-trashed datetimes)
445
     */
446
    const default_where_conditions_all = 'all';
447
448
    /**
449
     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
450
     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
451
     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
452
     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
453
     *        models which share tables with other models, this can return data for the wrong model.
454
     */
455
    const default_where_conditions_this_only = 'this_model_only';
456
457
    /**
458
     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
459
     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
460
     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
461
     */
462
    const default_where_conditions_others_only = 'other_models_only';
463
464
    /**
465
     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
466
     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
467
     *        their table with other models, like the Event and Venue models. For example, when querying for events
468
     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
469
     *        (regardless of whether those events and venues are trashed)
470
     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
471
     *        events.
472
     */
473
    const default_where_conditions_minimum_all = 'minimum';
474
475
    /**
476
     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
477
     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
478
     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
479
     *        not)
480
     */
481
    const default_where_conditions_minimum_others = 'full_this_minimum_others';
482
483
    /**
484
     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
485
     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
486
     *        it's possible it will return table entries for other models. You should use
487
     *        EEM_Base::default_where_conditions_minimum_all instead.
488
     */
489
    const default_where_conditions_none = 'none';
490
491
492
493
    /**
494
     * About all child constructors:
495
     * they should define the _tables, _fields and _model_relations arrays.
496
     * Should ALWAYS be called after child constructor.
497
     * In order to make the child constructors to be as simple as possible, this parent constructor
498
     * finalizes constructing all the object's attributes.
499
     * Generally, rather than requiring a child to code
500
     * $this->_tables = array(
501
     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
502
     *        ...);
503
     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
504
     * each EE_Table has a function to set the table's alias after the constructor, using
505
     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
506
     * do something similar.
507
     *
508
     * @param null $timezone
509
     * @throws EE_Error
510
     */
511
    protected function __construct($timezone = null)
512
    {
513
        // check that the model has not been loaded too soon
514
        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
515
            throw new EE_Error (
516
                sprintf(
517
                    __('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.',
518
                        'event_espresso'),
519
                    get_class($this)
520
                )
521
            );
522
        }
523
        /**
524
         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
525
         */
526
        if (empty(EEM_Base::$_model_query_blog_id)) {
527
            EEM_Base::set_model_query_blog_id();
528
        }
529
        /**
530
         * Filters the list of tables on a model. It is best to NOT use this directly and instead
531
         * just use EE_Register_Model_Extension
532
         *
533
         * @var EE_Table_Base[] $_tables
534
         */
535
        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
536
        foreach ($this->_tables as $table_alias => $table_obj) {
537
            /** @var $table_obj EE_Table_Base */
538
            $table_obj->_construct_finalize_with_alias($table_alias);
539
            if ($table_obj instanceof EE_Secondary_Table) {
540
                /** @var $table_obj EE_Secondary_Table */
541
                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
542
            }
543
        }
544
        /**
545
         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
546
         * EE_Register_Model_Extension
547
         *
548
         * @param EE_Model_Field_Base[] $_fields
549
         */
550
        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
551
        $this->_invalidate_field_caches();
552
        foreach ($this->_fields as $table_alias => $fields_for_table) {
553
            if (! array_key_exists($table_alias, $this->_tables)) {
554
                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
555
                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
556
            }
557
            foreach ($fields_for_table as $field_name => $field_obj) {
558
                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
559
                //primary key field base has a slightly different _construct_finalize
560
                /** @var $field_obj EE_Model_Field_Base */
561
                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
562
            }
563
        }
564
        // everything is related to Extra_Meta
565
        if (get_class($this) !== 'EEM_Extra_Meta') {
566
            //make extra meta related to everything, but don't block deleting things just
567
            //because they have related extra meta info. For now just orphan those extra meta
568
            //in the future we should automatically delete them
569
            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
570
        }
571
        //and change logs
572
        if (get_class($this) !== 'EEM_Change_Log') {
573
            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
574
        }
575
        /**
576
         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
577
         * EE_Register_Model_Extension
578
         *
579
         * @param EE_Model_Relation_Base[] $_model_relations
580
         */
581
        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
582
            $this->_model_relations);
583
        foreach ($this->_model_relations as $model_name => $relation_obj) {
584
            /** @var $relation_obj EE_Model_Relation_Base */
585
            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
586
        }
587
        foreach ($this->_indexes as $index_name => $index_obj) {
588
            /** @var $index_obj EE_Index */
589
            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
590
        }
591
        $this->set_timezone($timezone);
592
        //finalize default where condition strategy, or set default
593
        if (! $this->_default_where_conditions_strategy) {
594
            //nothing was set during child constructor, so set default
595
            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
596
        }
597
        $this->_default_where_conditions_strategy->_finalize_construct($this);
598
        if (! $this->_minimum_where_conditions_strategy) {
599
            //nothing was set during child constructor, so set default
600
            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
601
        }
602
        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
603
        //if the cap slug hasn't been set, and we haven't set it to false on purpose
604
        //to indicate to NOT set it, set it to the logical default
605
        if ($this->_caps_slug === null) {
606
            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
607
        }
608
        //initialize the standard cap restriction generators if none were specified by the child constructor
609
        if ($this->_cap_restriction_generators !== false) {
610
            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
611
                if (! isset($this->_cap_restriction_generators[$cap_context])) {
612
                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
613
                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
614
                        new EE_Restriction_Generator_Protected(),
615
                        $cap_context,
616
                        $this
617
                    );
618
                }
619
            }
620
        }
621
        //if there are cap restriction generators, use them to make the default cap restrictions
622
        if ($this->_cap_restriction_generators !== false) {
623
            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
624
                if (! $generator_object) {
625
                    continue;
626
                }
627 View Code Duplication
                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
628
                    throw new EE_Error(
629
                        sprintf(
630
                            __('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.',
631
                                'event_espresso'),
632
                            $context,
633
                            $this->get_this_model_name()
634
                        )
635
                    );
636
                }
637
                $action = $this->cap_action_for_context($context);
638
                if (! $generator_object->construction_finalized()) {
639
                    $generator_object->_construct_finalize($this, $action);
640
                }
641
            }
642
        }
643
        do_action('AHEE__' . get_class($this) . '__construct__end');
644
    }
645
646
647
648
    /**
649
     * Used to set the $_model_query_blog_id static property.
650
     *
651
     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
652
     *                      value for get_current_blog_id() will be used.
653
     */
654
    public static function set_model_query_blog_id($blog_id = 0)
655
    {
656
        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
657
    }
658
659
660
661
    /**
662
     * Returns whatever is set as the internal $model_query_blog_id.
663
     *
664
     * @return int
665
     */
666
    public static function get_model_query_blog_id()
667
    {
668
        return EEM_Base::$_model_query_blog_id;
669
    }
670
671
672
673
    /**
674
     * This function is a singleton method used to instantiate the Espresso_model object
675
     *
676
     * @param string            $timezone string representing the timezone we want to set for returned Date Time Strings
677
     *                                    (and any incoming timezone data that gets saved).
678
     *                                    Note this just sends the timezone info to the date time model field objects.
679
     *                                    Default is NULL
680
     *                                    (and will be assumed using the set timezone in the 'timezone_string' wp option)
681
     * @param ModelFieldFactory $model_field_factory
682
     * @return static (as in the concrete child class)
683
     * @throws EE_Error
684
     * @throws InvalidArgumentException
685
     * @throws InvalidDataTypeException
686
     * @throws InvalidInterfaceException
687
     */
688
    public static function instance($timezone = null, ModelFieldFactory $model_field_factory = null)
689
    {
690
        // check if instance of Espresso_model already exists
691
        if (! static::$_instance instanceof static) {
692
            $model_field_factory = self::getModelFieldFactory($model_field_factory);
693
            // instantiate Espresso_model
694
            static::$_instance = new static($timezone, $model_field_factory);
695
        }
696
        //we might have a timezone set, let set_timezone decide what to do with it
697
        static::$_instance->set_timezone($timezone);
698
        // Espresso_model object
699
        return static::$_instance;
700
    }
701
702
703
704
    /**
705
     * @param $model_field_factory
706
     * @return ModelFieldFactory
707
     * @throws InvalidArgumentException
708
     * @throws InvalidDataTypeException
709
     * @throws InvalidInterfaceException
710
     */
711
    private static function getModelFieldFactory($model_field_factory)
712
    {
713
        return $model_field_factory instanceof ModelFieldFactory
714
            ? $model_field_factory
715
            : LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory');
716
    }
717
718
719
720
    /**
721
     * resets the model and returns it
722
     *
723
     * @param null | string          $timezone
724
     * @param ModelFieldFactory|null $model_field_factory
725
     * @return EEM_Base|null (if the model was already instantiated, returns it, with
726
     * all its properties reset; if it wasn't instantiated, returns null)
727
     * @throws EE_Error
728
     * @throws ReflectionException
729
     * @throws InvalidArgumentException
730
     * @throws InvalidDataTypeException
731
     * @throws InvalidInterfaceException
732
     */
733
    public static function reset($timezone = null, ModelFieldFactory $model_field_factory = null)
734
    {
735
        if (static::$_instance instanceof EEM_Base) {
736
            //let's try to NOT swap out the current instance for a new one
737
            //because if someone has a reference to it, we can't remove their reference
738
            //so it's best to keep using the same reference, but change the original object
739
            //reset all its properties to their original values as defined in the class
740
            $r = new ReflectionClass(get_class(static::$_instance));
741
            $static_properties = $r->getStaticProperties();
742
            foreach ($r->getDefaultProperties() as $property => $value) {
743
                //don't set instance to null like it was originally,
744
                //but it's static anyways, and we're ignoring static properties (for now at least)
745
                if (! isset($static_properties[$property])) {
746
                    static::$_instance->{$property} = $value;
747
                }
748
            }
749
            //and then directly call its constructor again, like we would if we were creating a new one
750
            $model_field_factory = self::getModelFieldFactory($model_field_factory);
751
            static::$_instance->__construct($timezone, $model_field_factory);
752
            return self::instance();
753
        }
754
        return null;
755
    }
756
757
758
759
    /**
760
     * @return LoaderInterface
761
     * @throws InvalidArgumentException
762
     * @throws InvalidDataTypeException
763
     * @throws InvalidInterfaceException
764
     */
765
    private static function getLoader()
766
    {
767
        if(! EEM_Base::$loader instanceof LoaderInterface) {
768
            EEM_Base::$loader = LoaderFactory::getLoader();
769
        }
770
        return EEM_Base::$loader;
771
    }
772
773
774
775
    /**
776
     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
777
     *
778
     * @param  boolean $translated return localized strings or JUST the array.
779
     * @return array
780
     * @throws EE_Error
781
     * @throws InvalidArgumentException
782
     * @throws InvalidDataTypeException
783
     * @throws InvalidInterfaceException
784
     */
785
    public function status_array($translated = false)
786
    {
787
        if (! array_key_exists('Status', $this->_model_relations)) {
788
            return array();
789
        }
790
        $model_name = $this->get_this_model_name();
791
        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
792
        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
793
        $status_array = array();
794
        foreach ($stati as $status) {
795
            $status_array[$status->ID()] = $status->get('STS_code');
796
        }
797
        return $translated
798
            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
799
            : $status_array;
800
    }
801
802
803
804
    /**
805
     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
806
     *
807
     * @param array $query_params             {
808
     * @var array $0 (where) array {
809
     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
810
     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
811
     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
812
     *                                        conditions based on related models (and even
813
     *                                        models-related-to-related-models) prepend the model's name onto the field
814
     *                                        name. Eg,
815
     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
816
     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
817
     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
818
     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
819
     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
820
     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
821
     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
822
     *                                        to Venues (even when each of those models actually consisted of two
823
     *                                        tables). Also, you may chain the model relations together. Eg instead of
824
     *                                        just having
825
     *                                        "Venue.VNU_ID", you could have
826
     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
827
     *                                        events are related to Registrations, which are related to Attendees). You
828
     *                                        can take it even further with
829
     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
830
     *                                        (from the default of '='), change the value to an numerically-indexed
831
     *                                        array, where the first item in the list is the operator. eg: array(
832
     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
833
     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
834
     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
835
     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
836
     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
837
     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
838
     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
839
     *                                        the operator is IN. Also, values can actually be field names. To indicate
840
     *                                        the value is a field, simply provide a third array item (true) to the
841
     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
842
     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
843
     *                                        Note: you can also use related model field names like you would any other
844
     *                                        field name. eg:
845
     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
846
     *                                        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__>' =>
847
     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
848
     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
849
     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
850
     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
851
     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
852
     *                                        to be what you last specified. IE, "AND"s by default, but if you had
853
     *                                        previously specified to use ORs to join, ORs will continue to be used.
854
     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
855
     *                                        "stick" until you specify an AND. eg
856
     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
857
     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
858
     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
859
     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
860
     *                                        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 >>
861
     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
862
     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
863
     *                                        too, eg:
864
     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
865
     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
866
     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
867
     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
868
     *                                        Remember when you provide two numbers for the limit, the 1st number is
869
     *                                        the OFFSET, the 2nd is the LIMIT
870
     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
871
     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
872
     *                                        following format array('on_join_limit'
873
     *                                        => array( 'table_alias', array(1,2) ) ).
874
     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
875
     *                                        values are either 'ASC' or 'DESC'.
876
     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
877
     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
878
     *                                        DESC..." respectively. Like the
879
     *                                        'where' conditions, these fields can be on related models. Eg
880
     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
881
     *                                        perfectly valid from any model related to 'Registration' (like Event,
882
     *                                        Attendee, Price, Datetime, etc.)
883
     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
884
     *                                        'order' specifies whether to order the field specified in 'order_by' in
885
     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
886
     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
887
     *                                        order by the primary key. Eg,
888
     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
889
     *                                        //(will join with the Datetime model's table(s) and order by its field
890
     *                                        DTT_EVT_start) or
891
     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
892
     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
893
     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
894
     *                                        'group_by'=>'VNU_ID', or
895
     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
896
     *                                        if no
897
     *                                        $group_by is specified, and a limit is set, automatically groups by the
898
     *                                        model's primary key (or combined primary keys). This avoids some
899
     *                                        weirdness that results when using limits, tons of joins, and no group by,
900
     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
901
     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
902
     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
903
     *                                        results)
904
     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
905
     *                                        array where values are models to be joined in the query.Eg
906
     *                                        array('Attendee','Payment','Datetime'). You may join with transient
907
     *                                        models using period, eg "Registration.Transaction.Payment". You will
908
     *                                        probably only want to do this in hopes of increasing efficiency, as
909
     *                                        related models which belongs to the current model
910
     *                                        (ie, the current model has a foreign key to them, like how Registration
911
     *                                        belongs to Attendee) can be cached in order to avoid future queries
912
     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
913
     *                                        set this to 'none' to disable all default where conditions. Eg, usually
914
     *                                        soft-deleted objects are filtered-out if you want to include them, set
915
     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
916
     *                                        default where conditions set it to 'other_models_only'. If you only want
917
     *                                        this model's default where conditions added to the query, use
918
     *                                        'this_model_only'. If you want to use all default where conditions
919
     *                                        (default), set to 'all'.
920
     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
921
     *                                        we just NOT apply any capabilities/permissions/restrictions and return
922
     *                                        everything? Or should we only show the current user items they should be
923
     *                                        able to view on the frontend, backend, edit, or delete? can be set to
924
     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
925
     *                                        }
926
     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
927
     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
928
     *                                        again. Array keys are object IDs (if there is a primary key on the model.
929
     *                                        if not, numerically indexed) Some full examples: get 10 transactions
930
     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
931
     *                                        array( array(
932
     *                                        'OR'=>array(
933
     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
934
     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
935
     *                                        )
936
     *                                        ),
937
     *                                        'limit'=>10,
938
     *                                        'group_by'=>'TXN_ID'
939
     *                                        ));
940
     *                                        get all the answers to the question titled "shirt size" for event with id
941
     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
942
     *                                        'Question.QST_display_text'=>'shirt size',
943
     *                                        'Registration.Event.EVT_ID'=>12
944
     *                                        ),
945
     *                                        'order_by'=>array('ANS_value'=>'ASC')
946
     *                                        ));
947
     * @throws EE_Error
948
     */
949
    public function get_all($query_params = array())
950
    {
951
        if (isset($query_params['limit'])
952
            && ! isset($query_params['group_by'])
953
        ) {
954
            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
955
        }
956
        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
957
    }
958
959
960
961
    /**
962
     * Modifies the query parameters so we only get back model objects
963
     * that "belong" to the current user
964
     *
965
     * @param array $query_params @see EEM_Base::get_all()
966
     * @return array like EEM_Base::get_all
967
     */
968
    public function alter_query_params_to_only_include_mine($query_params = array())
969
    {
970
        $wp_user_field_name = $this->wp_user_field_name();
971
        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...
972
            $query_params[0][$wp_user_field_name] = get_current_user_id();
973
        }
974
        return $query_params;
975
    }
976
977
978
979
    /**
980
     * Returns the name of the field's name that points to the WP_User table
981
     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
982
     * foreign key to the WP_User table)
983
     *
984
     * @return string|boolean string on success, boolean false when there is no
985
     * foreign key to the WP_User table
986
     */
987
    public function wp_user_field_name()
988
    {
989
        try {
990
            if (! empty($this->_model_chain_to_wp_user)) {
991
                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
992
                $last_model_name = end($models_to_follow_to_wp_users);
993
                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
994
                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
995
            } else {
996
                $model_with_fk_to_wp_users = $this;
997
                $model_chain_to_wp_user = '';
998
            }
999
            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
1000
            return $model_chain_to_wp_user . $wp_user_field->get_name();
1001
        } catch (EE_Error $e) {
1002
            return false;
1003
        }
1004
    }
1005
1006
1007
1008
    /**
1009
     * Returns the _model_chain_to_wp_user string, which indicates which related model
1010
     * (or transiently-related model) has a foreign key to the wp_users table;
1011
     * useful for finding if model objects of this type are 'owned' by the current user.
1012
     * This is an empty string when the foreign key is on this model and when it isn't,
1013
     * but is only non-empty when this model's ownership is indicated by a RELATED model
1014
     * (or transiently-related model)
1015
     *
1016
     * @return string
1017
     */
1018
    public function model_chain_to_wp_user()
1019
    {
1020
        return $this->_model_chain_to_wp_user;
1021
    }
1022
1023
1024
1025
    /**
1026
     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1027
     * like how registrations don't have a foreign key to wp_users, but the
1028
     * events they are for are), or is unrelated to wp users.
1029
     * generally available
1030
     *
1031
     * @return boolean
1032
     */
1033
    public function is_owned()
1034
    {
1035
        if ($this->model_chain_to_wp_user()) {
1036
            return true;
1037
        }
1038
        try {
1039
            $this->get_foreign_key_to('WP_User');
1040
            return true;
1041
        } catch (EE_Error $e) {
1042
            return false;
1043
        }
1044
    }
1045
1046
1047
1048
    /**
1049
     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1050
     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1051
     * the model)
1052
     *
1053
     * @param array  $query_params      like EEM_Base::get_all's $query_params
1054
     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1055
     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1056
     *                                  fields on the model, and the models we joined to in the query. However, you can
1057
     *                                  override this and set the select to "*", or a specific column name, like
1058
     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1059
     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1060
     *                                  the aliases used to refer to this selection, and values are to be
1061
     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1062
     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1063
     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1064
     * @throws EE_Error
1065
     */
1066
    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1067
    {
1068
        // remember the custom selections, if any, and type cast as array
1069
        // (unless $columns_to_select is an object, then just set as an empty array)
1070
        // Note: (array) 'some string' === array( 'some string' )
1071
        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1072
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1073
        $select_expressions = $columns_to_select !== null
1074
            ? $this->_construct_select_from_input($columns_to_select)
1075
            : $this->_construct_default_select_sql($model_query_info);
1076
        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1077
        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1078
    }
1079
1080
1081
1082
    /**
1083
     * Gets an array of rows from the database just like $wpdb->get_results would,
1084
     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1085
     * take care of joins, field preparation etc.
1086
     *
1087
     * @param array  $query_params      like EEM_Base::get_all's $query_params
1088
     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1089
     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1090
     *                                  fields on the model, and the models we joined to in the query. However, you can
1091
     *                                  override this and set the select to "*", or a specific column name, like
1092
     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1093
     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1094
     *                                  the aliases used to refer to this selection, and values are to be
1095
     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1096
     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1097
     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1098
     * @throws EE_Error
1099
     */
1100
    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1101
    {
1102
        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1103
    }
1104
1105
1106
1107
    /**
1108
     * For creating a custom select statement
1109
     *
1110
     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1111
     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1112
     *                                 SQL, and 1=>is the datatype
1113
     * @throws EE_Error
1114
     * @return string
1115
     */
1116
    private function _construct_select_from_input($columns_to_select)
1117
    {
1118
        if (is_array($columns_to_select)) {
1119
            $select_sql_array = array();
1120
            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1121
                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1122
                    throw new EE_Error(
1123
                        sprintf(
1124
                            __(
1125
                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1126
                                'event_espresso'
1127
                            ),
1128
                            $selection_and_datatype,
1129
                            $alias
1130
                        )
1131
                    );
1132
                }
1133
                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1134
                    throw new EE_Error(
1135
                        sprintf(
1136
                            esc_html__(
1137
                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1138
                                'event_espresso'
1139
                            ),
1140
                            $selection_and_datatype[1],
1141
                            $selection_and_datatype[0],
1142
                            $alias,
1143
                            implode(', ', $this->_valid_wpdb_data_types)
1144
                        )
1145
                    );
1146
                }
1147
                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1148
            }
1149
            $columns_to_select_string = implode(', ', $select_sql_array);
1150
        } else {
1151
            $columns_to_select_string = $columns_to_select;
1152
        }
1153
        return $columns_to_select_string;
1154
    }
1155
1156
1157
1158
    /**
1159
     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1160
     *
1161
     * @return string
1162
     * @throws EE_Error
1163
     */
1164
    public function primary_key_name()
1165
    {
1166
        return $this->get_primary_key_field()->get_name();
1167
    }
1168
1169
1170
1171
    /**
1172
     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1173
     * If there is no primary key on this model, $id is treated as primary key string
1174
     *
1175
     * @param mixed $id int or string, depending on the type of the model's primary key
1176
     * @return EE_Base_Class
1177
     */
1178
    public function get_one_by_ID($id)
1179
    {
1180
        if ($this->get_from_entity_map($id)) {
1181
            return $this->get_from_entity_map($id);
1182
        }
1183
        return $this->get_one(
1184
            $this->alter_query_params_to_restrict_by_ID(
1185
                $id,
1186
                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1187
            )
1188
        );
1189
    }
1190
1191
1192
1193
    /**
1194
     * Alters query parameters to only get items with this ID are returned.
1195
     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1196
     * or could just be a simple primary key ID
1197
     *
1198
     * @param int   $id
1199
     * @param array $query_params
1200
     * @return array of normal query params, @see EEM_Base::get_all
1201
     * @throws EE_Error
1202
     */
1203
    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1204
    {
1205
        if (! isset($query_params[0])) {
1206
            $query_params[0] = array();
1207
        }
1208
        $conditions_from_id = $this->parse_index_primary_key_string($id);
1209
        if ($conditions_from_id === null) {
1210
            $query_params[0][$this->primary_key_name()] = $id;
1211
        } else {
1212
            //no primary key, so the $id must be from the get_index_primary_key_string()
1213
            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1214
        }
1215
        return $query_params;
1216
    }
1217
1218
1219
1220
    /**
1221
     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1222
     * array. If no item is found, null is returned.
1223
     *
1224
     * @param array $query_params like EEM_Base's $query_params variable.
1225
     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1226
     * @throws EE_Error
1227
     */
1228 View Code Duplication
    public function get_one($query_params = array())
1229
    {
1230
        if (! is_array($query_params)) {
1231
            EE_Error::doing_it_wrong('EEM_Base::get_one',
1232
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1233
                    gettype($query_params)), '4.6.0');
1234
            $query_params = array();
1235
        }
1236
        $query_params['limit'] = 1;
1237
        $items = $this->get_all($query_params);
1238
        if (empty($items)) {
1239
            return null;
1240
        }
1241
        return array_shift($items);
1242
    }
1243
1244
1245
1246
    /**
1247
     * Returns the next x number of items in sequence from the given value as
1248
     * found in the database matching the given query conditions.
1249
     *
1250
     * @param mixed $current_field_value    Value used for the reference point.
1251
     * @param null  $field_to_order_by      What field is used for the
1252
     *                                      reference point.
1253
     * @param int   $limit                  How many to return.
1254
     * @param array $query_params           Extra conditions on the query.
1255
     * @param null  $columns_to_select      If left null, then an array of
1256
     *                                      EE_Base_Class objects is returned,
1257
     *                                      otherwise you can indicate just the
1258
     *                                      columns you want returned.
1259
     * @return EE_Base_Class[]|array
1260
     * @throws EE_Error
1261
     */
1262
    public function next_x(
1263
        $current_field_value,
1264
        $field_to_order_by = null,
1265
        $limit = 1,
1266
        $query_params = array(),
1267
        $columns_to_select = null
1268
    ) {
1269
        return $this->_get_consecutive(
1270
            $current_field_value,
1271
            '>',
1272
            $field_to_order_by,
1273
            $limit,
1274
            $query_params,
1275
            $columns_to_select
1276
        );
1277
    }
1278
1279
1280
1281
    /**
1282
     * Returns the previous x number of items in sequence from the given value
1283
     * as found in the database matching the given query conditions.
1284
     *
1285
     * @param mixed $current_field_value    Value used for the reference point.
1286
     * @param null  $field_to_order_by      What field is used for the
1287
     *                                      reference point.
1288
     * @param int   $limit                  How many to return.
1289
     * @param array $query_params           Extra conditions on the query.
1290
     * @param null  $columns_to_select      If left null, then an array of
1291
     *                                      EE_Base_Class objects is returned,
1292
     *                                      otherwise you can indicate just the
1293
     *                                      columns you want returned.
1294
     * @return EE_Base_Class[]|array
1295
     * @throws EE_Error
1296
     */
1297
    public function previous_x(
1298
        $current_field_value,
1299
        $field_to_order_by = null,
1300
        $limit = 1,
1301
        $query_params = array(),
1302
        $columns_to_select = null
1303
    ) {
1304
        return $this->_get_consecutive(
1305
            $current_field_value,
1306
            '<',
1307
            $field_to_order_by,
1308
            $limit,
1309
            $query_params,
1310
            $columns_to_select
1311
        );
1312
    }
1313
1314
1315
1316
    /**
1317
     * Returns the next item in sequence from the given value as found in the
1318
     * database matching the given query conditions.
1319
     *
1320
     * @param mixed $current_field_value    Value used for the reference point.
1321
     * @param null  $field_to_order_by      What field is used for the
1322
     *                                      reference point.
1323
     * @param array $query_params           Extra conditions on the query.
1324
     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1325
     *                                      object is returned, otherwise you
1326
     *                                      can indicate just the columns you
1327
     *                                      want and a single array indexed by
1328
     *                                      the columns will be returned.
1329
     * @return EE_Base_Class|null|array()
1330
     * @throws EE_Error
1331
     */
1332 View Code Duplication
    public function next(
1333
        $current_field_value,
1334
        $field_to_order_by = null,
1335
        $query_params = array(),
1336
        $columns_to_select = null
1337
    ) {
1338
        $results = $this->_get_consecutive(
1339
            $current_field_value,
1340
            '>',
1341
            $field_to_order_by,
1342
            1,
1343
            $query_params,
1344
            $columns_to_select
1345
        );
1346
        return empty($results) ? null : reset($results);
1347
    }
1348
1349
1350
1351
    /**
1352
     * Returns the previous item in sequence from the given value as found in
1353
     * the database matching the given query conditions.
1354
     *
1355
     * @param mixed $current_field_value    Value used for the reference point.
1356
     * @param null  $field_to_order_by      What field is used for the
1357
     *                                      reference point.
1358
     * @param array $query_params           Extra conditions on the query.
1359
     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1360
     *                                      object is returned, otherwise you
1361
     *                                      can indicate just the columns you
1362
     *                                      want and a single array indexed by
1363
     *                                      the columns will be returned.
1364
     * @return EE_Base_Class|null|array()
1365
     * @throws EE_Error
1366
     */
1367 View Code Duplication
    public function previous(
1368
        $current_field_value,
1369
        $field_to_order_by = null,
1370
        $query_params = array(),
1371
        $columns_to_select = null
1372
    ) {
1373
        $results = $this->_get_consecutive(
1374
            $current_field_value,
1375
            '<',
1376
            $field_to_order_by,
1377
            1,
1378
            $query_params,
1379
            $columns_to_select
1380
        );
1381
        return empty($results) ? null : reset($results);
1382
    }
1383
1384
1385
1386
    /**
1387
     * Returns the a consecutive number of items in sequence from the given
1388
     * value as found in the database matching the given query conditions.
1389
     *
1390
     * @param mixed  $current_field_value   Value used for the reference point.
1391
     * @param string $operand               What operand is used for the sequence.
1392
     * @param string $field_to_order_by     What field is used for the reference point.
1393
     * @param int    $limit                 How many to return.
1394
     * @param array  $query_params          Extra conditions on the query.
1395
     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1396
     *                                      otherwise you can indicate just the columns you want returned.
1397
     * @return EE_Base_Class[]|array
1398
     * @throws EE_Error
1399
     */
1400
    protected function _get_consecutive(
1401
        $current_field_value,
1402
        $operand = '>',
1403
        $field_to_order_by = null,
1404
        $limit = 1,
1405
        $query_params = array(),
1406
        $columns_to_select = null
1407
    ) {
1408
        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1409
        if (empty($field_to_order_by)) {
1410
            if ($this->has_primary_key_field()) {
1411
                $field_to_order_by = $this->get_primary_key_field()->get_name();
1412
            } else {
1413
                if (WP_DEBUG) {
1414
                    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).',
1415
                        'event_espresso'));
1416
                }
1417
                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1418
                return array();
1419
            }
1420
        }
1421
        if (! is_array($query_params)) {
1422
            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1423
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1424
                    gettype($query_params)), '4.6.0');
1425
            $query_params = array();
1426
        }
1427
        //let's add the where query param for consecutive look up.
1428
        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1429
        $query_params['limit'] = $limit;
1430
        //set direction
1431
        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1432
        $query_params['order_by'] = $operand === '>'
1433
            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1434
            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1435
        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1436
        if (empty($columns_to_select)) {
1437
            return $this->get_all($query_params);
1438
        }
1439
        //getting just the fields
1440
        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1441
    }
1442
1443
1444
1445
    /**
1446
     * This sets the _timezone property after model object has been instantiated.
1447
     *
1448
     * @param null | string $timezone valid PHP DateTimeZone timezone string
1449
     */
1450
    public function set_timezone($timezone)
1451
    {
1452
        if ($timezone !== null) {
1453
            $this->_timezone = $timezone;
1454
        }
1455
        //note we need to loop through relations and set the timezone on those objects as well.
1456
        foreach ($this->_model_relations as $relation) {
1457
            $relation->set_timezone($timezone);
1458
        }
1459
        //and finally we do the same for any datetime fields
1460
        foreach ($this->_fields as $field) {
1461
            if ($field instanceof EE_Datetime_Field) {
1462
                $field->set_timezone($timezone);
1463
            }
1464
        }
1465
    }
1466
1467
1468
1469
    /**
1470
     * This just returns whatever is set for the current timezone.
1471
     *
1472
     * @access public
1473
     * @return string
1474
     */
1475
    public function get_timezone()
1476
    {
1477
        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1478
        if (empty($this->_timezone)) {
1479
            foreach ($this->_fields as $field) {
1480
                if ($field instanceof EE_Datetime_Field) {
1481
                    $this->set_timezone($field->get_timezone());
1482
                    break;
1483
                }
1484
            }
1485
        }
1486
        //if timezone STILL empty then return the default timezone for the site.
1487
        if (empty($this->_timezone)) {
1488
            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1489
        }
1490
        return $this->_timezone;
1491
    }
1492
1493
1494
1495
    /**
1496
     * This returns the date formats set for the given field name and also ensures that
1497
     * $this->_timezone property is set correctly.
1498
     *
1499
     * @since 4.6.x
1500
     * @param string $field_name The name of the field the formats are being retrieved for.
1501
     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1502
     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1503
     * @return array formats in an array with the date format first, and the time format last.
1504
     */
1505
    public function get_formats_for($field_name, $pretty = false)
1506
    {
1507
        $field_settings = $this->field_settings_for($field_name);
1508
        //if not a valid EE_Datetime_Field then throw error
1509
        if (! $field_settings instanceof EE_Datetime_Field) {
1510
            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.',
1511
                'event_espresso'), $field_name));
1512
        }
1513
        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1514
        //the field.
1515
        $this->_timezone = $field_settings->get_timezone();
1516
        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1517
    }
1518
1519
1520
1521
    /**
1522
     * This returns the current time in a format setup for a query on this model.
1523
     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1524
     * it will return:
1525
     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1526
     *  NOW
1527
     *  - or a unix timestamp (equivalent to time())
1528
     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1529
     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1530
     * the time returned to be the current time down to the exact second, set $timestamp to true.
1531
     * @since 4.6.x
1532
     * @param string $field_name       The field the current time is needed for.
1533
     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1534
     *                                 formatted string matching the set format for the field in the set timezone will
1535
     *                                 be returned.
1536
     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1537
     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1538
     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1539
     *                                 exception is triggered.
1540
     */
1541
    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1542
    {
1543
        $formats = $this->get_formats_for($field_name);
1544
        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1545
        if ($timestamp) {
1546
            return $DateTime->format('U');
1547
        }
1548
        //not returning timestamp, so return formatted string in timezone.
1549
        switch ($what) {
1550
            case 'time' :
1551
                return $DateTime->format($formats[1]);
1552
                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...
1553
            case 'date' :
1554
                return $DateTime->format($formats[0]);
1555
                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...
1556
            default :
1557
                return $DateTime->format(implode(' ', $formats));
1558
                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...
1559
        }
1560
    }
1561
1562
1563
1564
    /**
1565
     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1566
     * for the model are.  Returns a DateTime object.
1567
     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1568
     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1569
     * ignored.
1570
     *
1571
     * @param string $field_name      The field being setup.
1572
     * @param string $timestring      The date time string being used.
1573
     * @param string $incoming_format The format for the time string.
1574
     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1575
     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1576
     *                                format is
1577
     *                                'U', this is ignored.
1578
     * @return DateTime
1579
     * @throws EE_Error
1580
     */
1581
    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1582
    {
1583
        //just using this to ensure the timezone is set correctly internally
1584
        $this->get_formats_for($field_name);
1585
        //load EEH_DTT_Helper
1586
        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1587
        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1588
        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1589
    }
1590
1591
1592
1593
    /**
1594
     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1595
     *
1596
     * @return EE_Table_Base[]
1597
     */
1598
    public function get_tables()
1599
    {
1600
        return $this->_tables;
1601
    }
1602
1603
1604
1605
    /**
1606
     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1607
     * also updates all the model objects, where the criteria expressed in $query_params are met..
1608
     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1609
     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1610
     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1611
     * model object with EVT_ID = 1
1612
     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1613
     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1614
     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1615
     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1616
     * are not specified)
1617
     *
1618
     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1619
     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1620
     *                                         are to be serialized. Basically, the values are what you'd expect to be
1621
     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1622
     *                                         we wanted to update only the TXN_details on any Transactions where its
1623
     *                                         ID=34, we'd use this method as follows:
1624
     *                                         EEM_Transaction::instance()->update(
1625
     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1626
     *                                         array(array('TXN_ID'=>34)));
1627
     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1628
     *                                         in client code into what's expected to be stored on each field. Eg,
1629
     *                                         consider updating Question's QST_admin_label field is of type
1630
     *                                         Simple_HTML. If you use this function to update that field to $new_value
1631
     *                                         = (note replace 8's with appropriate opening and closing tags in the
1632
     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1633
     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1634
     *                                         TRUE, it is assumed that you've already called
1635
     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1636
     *                                         malicious javascript. However, if
1637
     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1638
     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1639
     *                                         and every other field, before insertion. We provide this parameter
1640
     *                                         because model objects perform their prepare_for_set function on all
1641
     *                                         their values, and so don't need to be called again (and in many cases,
1642
     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1643
     *                                         prepare_for_set method...)
1644
     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1645
     *                                         in this model's entity map according to $fields_n_values that match
1646
     *                                         $query_params. This obviously has some overhead, so you can disable it
1647
     *                                         by setting this to FALSE, but be aware that model objects being used
1648
     *                                         could get out-of-sync with the database
1649
     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1650
     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1651
     *                                         bad)
1652
     * @throws EE_Error
1653
     */
1654
    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1655
    {
1656
        if (! is_array($query_params)) {
1657
            EE_Error::doing_it_wrong('EEM_Base::update',
1658
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1659
                    gettype($query_params)), '4.6.0');
1660
            $query_params = array();
1661
        }
1662
        /**
1663
         * Action called before a model update call has been made.
1664
         *
1665
         * @param EEM_Base $model
1666
         * @param array    $fields_n_values the updated fields and their new values
1667
         * @param array    $query_params    @see EEM_Base::get_all()
1668
         */
1669
        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1670
        /**
1671
         * Filters the fields about to be updated given the query parameters. You can provide the
1672
         * $query_params to $this->get_all() to find exactly which records will be updated
1673
         *
1674
         * @param array    $fields_n_values fields and their new values
1675
         * @param EEM_Base $model           the model being queried
1676
         * @param array    $query_params    see EEM_Base::get_all()
1677
         */
1678
        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1679
            $query_params);
1680
        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1681
        //to do that, for each table, verify that it's PK isn't null.
1682
        $tables = $this->get_tables();
1683
        //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
1684
        //NOTE: we should make this code more efficient by NOT querying twice
1685
        //before the real update, but that needs to first go through ALPHA testing
1686
        //as it's dangerous. says Mike August 8 2014
1687
        //we want to make sure the default_where strategy is ignored
1688
        $this->_ignore_where_strategy = true;
1689
        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1690
        foreach ($wpdb_select_results as $wpdb_result) {
1691
            // type cast stdClass as array
1692
            $wpdb_result = (array)$wpdb_result;
1693
            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1694
            if ($this->has_primary_key_field()) {
1695
                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1696
            } else {
1697
                //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)
1698
                $main_table_pk_value = null;
1699
            }
1700
            //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
1701
            //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
1702
            if (count($tables) > 1) {
1703
                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1704
                //in that table, and so we'll want to insert one
1705
                foreach ($tables as $table_obj) {
1706
                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1707
                    //if there is no private key for this table on the results, it means there's no entry
1708
                    //in this table, right? so insert a row in the current table, using any fields available
1709
                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1710
                           && $wpdb_result[$this_table_pk_column])
1711
                    ) {
1712
                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1713
                            $main_table_pk_value);
1714
                        //if we died here, report the error
1715
                        if (! $success) {
1716
                            return false;
1717
                        }
1718
                    }
1719
                }
1720
            }
1721
            //				//and now check that if we have cached any models by that ID on the model, that
1722
            //				//they also get updated properly
1723
            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1724
            //				if( $model_object ){
1725
            //					foreach( $fields_n_values as $field => $value ){
1726
            //						$model_object->set($field, $value);
1727
            //let's make sure default_where strategy is followed now
1728
            $this->_ignore_where_strategy = false;
1729
        }
1730
        //if we want to keep model objects in sync, AND
1731
        //if this wasn't called from a model object (to update itself)
1732
        //then we want to make sure we keep all the existing
1733
        //model objects in sync with the db
1734
        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1735
            if ($this->has_primary_key_field()) {
1736
                $model_objs_affected_ids = $this->get_col($query_params);
1737
            } else {
1738
                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1739
                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1740
                $model_objs_affected_ids = array();
1741
                foreach ($models_affected_key_columns as $row) {
1742
                    $combined_index_key = $this->get_index_primary_key_string($row);
1743
                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1744
                }
1745
            }
1746
            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...
1747
                //wait wait wait- if nothing was affected let's stop here
1748
                return 0;
1749
            }
1750
            foreach ($model_objs_affected_ids as $id) {
1751
                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1752
                if ($model_obj_in_entity_map) {
1753
                    foreach ($fields_n_values as $field => $new_value) {
1754
                        $model_obj_in_entity_map->set($field, $new_value);
1755
                    }
1756
                }
1757
            }
1758
            //if there is a primary key on this model, we can now do a slight optimization
1759
            if ($this->has_primary_key_field()) {
1760
                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1761
                $query_params = array(
1762
                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1763
                    'limit'                    => count($model_objs_affected_ids),
1764
                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1765
                );
1766
            }
1767
        }
1768
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
        $SQL = "UPDATE "
1770
               . $model_query_info->get_full_join_sql()
1771
               . " SET "
1772
               . $this->_construct_update_sql($fields_n_values)
1773
               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1774
        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1775
        /**
1776
         * Action called after a model update call has been made.
1777
         *
1778
         * @param EEM_Base $model
1779
         * @param array    $fields_n_values the updated fields and their new values
1780
         * @param array    $query_params    @see EEM_Base::get_all()
1781
         * @param int      $rows_affected
1782
         */
1783
        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1784
        return $rows_affected;//how many supposedly got updated
1785
    }
1786
1787
1788
1789
    /**
1790
     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1791
     * are teh values of the field specified (or by default the primary key field)
1792
     * that matched the query params. Note that you should pass the name of the
1793
     * model FIELD, not the database table's column name.
1794
     *
1795
     * @param array  $query_params @see EEM_Base::get_all()
1796
     * @param string $field_to_select
1797
     * @return array just like $wpdb->get_col()
1798
     * @throws EE_Error
1799
     */
1800
    public function get_col($query_params = array(), $field_to_select = null)
1801
    {
1802
        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...
1803
            $field = $this->field_settings_for($field_to_select);
1804
        } elseif ($this->has_primary_key_field()) {
1805
            $field = $this->get_primary_key_field();
1806
        } else {
1807
            //no primary key, just grab the first column
1808
            $field = reset($this->field_settings());
1809
        }
1810
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1811
        $select_expressions = $field->get_qualified_column();
1812
        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1813
        return $this->_do_wpdb_query('get_col', array($SQL));
1814
    }
1815
1816
1817
1818
    /**
1819
     * Returns a single column value for a single row from the database
1820
     *
1821
     * @param array  $query_params    @see EEM_Base::get_all()
1822
     * @param string $field_to_select @see EEM_Base::get_col()
1823
     * @return string
1824
     * @throws EE_Error
1825
     */
1826
    public function get_var($query_params = array(), $field_to_select = null)
1827
    {
1828
        $query_params['limit'] = 1;
1829
        $col = $this->get_col($query_params, $field_to_select);
1830
        if (! empty($col)) {
1831
            return reset($col);
1832
        }
1833
        return null;
1834
    }
1835
1836
1837
1838
    /**
1839
     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1840
     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1841
     * injection, but currently no further filtering is done
1842
     *
1843
     * @global      $wpdb
1844
     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1845
     *                               be updated to in the DB
1846
     * @return string of SQL
1847
     * @throws EE_Error
1848
     */
1849
    public function _construct_update_sql($fields_n_values)
1850
    {
1851
        /** @type WPDB $wpdb */
1852
        global $wpdb;
1853
        $cols_n_values = array();
1854
        foreach ($fields_n_values as $field_name => $value) {
1855
            $field_obj = $this->field_settings_for($field_name);
1856
            //if the value is NULL, we want to assign the value to that.
1857
            //wpdb->prepare doesn't really handle that properly
1858
            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1859
            $value_sql = $prepared_value === null ? 'NULL'
1860
                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1861
            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1862
        }
1863
        return implode(",", $cols_n_values);
1864
    }
1865
1866
1867
1868
    /**
1869
     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1870
     * Performs a HARD delete, meaning the database row should always be removed,
1871
     * not just have a flag field on it switched
1872
     * Wrapper for EEM_Base::delete_permanently()
1873
     *
1874
     * @param mixed $id
1875
     * @param boolean $allow_blocking
1876
     * @return int the number of rows deleted
1877
     * @throws EE_Error
1878
     */
1879 View Code Duplication
    public function delete_permanently_by_ID($id, $allow_blocking = true)
1880
    {
1881
        return $this->delete_permanently(
1882
            array(
1883
                array($this->get_primary_key_field()->get_name() => $id),
1884
                'limit' => 1,
1885
            ),
1886
            $allow_blocking
1887
        );
1888
    }
1889
1890
1891
1892
    /**
1893
     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1894
     * Wrapper for EEM_Base::delete()
1895
     *
1896
     * @param mixed $id
1897
     * @param boolean $allow_blocking
1898
     * @return int the number of rows deleted
1899
     * @throws EE_Error
1900
     */
1901 View Code Duplication
    public function delete_by_ID($id, $allow_blocking = true)
1902
    {
1903
        return $this->delete(
1904
            array(
1905
                array($this->get_primary_key_field()->get_name() => $id),
1906
                'limit' => 1,
1907
            ),
1908
            $allow_blocking
1909
        );
1910
    }
1911
1912
1913
1914
    /**
1915
     * Identical to delete_permanently, but does a "soft" delete if possible,
1916
     * meaning if the model has a field that indicates its been "trashed" or
1917
     * "soft deleted", we will just set that instead of actually deleting the rows.
1918
     *
1919
     * @see EEM_Base::delete_permanently
1920
     * @param array   $query_params
1921
     * @param boolean $allow_blocking
1922
     * @return int how many rows got deleted
1923
     * @throws EE_Error
1924
     */
1925
    public function delete($query_params, $allow_blocking = true)
1926
    {
1927
        return $this->delete_permanently($query_params, $allow_blocking);
1928
    }
1929
1930
1931
1932
    /**
1933
     * Deletes the model objects that meet the query params. Note: this method is overridden
1934
     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1935
     * as archived, not actually deleted
1936
     *
1937
     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1938
     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1939
     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1940
     *                                deletes regardless of other objects which may depend on it. Its generally
1941
     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1942
     *                                DB
1943
     * @return int how many rows got deleted
1944
     * @throws EE_Error
1945
     */
1946
    public function delete_permanently($query_params, $allow_blocking = true)
1947
    {
1948
        /**
1949
         * Action called just before performing a real deletion query. You can use the
1950
         * model and its $query_params to find exactly which items will be deleted
1951
         *
1952
         * @param EEM_Base $model
1953
         * @param array    $query_params   @see EEM_Base::get_all()
1954
         * @param boolean  $allow_blocking whether or not to allow related model objects
1955
         *                                 to block (prevent) this deletion
1956
         */
1957
        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1958
        //some MySQL databases may be running safe mode, which may restrict
1959
        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1960
        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1961
        //to delete them
1962
        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1963
        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1964
        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1965
            $columns_and_ids_for_deleting
1966
        );
1967
        /**
1968
         * Allows client code to act on the items being deleted before the query is actually executed.
1969
         *
1970
         * @param EEM_Base $this  The model instance being acted on.
1971
         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1972
         * @param bool     $allow_blocking @see param description in method phpdoc block.
1973
         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1974
         *                                                  derived from the incoming query parameters.
1975
         *                                                  @see details on the structure of this array in the phpdocs
1976
         *                                                  for the `_get_ids_for_delete_method`
1977
         *
1978
         */
1979
        do_action('AHEE__EEM_Base__delete__before_query',
1980
            $this,
1981
            $query_params,
1982
            $allow_blocking,
1983
            $columns_and_ids_for_deleting
1984
        );
1985
        if ($deletion_where_query_part) {
1986
            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1987
            $table_aliases = array_keys($this->_tables);
1988
            $SQL = "DELETE "
1989
                   . implode(", ", $table_aliases)
1990
                   . " FROM "
1991
                   . $model_query_info->get_full_join_sql()
1992
                   . " WHERE "
1993
                   . $deletion_where_query_part;
1994
            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1995
        } else {
1996
            $rows_deleted = 0;
1997
        }
1998
1999
        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2000
        //there was no error with the delete query.
2001
        if ($this->has_primary_key_field()
2002
            && $rows_deleted !== false
2003
            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2004
        ) {
2005
            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2006
            foreach ($ids_for_removal as $id) {
2007 View Code Duplication
                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2008
                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2009
                }
2010
            }
2011
2012
            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2013
            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2014
            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2015
            // (although it is possible).
2016
            //Note this can be skipped by using the provided filter and returning false.
2017
            if (apply_filters(
2018
                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2019
                ! $this instanceof EEM_Extra_Meta,
2020
                $this
2021
            )) {
2022
                EEM_Extra_Meta::instance()->delete_permanently(array(
2023
                    0 => array(
2024
                        'EXM_type' => $this->get_this_model_name(),
2025
                        'OBJ_ID'   => array(
2026
                            'IN',
2027
                            $ids_for_removal
2028
                        )
2029
                    )
2030
                ));
2031
            }
2032
        }
2033
2034
        /**
2035
         * Action called just after performing a real deletion query. Although at this point the
2036
         * items should have been deleted
2037
         *
2038
         * @param EEM_Base $model
2039
         * @param array    $query_params @see EEM_Base::get_all()
2040
         * @param int      $rows_deleted
2041
         */
2042
        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2043
        return $rows_deleted;//how many supposedly got deleted
2044
    }
2045
2046
2047
2048
    /**
2049
     * Checks all the relations that throw error messages when there are blocking related objects
2050
     * for related model objects. If there are any related model objects on those relations,
2051
     * adds an EE_Error, and return true
2052
     *
2053
     * @param EE_Base_Class|int $this_model_obj_or_id
2054
     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2055
     *                                                 should be ignored when determining whether there are related
2056
     *                                                 model objects which block this model object's deletion. Useful
2057
     *                                                 if you know A is related to B and are considering deleting A,
2058
     *                                                 but want to see if A has any other objects blocking its deletion
2059
     *                                                 before removing the relation between A and B
2060
     * @return boolean
2061
     * @throws EE_Error
2062
     */
2063
    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2064
    {
2065
        //first, if $ignore_this_model_obj was supplied, get its model
2066
        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2067
            $ignored_model = $ignore_this_model_obj->get_model();
2068
        } else {
2069
            $ignored_model = null;
2070
        }
2071
        //now check all the relations of $this_model_obj_or_id and see if there
2072
        //are any related model objects blocking it?
2073
        $is_blocked = false;
2074
        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2075
            if ($relation_obj->block_delete_if_related_models_exist()) {
2076
                //if $ignore_this_model_obj was supplied, then for the query
2077
                //on that model needs to be told to ignore $ignore_this_model_obj
2078
                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2079
                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2080
                        array(
2081
                            $ignored_model->get_primary_key_field()->get_name() => array(
2082
                                '!=',
2083
                                $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...
2084
                            ),
2085
                        ),
2086
                    ));
2087
                } else {
2088
                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2089
                }
2090
                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...
2091
                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2092
                    $is_blocked = true;
2093
                }
2094
            }
2095
        }
2096
        return $is_blocked;
2097
    }
2098
2099
2100
    /**
2101
     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2102
     * @param array $row_results_for_deleting
2103
     * @param bool  $allow_blocking
2104
     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2105
     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2106
     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2107
     *                 deleted. Example:
2108
     *                      array('Event.EVT_ID' => array( 1,2,3))
2109
     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2110
     *                 where each element is a group of columns and values that get deleted. Example:
2111
     *                      array(
2112
     *                          0 => array(
2113
     *                              'Term_Relationship.object_id' => 1
2114
     *                              'Term_Relationship.term_taxonomy_id' => 5
2115
     *                          ),
2116
     *                          1 => array(
2117
     *                              'Term_Relationship.object_id' => 1
2118
     *                              'Term_Relationship.term_taxonomy_id' => 6
2119
     *                          )
2120
     *                      )
2121
     * @throws EE_Error
2122
     */
2123
    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2124
    {
2125
        $ids_to_delete_indexed_by_column = array();
2126
        if ($this->has_primary_key_field()) {
2127
            $primary_table = $this->_get_main_table();
2128
            $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...
2129
            $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...
2130
            $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...
2131
            foreach ($row_results_for_deleting as $item_to_delete) {
2132
                //before we mark this item for deletion,
2133
                //make sure there's no related entities blocking its deletion (if we're checking)
2134
                if (
2135
                    $allow_blocking
2136
                    && $this->delete_is_blocked_by_related_models(
2137
                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2138
                    )
2139
                ) {
2140
                    continue;
2141
                }
2142
                //primary table deletes
2143
                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2144
                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2145
                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2146
                }
2147
            }
2148
        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2149
            $fields = $this->get_combined_primary_key_fields();
2150
            foreach ($row_results_for_deleting as $item_to_delete) {
2151
                $ids_to_delete_indexed_by_column_for_row = array();
2152
                foreach ($fields as $cpk_field) {
2153
                    if ($cpk_field instanceof EE_Model_Field_Base) {
2154
                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2155
                            $item_to_delete[$cpk_field->get_qualified_column()];
2156
                    }
2157
                }
2158
                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2159
            }
2160
        } else {
2161
            //so there's no primary key and no combined key...
2162
            //sorry, can't help you
2163
            throw new EE_Error(
2164
                sprintf(
2165
                    __(
2166
                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2167
                        "event_espresso"
2168
                    ), get_class($this)
2169
                )
2170
            );
2171
        }    
2172
        return $ids_to_delete_indexed_by_column;
2173
    }
2174
2175
2176
    /**
2177
     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2178
     * the corresponding query_part for the query performing the delete.
2179
     *
2180
     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2181
     * @return string
2182
     * @throws EE_Error
2183
     */
2184
    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2185
        $query_part = '';
2186
        if (empty($ids_to_delete_indexed_by_column)) {
2187
            return $query_part;
2188
        } elseif ($this->has_primary_key_field()) {
2189
            $query = array();
2190
            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2191
                //make sure we have unique $ids
2192
                $ids = array_unique($ids);
2193
                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2194
            }
2195
            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2196
        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2197
            $ways_to_identify_a_row = array();
2198
            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2199
                $values_for_each_combined_primary_key_for_a_row = array();
2200
                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2201
                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2202
                }
2203
                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2204
            }
2205
            $query_part = implode(' OR ', $ways_to_identify_a_row);
2206
        }
2207
        return $query_part;
2208
    }
2209
    
2210
2211
2212
    /**
2213
     * Gets the model field by the fully qualified name
2214
     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2215
     * @return EE_Model_Field_Base
2216
     */
2217
    public function get_field_by_column($qualified_column_name)
2218
    {
2219
       foreach($this->field_settings(true) as $field_name => $field_obj){
2220
           if($field_obj->get_qualified_column() === $qualified_column_name){
2221
               return $field_obj;
2222
           }
2223
       }
2224
        throw new EE_Error(
2225
            sprintf(
2226
                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2227
                $this->get_this_model_name(),
2228
                $qualified_column_name
2229
            )
2230
        );
2231
    }
2232
2233
2234
2235
    /**
2236
     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2237
     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2238
     * column
2239
     *
2240
     * @param array  $query_params   like EEM_Base::get_all's
2241
     * @param string $field_to_count field on model to count by (not column name)
2242
     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2243
     *                               that by the setting $distinct to TRUE;
2244
     * @return int
2245
     * @throws EE_Error
2246
     */
2247
    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2248
    {
2249
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2250
        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...
2251
            $field_obj = $this->field_settings_for($field_to_count);
2252
            $column_to_count = $field_obj->get_qualified_column();
2253
        } elseif ($this->has_primary_key_field()) {
2254
            $pk_field_obj = $this->get_primary_key_field();
2255
            $column_to_count = $pk_field_obj->get_qualified_column();
2256
        } else {
2257
            //there's no primary key
2258
            //if we're counting distinct items, and there's no primary key,
2259
            //we need to list out the columns for distinction;
2260
            //otherwise we can just use star
2261
            if ($distinct) {
2262
                $columns_to_use = array();
2263
                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2264
                    $columns_to_use[] = $field_obj->get_qualified_column();
2265
                }
2266
                $column_to_count = implode(',', $columns_to_use);
2267
            } else {
2268
                $column_to_count = '*';
2269
            }
2270
        }
2271
        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2272
        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2273
        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2274
    }
2275
2276
2277
2278
    /**
2279
     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2280
     *
2281
     * @param array  $query_params like EEM_Base::get_all
2282
     * @param string $field_to_sum name of field (array key in $_fields array)
2283
     * @return float
2284
     * @throws EE_Error
2285
     */
2286
    public function sum($query_params, $field_to_sum = null)
2287
    {
2288
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2289
        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...
2290
            $field_obj = $this->field_settings_for($field_to_sum);
2291
        } else {
2292
            $field_obj = $this->get_primary_key_field();
2293
        }
2294
        $column_to_count = $field_obj->get_qualified_column();
2295
        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2296
        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2297
        $data_type = $field_obj->get_wpdb_data_type();
2298
        if ($data_type === '%d' || $data_type === '%s') {
2299
            return (float)$return_value;
2300
        }
2301
        //must be %f
2302
        return (float)$return_value;
2303
    }
2304
2305
2306
2307
    /**
2308
     * Just calls the specified method on $wpdb with the given arguments
2309
     * Consolidates a little extra error handling code
2310
     *
2311
     * @param string $wpdb_method
2312
     * @param array  $arguments_to_provide
2313
     * @throws EE_Error
2314
     * @global wpdb  $wpdb
2315
     * @return mixed
2316
     */
2317
    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2318
    {
2319
        //if we're in maintenance mode level 2, DON'T run any queries
2320
        //because level 2 indicates the database needs updating and
2321
        //is probably out of sync with the code
2322
        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2323
            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.",
2324
                "event_espresso")));
2325
        }
2326
        /** @type WPDB $wpdb */
2327
        global $wpdb;
2328 View Code Duplication
        if (! method_exists($wpdb, $wpdb_method)) {
2329
            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2330
                'event_espresso'), $wpdb_method));
2331
        }
2332
        if (WP_DEBUG) {
2333
            $old_show_errors_value = $wpdb->show_errors;
2334
            $wpdb->show_errors(false);
2335
        }
2336
        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2337
        $this->show_db_query_if_previously_requested($wpdb->last_query);
2338
        if (WP_DEBUG) {
2339
            $wpdb->show_errors($old_show_errors_value);
2340
            if (! empty($wpdb->last_error)) {
2341
                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2342
            }
2343
            if ($result === false) {
2344
                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"',
2345
                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2346
            }
2347
        } elseif ($result === false) {
2348
            EE_Error::add_error(
2349
                sprintf(
2350
                    __('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"',
2351
                        'event_espresso'),
2352
                    $wpdb_method,
2353
                    var_export($arguments_to_provide, true),
2354
                    $wpdb->last_error
2355
                ),
2356
                __FILE__,
2357
                __FUNCTION__,
2358
                __LINE__
2359
            );
2360
        }
2361
        return $result;
2362
    }
2363
2364
2365
2366
    /**
2367
     * Attempts to run the indicated WPDB method with the provided arguments,
2368
     * and if there's an error tries to verify the DB is correct. Uses
2369
     * the static property EEM_Base::$_db_verification_level to determine whether
2370
     * we should try to fix the EE core db, the addons, or just give up
2371
     *
2372
     * @param string $wpdb_method
2373
     * @param array  $arguments_to_provide
2374
     * @return mixed
2375
     */
2376
    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2377
    {
2378
        /** @type WPDB $wpdb */
2379
        global $wpdb;
2380
        $wpdb->last_error = null;
2381
        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2382
        // was there an error running the query? but we don't care on new activations
2383
        // (we're going to setup the DB anyway on new activations)
2384
        if (($result === false || ! empty($wpdb->last_error))
2385
            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2386
        ) {
2387
            switch (EEM_Base::$_db_verification_level) {
2388
                case EEM_Base::db_verified_none :
2389
                    // let's double-check core's DB
2390
                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2391
                    break;
2392
                case EEM_Base::db_verified_core :
2393
                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2394
                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2395
                    break;
2396
                case EEM_Base::db_verified_addons :
2397
                    // ummmm... you in trouble
2398
                    return $result;
2399
                    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...
2400
            }
2401
            if (! empty($error_message)) {
2402
                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2403
                trigger_error($error_message);
2404
            }
2405
            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2406
        }
2407
        return $result;
2408
    }
2409
2410
2411
2412
    /**
2413
     * Verifies the EE core database is up-to-date and records that we've done it on
2414
     * EEM_Base::$_db_verification_level
2415
     *
2416
     * @param string $wpdb_method
2417
     * @param array  $arguments_to_provide
2418
     * @return string
2419
     */
2420 View Code Duplication
    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2421
    {
2422
        /** @type WPDB $wpdb */
2423
        global $wpdb;
2424
        //ok remember that we've already attempted fixing the core db, in case the problem persists
2425
        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2426
        $error_message = sprintf(
2427
            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2428
                'event_espresso'),
2429
            $wpdb->last_error,
2430
            $wpdb_method,
2431
            wp_json_encode($arguments_to_provide)
2432
        );
2433
        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2434
        return $error_message;
2435
    }
2436
2437
2438
2439
    /**
2440
     * Verifies the EE addons' database is up-to-date and records that we've done it on
2441
     * EEM_Base::$_db_verification_level
2442
     *
2443
     * @param $wpdb_method
2444
     * @param $arguments_to_provide
2445
     * @return string
2446
     */
2447 View Code Duplication
    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2448
    {
2449
        /** @type WPDB $wpdb */
2450
        global $wpdb;
2451
        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2452
        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2453
        $error_message = sprintf(
2454
            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2455
                'event_espresso'),
2456
            $wpdb->last_error,
2457
            $wpdb_method,
2458
            wp_json_encode($arguments_to_provide)
2459
        );
2460
        EE_System::instance()->initialize_addons();
2461
        return $error_message;
2462
    }
2463
2464
2465
2466
    /**
2467
     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2468
     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2469
     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2470
     * ..."
2471
     *
2472
     * @param EE_Model_Query_Info_Carrier $model_query_info
2473
     * @return string
2474
     */
2475
    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2476
    {
2477
        return " FROM " . $model_query_info->get_full_join_sql() .
2478
               $model_query_info->get_where_sql() .
2479
               $model_query_info->get_group_by_sql() .
2480
               $model_query_info->get_having_sql() .
2481
               $model_query_info->get_order_by_sql() .
2482
               $model_query_info->get_limit_sql();
2483
    }
2484
2485
2486
2487
    /**
2488
     * Set to easily debug the next X queries ran from this model.
2489
     *
2490
     * @param int $count
2491
     */
2492
    public function show_next_x_db_queries($count = 1)
2493
    {
2494
        $this->_show_next_x_db_queries = $count;
2495
    }
2496
2497
2498
2499
    /**
2500
     * @param $sql_query
2501
     */
2502
    public function show_db_query_if_previously_requested($sql_query)
2503
    {
2504
        if ($this->_show_next_x_db_queries > 0) {
2505
            echo $sql_query;
2506
            $this->_show_next_x_db_queries--;
2507
        }
2508
    }
2509
2510
2511
2512
    /**
2513
     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2514
     * There are the 3 cases:
2515
     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2516
     * $otherModelObject has no ID, it is first saved.
2517
     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2518
     * has no ID, it is first saved.
2519
     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2520
     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2521
     * join table
2522
     *
2523
     * @param        EE_Base_Class                     /int $thisModelObject
2524
     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2525
     * @param string $relationName                     , key in EEM_Base::_relations
2526
     *                                                 an attendee to a group, you also want to specify which role they
2527
     *                                                 will have in that group. So you would use this parameter to
2528
     *                                                 specify array('role-column-name'=>'role-id')
2529
     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2530
     *                                                 to for relation to methods that allow you to further specify
2531
     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2532
     *                                                 only acceptable query_params is strict "col" => "value" pairs
2533
     *                                                 because these will be inserted in any new rows created as well.
2534
     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2535
     * @throws EE_Error
2536
     */
2537
    public function add_relationship_to(
2538
        $id_or_obj,
2539
        $other_model_id_or_obj,
2540
        $relationName,
2541
        $extra_join_model_fields_n_values = array()
2542
    ) {
2543
        $relation_obj = $this->related_settings_for($relationName);
2544
        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2545
    }
2546
2547
2548
2549
    /**
2550
     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2551
     * There are the 3 cases:
2552
     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2553
     * error
2554
     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2555
     * an error
2556
     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2557
     *
2558
     * @param        EE_Base_Class /int $id_or_obj
2559
     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2560
     * @param string $relationName key in EEM_Base::_relations
2561
     * @return boolean of success
2562
     * @throws EE_Error
2563
     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2564
     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2565
     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2566
     *                             because these will be inserted in any new rows created as well.
2567
     */
2568
    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2569
    {
2570
        $relation_obj = $this->related_settings_for($relationName);
2571
        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2572
    }
2573
2574
2575
2576
    /**
2577
     * @param mixed           $id_or_obj
2578
     * @param string          $relationName
2579
     * @param array           $where_query_params
2580
     * @param EE_Base_Class[] objects to which relations were removed
2581
     * @return \EE_Base_Class[]
2582
     * @throws EE_Error
2583
     */
2584
    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2585
    {
2586
        $relation_obj = $this->related_settings_for($relationName);
2587
        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2588
    }
2589
2590
2591
2592
    /**
2593
     * Gets all the related items of the specified $model_name, using $query_params.
2594
     * Note: by default, we remove the "default query params"
2595
     * because we want to get even deleted items etc.
2596
     *
2597
     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2598
     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2599
     * @param array  $query_params like EEM_Base::get_all
2600
     * @return EE_Base_Class[]
2601
     * @throws EE_Error
2602
     */
2603
    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2604
    {
2605
        $model_obj = $this->ensure_is_obj($id_or_obj);
2606
        $relation_settings = $this->related_settings_for($model_name);
2607
        return $relation_settings->get_all_related($model_obj, $query_params);
2608
    }
2609
2610
2611
2612
    /**
2613
     * Deletes all the model objects across the relation indicated by $model_name
2614
     * which are related to $id_or_obj which meet the criteria set in $query_params.
2615
     * However, if the model objects can't be deleted because of blocking related model objects, then
2616
     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2617
     *
2618
     * @param EE_Base_Class|int|string $id_or_obj
2619
     * @param string                   $model_name
2620
     * @param array                    $query_params
2621
     * @return int how many deleted
2622
     * @throws EE_Error
2623
     */
2624
    public function delete_related($id_or_obj, $model_name, $query_params = array())
2625
    {
2626
        $model_obj = $this->ensure_is_obj($id_or_obj);
2627
        $relation_settings = $this->related_settings_for($model_name);
2628
        return $relation_settings->delete_all_related($model_obj, $query_params);
2629
    }
2630
2631
2632
2633
    /**
2634
     * Hard deletes all the model objects across the relation indicated by $model_name
2635
     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2636
     * the model objects can't be hard deleted because of blocking related model objects,
2637
     * just does a soft-delete on them instead.
2638
     *
2639
     * @param EE_Base_Class|int|string $id_or_obj
2640
     * @param string                   $model_name
2641
     * @param array                    $query_params
2642
     * @return int how many deleted
2643
     * @throws EE_Error
2644
     */
2645
    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2646
    {
2647
        $model_obj = $this->ensure_is_obj($id_or_obj);
2648
        $relation_settings = $this->related_settings_for($model_name);
2649
        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2650
    }
2651
2652
2653
2654
    /**
2655
     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2656
     * unless otherwise specified in the $query_params
2657
     *
2658
     * @param        int             /EE_Base_Class $id_or_obj
2659
     * @param string $model_name     like 'Event', or 'Registration'
2660
     * @param array  $query_params   like EEM_Base::get_all's
2661
     * @param string $field_to_count name of field to count by. By default, uses primary key
2662
     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2663
     *                               that by the setting $distinct to TRUE;
2664
     * @return int
2665
     * @throws EE_Error
2666
     */
2667
    public function count_related(
2668
        $id_or_obj,
2669
        $model_name,
2670
        $query_params = array(),
2671
        $field_to_count = null,
2672
        $distinct = false
2673
    ) {
2674
        $related_model = $this->get_related_model_obj($model_name);
2675
        //we're just going to use the query params on the related model's normal get_all query,
2676
        //except add a condition to say to match the current mod
2677
        if (! isset($query_params['default_where_conditions'])) {
2678
            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2679
        }
2680
        $this_model_name = $this->get_this_model_name();
2681
        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2682
        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2683
        return $related_model->count($query_params, $field_to_count, $distinct);
2684
    }
2685
2686
2687
2688
    /**
2689
     * Instead of getting the related model objects, simply sums up the values of the specified field.
2690
     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2691
     *
2692
     * @param        int           /EE_Base_Class $id_or_obj
2693
     * @param string $model_name   like 'Event', or 'Registration'
2694
     * @param array  $query_params like EEM_Base::get_all's
2695
     * @param string $field_to_sum name of field to count by. By default, uses primary key
2696
     * @return float
2697
     * @throws EE_Error
2698
     */
2699
    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2700
    {
2701
        $related_model = $this->get_related_model_obj($model_name);
2702
        if (! is_array($query_params)) {
2703
            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2704
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2705
                    gettype($query_params)), '4.6.0');
2706
            $query_params = array();
2707
        }
2708
        //we're just going to use the query params on the related model's normal get_all query,
2709
        //except add a condition to say to match the current mod
2710
        if (! isset($query_params['default_where_conditions'])) {
2711
            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712
        }
2713
        $this_model_name = $this->get_this_model_name();
2714
        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2715
        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2716
        return $related_model->sum($query_params, $field_to_sum);
2717
    }
2718
2719
2720
2721
    /**
2722
     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2723
     * $modelObject
2724
     *
2725
     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2726
     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2727
     * @param array               $query_params     like EEM_Base::get_all's
2728
     * @return EE_Base_Class
2729
     * @throws EE_Error
2730
     */
2731
    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2732
    {
2733
        $query_params['limit'] = 1;
2734
        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2735
        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...
2736
            return array_shift($results);
2737
        }
2738
        return null;
2739
    }
2740
2741
2742
2743
    /**
2744
     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2745
     *
2746
     * @return string
2747
     */
2748
    public function get_this_model_name()
2749
    {
2750
        return str_replace("EEM_", "", get_class($this));
2751
    }
2752
2753
2754
2755
    /**
2756
     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2757
     *
2758
     * @return EE_Any_Foreign_Model_Name_Field
2759
     * @throws EE_Error
2760
     */
2761
    public function get_field_containing_related_model_name()
2762
    {
2763
        foreach ($this->field_settings(true) as $field) {
2764
            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2765
                $field_with_model_name = $field;
2766
            }
2767
        }
2768 View Code Duplication
        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2769
            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2770
                $this->get_this_model_name()));
2771
        }
2772
        return $field_with_model_name;
2773
    }
2774
2775
2776
2777
    /**
2778
     * Inserts a new entry into the database, for each table.
2779
     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2780
     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2781
     * we also know there is no model object with the newly inserted item's ID at the moment (because
2782
     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2783
     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2784
     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2785
     *
2786
     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2787
     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2788
     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2789
     *                              of EEM_Base)
2790
     * @return int new primary key on main table that got inserted
2791
     * @throws EE_Error
2792
     */
2793
    public function insert($field_n_values)
2794
    {
2795
        /**
2796
         * Filters the fields and their values before inserting an item using the models
2797
         *
2798
         * @param array    $fields_n_values keys are the fields and values are their new values
2799
         * @param EEM_Base $model           the model used
2800
         */
2801
        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2802
        if ($this->_satisfies_unique_indexes($field_n_values)) {
2803
            $main_table = $this->_get_main_table();
2804
            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2805
            if ($new_id !== false) {
2806
                foreach ($this->_get_other_tables() as $other_table) {
2807
                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2808
                }
2809
            }
2810
            /**
2811
             * Done just after attempting to insert a new model object
2812
             *
2813
             * @param EEM_Base   $model           used
2814
             * @param array      $fields_n_values fields and their values
2815
             * @param int|string the              ID of the newly-inserted model object
2816
             */
2817
            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2818
            return $new_id;
2819
        }
2820
        return false;
2821
    }
2822
2823
2824
2825
    /**
2826
     * Checks that the result would satisfy the unique indexes on this model
2827
     *
2828
     * @param array  $field_n_values
2829
     * @param string $action
2830
     * @return boolean
2831
     * @throws EE_Error
2832
     */
2833
    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2834
    {
2835
        foreach ($this->unique_indexes() as $index_name => $index) {
2836
            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2837
            if ($this->exists(array($uniqueness_where_params))) {
2838
                EE_Error::add_error(
2839
                    sprintf(
2840
                        __(
2841
                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2842
                            "event_espresso"
2843
                        ),
2844
                        $action,
2845
                        $this->_get_class_name(),
2846
                        $index_name,
2847
                        implode(",", $index->field_names()),
2848
                        http_build_query($uniqueness_where_params)
2849
                    ),
2850
                    __FILE__,
2851
                    __FUNCTION__,
2852
                    __LINE__
2853
                );
2854
                return false;
2855
            }
2856
        }
2857
        return true;
2858
    }
2859
2860
2861
2862
    /**
2863
     * Checks the database for an item that conflicts (ie, if this item were
2864
     * saved to the DB would break some uniqueness requirement, like a primary key
2865
     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2866
     * can be either an EE_Base_Class or an array of fields n values
2867
     *
2868
     * @param EE_Base_Class|array $obj_or_fields_array
2869
     * @param boolean             $include_primary_key whether to use the model object's primary key
2870
     *                                                 when looking for conflicts
2871
     *                                                 (ie, if false, we ignore the model object's primary key
2872
     *                                                 when finding "conflicts". If true, it's also considered).
2873
     *                                                 Only works for INT primary key,
2874
     *                                                 STRING primary keys cannot be ignored
2875
     * @throws EE_Error
2876
     * @return EE_Base_Class|array
2877
     */
2878
    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2879
    {
2880 View Code Duplication
        if ($obj_or_fields_array instanceof EE_Base_Class) {
2881
            $fields_n_values = $obj_or_fields_array->model_field_array();
2882
        } elseif (is_array($obj_or_fields_array)) {
2883
            $fields_n_values = $obj_or_fields_array;
2884
        } else {
2885
            throw new EE_Error(
2886
                sprintf(
2887
                    __(
2888
                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2889
                        "event_espresso"
2890
                    ),
2891
                    get_class($this),
2892
                    $obj_or_fields_array
2893
                )
2894
            );
2895
        }
2896
        $query_params = array();
2897
        if ($this->has_primary_key_field()
2898
            && ($include_primary_key
2899
                || $this->get_primary_key_field()
2900
                   instanceof
2901
                   EE_Primary_Key_String_Field)
2902
            && isset($fields_n_values[$this->primary_key_name()])
2903
        ) {
2904
            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2905
        }
2906
        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2907
            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2908
            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2909
        }
2910
        //if there is nothing to base this search on, then we shouldn't find anything
2911
        if (empty($query_params)) {
2912
            return array();
2913
        }
2914
        return $this->get_one($query_params);
2915
    }
2916
2917
2918
2919
    /**
2920
     * Like count, but is optimized and returns a boolean instead of an int
2921
     *
2922
     * @param array $query_params
2923
     * @return boolean
2924
     * @throws EE_Error
2925
     */
2926
    public function exists($query_params)
2927
    {
2928
        $query_params['limit'] = 1;
2929
        return $this->count($query_params) > 0;
2930
    }
2931
2932
2933
2934
    /**
2935
     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2936
     *
2937
     * @param int|string $id
2938
     * @return boolean
2939
     * @throws EE_Error
2940
     */
2941
    public function exists_by_ID($id)
2942
    {
2943
        return $this->exists(
2944
            array(
2945
                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2946
                array(
2947
                    $this->primary_key_name() => $id,
2948
                ),
2949
            )
2950
        );
2951
    }
2952
2953
2954
2955
    /**
2956
     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2957
     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2958
     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2959
     * on the main table)
2960
     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2961
     * cases where we want to call it directly rather than via insert().
2962
     *
2963
     * @access   protected
2964
     * @param EE_Table_Base $table
2965
     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2966
     *                                       float
2967
     * @param int           $new_id          for now we assume only int keys
2968
     * @throws EE_Error
2969
     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2970
     * @return int ID of new row inserted, or FALSE on failure
2971
     */
2972
    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2973
    {
2974
        global $wpdb;
2975
        $insertion_col_n_values = array();
2976
        $format_for_insertion = array();
2977
        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2978
        foreach ($fields_on_table as $field_name => $field_obj) {
2979
            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2980
            if ($field_obj->is_auto_increment()) {
2981
                continue;
2982
            }
2983
            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2984
            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2985
            if ($prepared_value !== null) {
2986
                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2987
                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2988
            }
2989
        }
2990
        if ($table instanceof EE_Secondary_Table && $new_id) {
2991
            //its not the main table, so we should have already saved the main table's PK which we just inserted
2992
            //so add the fk to the main table as a column
2993
            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2994
            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2995
        }
2996
        //insert the new entry
2997
        $result = $this->_do_wpdb_query('insert',
2998
            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2999
        if ($result === false) {
3000
            return false;
3001
        }
3002
        //ok, now what do we return for the ID of the newly-inserted thing?
3003
        if ($this->has_primary_key_field()) {
3004
            if ($this->get_primary_key_field()->is_auto_increment()) {
3005
                return $wpdb->insert_id;
3006
            }
3007
            //it's not an auto-increment primary key, so
3008
            //it must have been supplied
3009
            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3010
        }
3011
        //we can't return a  primary key because there is none. instead return
3012
        //a unique string indicating this model
3013
        return $this->get_index_primary_key_string($fields_n_values);
3014
    }
3015
3016
3017
3018
    /**
3019
     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3020
     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3021
     * and there is no default, we pass it along. WPDB will take care of it)
3022
     *
3023
     * @param EE_Model_Field_Base $field_obj
3024
     * @param array               $fields_n_values
3025
     * @return mixed string|int|float depending on what the table column will be expecting
3026
     * @throws EE_Error
3027
     */
3028
    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3029
    {
3030
        //if this field doesn't allow nullable, don't allow it
3031
        if (
3032
            ! $field_obj->is_nullable()
3033
            && (
3034
                ! isset($fields_n_values[$field_obj->get_name()])
3035
                || $fields_n_values[$field_obj->get_name()] === null
3036
            )
3037
        ) {
3038
            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3039
        }
3040
        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3041
            ? $fields_n_values[$field_obj->get_name()]
3042
            : null;
3043
        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3044
    }
3045
3046
3047
3048
    /**
3049
     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3050
     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3051
     * the field's prepare_for_set() method.
3052
     *
3053
     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3054
     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3055
     *                                   top of file)
3056
     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3057
     *                                   $value is a custom selection
3058
     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3059
     */
3060
    private function _prepare_value_for_use_in_db($value, $field)
3061
    {
3062
        if ($field && $field instanceof EE_Model_Field_Base) {
3063
            switch ($this->_values_already_prepared_by_model_object) {
3064
                /** @noinspection PhpMissingBreakStatementInspection */
3065
                case self::not_prepared_by_model_object:
3066
                    $value = $field->prepare_for_set($value);
3067
                //purposefully left out "return"
3068
                case self::prepared_by_model_object:
3069
                    /** @noinspection SuspiciousAssignmentsInspection */
3070
                    $value = $field->prepare_for_use_in_db($value);
3071
                case self::prepared_for_use_in_db:
3072
                    //leave the value alone
3073
            }
3074
            return $value;
3075
        }
3076
        return $value;
3077
    }
3078
3079
3080
3081
    /**
3082
     * Returns the main table on this model
3083
     *
3084
     * @return EE_Primary_Table
3085
     * @throws EE_Error
3086
     */
3087
    protected function _get_main_table()
3088
    {
3089
        foreach ($this->_tables as $table) {
3090
            if ($table instanceof EE_Primary_Table) {
3091
                return $table;
3092
            }
3093
        }
3094
        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3095
            'event_espresso'), get_class($this)));
3096
    }
3097
3098
3099
3100
    /**
3101
     * table
3102
     * returns EE_Primary_Table table name
3103
     *
3104
     * @return string
3105
     * @throws EE_Error
3106
     */
3107
    public function table()
3108
    {
3109
        return $this->_get_main_table()->get_table_name();
3110
    }
3111
3112
3113
3114
    /**
3115
     * table
3116
     * returns first EE_Secondary_Table table name
3117
     *
3118
     * @return string
3119
     */
3120
    public function second_table()
3121
    {
3122
        // grab second table from tables array
3123
        $second_table = end($this->_tables);
3124
        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3125
    }
3126
3127
3128
3129
    /**
3130
     * get_table_obj_by_alias
3131
     * returns table name given it's alias
3132
     *
3133
     * @param string $table_alias
3134
     * @return EE_Primary_Table | EE_Secondary_Table
3135
     */
3136
    public function get_table_obj_by_alias($table_alias = '')
3137
    {
3138
        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3139
    }
3140
3141
3142
3143
    /**
3144
     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3145
     *
3146
     * @return EE_Secondary_Table[]
3147
     */
3148
    protected function _get_other_tables()
3149
    {
3150
        $other_tables = array();
3151
        foreach ($this->_tables as $table_alias => $table) {
3152
            if ($table instanceof EE_Secondary_Table) {
3153
                $other_tables[$table_alias] = $table;
3154
            }
3155
        }
3156
        return $other_tables;
3157
    }
3158
3159
3160
3161
    /**
3162
     * Finds all the fields that correspond to the given table
3163
     *
3164
     * @param string $table_alias , array key in EEM_Base::_tables
3165
     * @return EE_Model_Field_Base[]
3166
     */
3167
    public function _get_fields_for_table($table_alias)
3168
    {
3169
        return $this->_fields[$table_alias];
3170
    }
3171
3172
3173
3174
    /**
3175
     * Recurses through all the where parameters, and finds all the related models we'll need
3176
     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3177
     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3178
     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3179
     * related Registration, Transaction, and Payment models.
3180
     *
3181
     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3182
     * @return EE_Model_Query_Info_Carrier
3183
     * @throws EE_Error
3184
     */
3185
    public function _extract_related_models_from_query($query_params)
3186
    {
3187
        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3188
        if (array_key_exists(0, $query_params)) {
3189
            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3190
        }
3191 View Code Duplication
        if (array_key_exists('group_by', $query_params)) {
3192
            if (is_array($query_params['group_by'])) {
3193
                $this->_extract_related_models_from_sub_params_array_values(
3194
                    $query_params['group_by'],
3195
                    $query_info_carrier,
3196
                    'group_by'
3197
                );
3198
            } elseif (! empty ($query_params['group_by'])) {
3199
                $this->_extract_related_model_info_from_query_param(
3200
                    $query_params['group_by'],
3201
                    $query_info_carrier,
3202
                    'group_by'
3203
                );
3204
            }
3205
        }
3206
        if (array_key_exists('having', $query_params)) {
3207
            $this->_extract_related_models_from_sub_params_array_keys(
3208
                $query_params[0],
3209
                $query_info_carrier,
3210
                'having'
3211
            );
3212
        }
3213 View Code Duplication
        if (array_key_exists('order_by', $query_params)) {
3214
            if (is_array($query_params['order_by'])) {
3215
                $this->_extract_related_models_from_sub_params_array_keys(
3216
                    $query_params['order_by'],
3217
                    $query_info_carrier,
3218
                    'order_by'
3219
                );
3220
            } elseif (! empty($query_params['order_by'])) {
3221
                $this->_extract_related_model_info_from_query_param(
3222
                    $query_params['order_by'],
3223
                    $query_info_carrier,
3224
                    'order_by'
3225
                );
3226
            }
3227
        }
3228
        if (array_key_exists('force_join', $query_params)) {
3229
            $this->_extract_related_models_from_sub_params_array_values(
3230
                $query_params['force_join'],
3231
                $query_info_carrier,
3232
                'force_join'
3233
            );
3234
        }
3235
        return $query_info_carrier;
3236
    }
3237
3238
3239
3240
    /**
3241
     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3242
     *
3243
     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3244
     *                                                      $query_params['having']
3245
     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3246
     * @param string                      $query_param_type one of $this->_allowed_query_params
3247
     * @throws EE_Error
3248
     * @return \EE_Model_Query_Info_Carrier
3249
     */
3250
    private function _extract_related_models_from_sub_params_array_keys(
3251
        $sub_query_params,
3252
        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3253
        $query_param_type
3254
    ) {
3255
        if (! empty($sub_query_params)) {
3256
            $sub_query_params = (array)$sub_query_params;
3257
            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3258
                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3259
                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3260
                    $query_param_type);
3261
                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3262
                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3263
                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3264
                //of array('Registration.TXN_ID'=>23)
3265
                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3266
                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3267
                    if (! is_array($possibly_array_of_params)) {
3268
                        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'))",
3269
                            "event_espresso"),
3270
                            $param, $possibly_array_of_params));
3271
                    }
3272
                    $this->_extract_related_models_from_sub_params_array_keys(
3273
                        $possibly_array_of_params,
3274
                        $model_query_info_carrier, $query_param_type
3275
                    );
3276
                } 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...
3277
                          && is_array($possibly_array_of_params)
3278
                          && isset($possibly_array_of_params[2])
3279
                          && $possibly_array_of_params[2] == true
3280
                ) {
3281
                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3282
                    //indicating that $possible_array_of_params[1] is actually a field name,
3283
                    //from which we should extract query parameters!
3284 View Code Duplication
                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3285
                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3286
                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3287
                    }
3288
                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3289
                        $model_query_info_carrier, $query_param_type);
3290
                }
3291
            }
3292
        }
3293
        return $model_query_info_carrier;
3294
    }
3295
3296
3297
3298
    /**
3299
     * For extracting related models from forced_joins, where the array values contain the info about what
3300
     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3301
     *
3302
     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3303
     *                                                      $query_params['having']
3304
     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3305
     * @param string                      $query_param_type one of $this->_allowed_query_params
3306
     * @throws EE_Error
3307
     * @return \EE_Model_Query_Info_Carrier
3308
     */
3309
    private function _extract_related_models_from_sub_params_array_values(
3310
        $sub_query_params,
3311
        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3312
        $query_param_type
3313
    ) {
3314
        if (! empty($sub_query_params)) {
3315
            if (! is_array($sub_query_params)) {
3316
                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3317
                    $sub_query_params));
3318
            }
3319
            foreach ($sub_query_params as $param) {
3320
                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3321
                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3322
                    $query_param_type);
3323
            }
3324
        }
3325
        return $model_query_info_carrier;
3326
    }
3327
3328
3329
3330
    /**
3331
     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3332
     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3333
     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3334
     * but use them in a different order. Eg, we need to know what models we are querying
3335
     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3336
     * other models before we can finalize the where clause SQL.
3337
     *
3338
     * @param array $query_params
3339
     * @throws EE_Error
3340
     * @return EE_Model_Query_Info_Carrier
3341
     */
3342
    public function _create_model_query_info_carrier($query_params)
3343
    {
3344
        if (! is_array($query_params)) {
3345
            EE_Error::doing_it_wrong(
3346
                'EEM_Base::_create_model_query_info_carrier',
3347
                sprintf(
3348
                    __(
3349
                        '$query_params should be an array, you passed a variable of type %s',
3350
                        'event_espresso'
3351
                    ),
3352
                    gettype($query_params)
3353
                ),
3354
                '4.6.0'
3355
            );
3356
            $query_params = array();
3357
        }
3358
        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3359
        //first check if we should alter the query to account for caps or not
3360
        //because the caps might require us to do extra joins
3361
        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3362
            $query_params[0] = $where_query_params = array_replace_recursive(
3363
                $where_query_params,
3364
                $this->caps_where_conditions(
3365
                    $query_params['caps']
3366
                )
3367
            );
3368
        }
3369
        $query_object = $this->_extract_related_models_from_query($query_params);
3370
        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3371
        foreach ($where_query_params as $key => $value) {
3372
            if (is_int($key)) {
3373
                throw new EE_Error(
3374
                    sprintf(
3375
                        __(
3376
                            "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.",
3377
                            "event_espresso"
3378
                        ),
3379
                        $key,
3380
                        var_export($value, true),
3381
                        var_export($query_params, true),
3382
                        get_class($this)
3383
                    )
3384
                );
3385
            }
3386
        }
3387
        if (
3388
            array_key_exists('default_where_conditions', $query_params)
3389
            && ! empty($query_params['default_where_conditions'])
3390
        ) {
3391
            $use_default_where_conditions = $query_params['default_where_conditions'];
3392
        } else {
3393
            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3394
        }
3395
        $where_query_params = array_merge(
3396
            $this->_get_default_where_conditions_for_models_in_query(
3397
                $query_object,
3398
                $use_default_where_conditions,
3399
                $where_query_params
3400
            ),
3401
            $where_query_params
3402
        );
3403
        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3404
        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3405
        // So we need to setup a subquery and use that for the main join.
3406
        // Note for now this only works on the primary table for the model.
3407
        // So for instance, you could set the limit array like this:
3408
        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3409
        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3410
            $query_object->set_main_model_join_sql(
3411
                $this->_construct_limit_join_select(
3412
                    $query_params['on_join_limit'][0],
3413
                    $query_params['on_join_limit'][1]
3414
                )
3415
            );
3416
        }
3417
        //set limit
3418
        if (array_key_exists('limit', $query_params)) {
3419
            if (is_array($query_params['limit'])) {
3420
                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3421
                    $e = sprintf(
3422
                        __(
3423
                            "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)",
3424
                            "event_espresso"
3425
                        ),
3426
                        http_build_query($query_params['limit'])
3427
                    );
3428
                    throw new EE_Error($e . "|" . $e);
3429
                }
3430
                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3431
                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3432
            } elseif (! empty ($query_params['limit'])) {
3433
                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3434
            }
3435
        }
3436
        //set order by
3437
        if (array_key_exists('order_by', $query_params)) {
3438
            if (is_array($query_params['order_by'])) {
3439
                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3440
                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3441
                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3442
                if (array_key_exists('order', $query_params)) {
3443
                    throw new EE_Error(
3444
                        sprintf(
3445
                            __(
3446
                                "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 ",
3447
                                "event_espresso"
3448
                            ),
3449
                            get_class($this),
3450
                            implode(", ", array_keys($query_params['order_by'])),
3451
                            implode(", ", $query_params['order_by']),
3452
                            $query_params['order']
3453
                        )
3454
                    );
3455
                }
3456
                $this->_extract_related_models_from_sub_params_array_keys(
3457
                    $query_params['order_by'],
3458
                    $query_object,
3459
                    'order_by'
3460
                );
3461
                //assume it's an array of fields to order by
3462
                $order_array = array();
3463
                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3464
                    $order = $this->_extract_order($order);
3465
                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3466
                }
3467
                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3468
            } elseif (! empty ($query_params['order_by'])) {
3469
                $this->_extract_related_model_info_from_query_param(
3470
                    $query_params['order_by'],
3471
                    $query_object,
3472
                    'order',
3473
                    $query_params['order_by']
3474
                );
3475
                $order = isset($query_params['order'])
3476
                    ? $this->_extract_order($query_params['order'])
3477
                    : 'DESC';
3478
                $query_object->set_order_by_sql(
3479
                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3480
                );
3481
            }
3482
        }
3483
        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3484
        if (! array_key_exists('order_by', $query_params)
3485
            && array_key_exists('order', $query_params)
3486
            && ! empty($query_params['order'])
3487
        ) {
3488
            $pk_field = $this->get_primary_key_field();
3489
            $order = $this->_extract_order($query_params['order']);
3490
            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3491
        }
3492
        //set group by
3493
        if (array_key_exists('group_by', $query_params)) {
3494
            if (is_array($query_params['group_by'])) {
3495
                //it's an array, so assume we'll be grouping by a bunch of stuff
3496
                $group_by_array = array();
3497
                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3498
                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3499
                }
3500
                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3501
            } elseif (! empty ($query_params['group_by'])) {
3502
                $query_object->set_group_by_sql(
3503
                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3504
                );
3505
            }
3506
        }
3507
        //set having
3508
        if (array_key_exists('having', $query_params) && $query_params['having']) {
3509
            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3510
        }
3511
        //now, just verify they didn't pass anything wack
3512
        foreach ($query_params as $query_key => $query_value) {
3513 View Code Duplication
            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3514
                throw new EE_Error(
3515
                    sprintf(
3516
                        __(
3517
                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3518
                            'event_espresso'
3519
                        ),
3520
                        $query_key,
3521
                        get_class($this),
3522
                        //						print_r( $this->_allowed_query_params, TRUE )
3523
                        implode(',', $this->_allowed_query_params)
3524
                    )
3525
                );
3526
            }
3527
        }
3528
        $main_model_join_sql = $query_object->get_main_model_join_sql();
3529
        if (empty($main_model_join_sql)) {
3530
            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3531
        }
3532
        return $query_object;
3533
    }
3534
3535
3536
3537
    /**
3538
     * Gets the where conditions that should be imposed on the query based on the
3539
     * context (eg reading frontend, backend, edit or delete).
3540
     *
3541
     * @param string $context one of EEM_Base::valid_cap_contexts()
3542
     * @return array like EEM_Base::get_all() 's $query_params[0]
3543
     * @throws EE_Error
3544
     */
3545
    public function caps_where_conditions($context = self::caps_read)
3546
    {
3547
        EEM_Base::verify_is_valid_cap_context($context);
3548
        $cap_where_conditions = array();
3549
        $cap_restrictions = $this->caps_missing($context);
3550
        /**
3551
         * @var $cap_restrictions EE_Default_Where_Conditions[]
3552
         */
3553
        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3554
            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3555
                $restriction_if_no_cap->get_default_where_conditions());
3556
        }
3557
        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3558
            $cap_restrictions);
3559
    }
3560
3561
3562
3563
    /**
3564
     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3565
     * otherwise throws an exception
3566
     *
3567
     * @param string $should_be_order_string
3568
     * @return string either ASC, asc, DESC or desc
3569
     * @throws EE_Error
3570
     */
3571 View Code Duplication
    private function _extract_order($should_be_order_string)
3572
    {
3573
        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3574
            return $should_be_order_string;
3575
        }
3576
        throw new EE_Error(
3577
            sprintf(
3578
                __(
3579
                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3580
                    "event_espresso"
3581
                ), get_class($this), $should_be_order_string
3582
            )
3583
        );
3584
    }
3585
3586
3587
3588
    /**
3589
     * Looks at all the models which are included in this query, and asks each
3590
     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3591
     * so they can be merged
3592
     *
3593
     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3594
     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3595
     *                                                                  'none' means NO default where conditions will
3596
     *                                                                  be used AT ALL during this query.
3597
     *                                                                  'other_models_only' means default where
3598
     *                                                                  conditions from other models will be used, but
3599
     *                                                                  not for this primary model. 'all', the default,
3600
     *                                                                  means default where conditions will apply as
3601
     *                                                                  normal
3602
     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3603
     * @throws EE_Error
3604
     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3605
     */
3606
    private function _get_default_where_conditions_for_models_in_query(
3607
        EE_Model_Query_Info_Carrier $query_info_carrier,
3608
        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3609
        $where_query_params = array()
3610
    ) {
3611
        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3612
        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3613
            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3614
                "event_espresso"), $use_default_where_conditions,
3615
                implode(", ", $allowed_used_default_where_conditions_values)));
3616
        }
3617
        $universal_query_params = array();
3618
        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3619
            $universal_query_params = $this->_get_default_where_conditions();
3620
        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3621
            $universal_query_params = $this->_get_minimum_where_conditions();
3622
        }
3623
        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3624
            $related_model = $this->get_related_model_obj($model_name);
3625
            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3626
                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3627
            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3628
                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3629
            } else {
3630
                //we don't want to add full or even minimum default where conditions from this model, so just continue
3631
                continue;
3632
            }
3633
            $overrides = $this->_override_defaults_or_make_null_friendly(
3634
                $related_model_universal_where_params,
3635
                $where_query_params,
3636
                $related_model,
3637
                $model_relation_path
3638
            );
3639
            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3640
                $universal_query_params,
3641
                $overrides
3642
            );
3643
        }
3644
        return $universal_query_params;
3645
    }
3646
3647
3648
3649
    /**
3650
     * Determines whether or not we should use default where conditions for the model in question
3651
     * (this model, or other related models).
3652
     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3653
     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3654
     * We should use default where conditions on related models when they requested to use default where conditions
3655
     * on all models, or specifically just on other related models
3656
     * @param      $default_where_conditions_value
3657
     * @param bool $for_this_model false means this is for OTHER related models
3658
     * @return bool
3659
     */
3660
    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3661
    {
3662
        return (
3663
                   $for_this_model
3664
                   && in_array(
3665
                       $default_where_conditions_value,
3666
                       array(
3667
                           EEM_Base::default_where_conditions_all,
3668
                           EEM_Base::default_where_conditions_this_only,
3669
                           EEM_Base::default_where_conditions_minimum_others,
3670
                       ),
3671
                       true
3672
                   )
3673
               )
3674
               || (
3675
                   ! $for_this_model
3676
                   && in_array(
3677
                       $default_where_conditions_value,
3678
                       array(
3679
                           EEM_Base::default_where_conditions_all,
3680
                           EEM_Base::default_where_conditions_others_only,
3681
                       ),
3682
                       true
3683
                   )
3684
               );
3685
    }
3686
3687
    /**
3688
     * Determines whether or not we should use default minimum conditions for the model in question
3689
     * (this model, or other related models).
3690
     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3691
     * where conditions.
3692
     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3693
     * on this model or others
3694
     * @param      $default_where_conditions_value
3695
     * @param bool $for_this_model false means this is for OTHER related models
3696
     * @return bool
3697
     */
3698
    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3699
    {
3700
        return (
3701
                   $for_this_model
3702
                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3703
               )
3704
               || (
3705
                   ! $for_this_model
3706
                   && in_array(
3707
                       $default_where_conditions_value,
3708
                       array(
3709
                           EEM_Base::default_where_conditions_minimum_others,
3710
                           EEM_Base::default_where_conditions_minimum_all,
3711
                       ),
3712
                       true
3713
                   )
3714
               );
3715
    }
3716
3717
3718
    /**
3719
     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3720
     * then we also add a special where condition which allows for that model's primary key
3721
     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3722
     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3723
     *
3724
     * @param array    $default_where_conditions
3725
     * @param array    $provided_where_conditions
3726
     * @param EEM_Base $model
3727
     * @param string   $model_relation_path like 'Transaction.Payment.'
3728
     * @return array like EEM_Base::get_all's $query_params[0]
3729
     * @throws EE_Error
3730
     */
3731
    private function _override_defaults_or_make_null_friendly(
3732
        $default_where_conditions,
3733
        $provided_where_conditions,
3734
        $model,
3735
        $model_relation_path
3736
    ) {
3737
        $null_friendly_where_conditions = array();
3738
        $none_overridden = true;
3739
        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3740
        foreach ($default_where_conditions as $key => $val) {
3741
            if (isset($provided_where_conditions[$key])) {
3742
                $none_overridden = false;
3743
            } else {
3744
                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3745
            }
3746
        }
3747
        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...
3748
            if ($model->has_primary_key_field()) {
3749
                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3750
                                                                                . "."
3751
                                                                                . $model->primary_key_name()] = array('IS NULL');
3752
            }/*else{
3753
				//@todo NO PK, use other defaults
3754
			}*/
3755
        }
3756
        return $null_friendly_where_conditions;
3757
    }
3758
3759
3760
3761
    /**
3762
     * Uses the _default_where_conditions_strategy set during __construct() to get
3763
     * default where conditions on all get_all, update, and delete queries done by this model.
3764
     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3765
     * NOT array('Event_CPT.post_type'=>'esp_event').
3766
     *
3767
     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3768
     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3769
     */
3770
    private function _get_default_where_conditions($model_relation_path = null)
3771
    {
3772
        if ($this->_ignore_where_strategy) {
3773
            return array();
3774
        }
3775
        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3776
    }
3777
3778
3779
3780
    /**
3781
     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3782
     * minimum where conditions on all get_all, update, and delete queries done by this model.
3783
     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3784
     * NOT array('Event_CPT.post_type'=>'esp_event').
3785
     * Similar to _get_default_where_conditions
3786
     *
3787
     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3788
     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3789
     */
3790
    protected function _get_minimum_where_conditions($model_relation_path = null)
3791
    {
3792
        if ($this->_ignore_where_strategy) {
3793
            return array();
3794
        }
3795
        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3796
    }
3797
3798
3799
3800
    /**
3801
     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3802
     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3803
     *
3804
     * @param EE_Model_Query_Info_Carrier $model_query_info
3805
     * @return string
3806
     * @throws EE_Error
3807
     */
3808
    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3809
    {
3810
        $selects = $this->_get_columns_to_select_for_this_model();
3811
        foreach (
3812
            $model_query_info->get_model_names_included() as $model_relation_chain =>
3813
            $name_of_other_model_included
3814
        ) {
3815
            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3816
            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3817
            foreach ($other_model_selects as $key => $value) {
3818
                $selects[] = $value;
3819
            }
3820
        }
3821
        return implode(", ", $selects);
3822
    }
3823
3824
3825
3826
    /**
3827
     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3828
     * So that's going to be the columns for all the fields on the model
3829
     *
3830
     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3831
     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3832
     */
3833
    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3834
    {
3835
        $fields = $this->field_settings();
3836
        $selects = array();
3837
        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3838
            $this->get_this_model_name());
3839
        foreach ($fields as $field_obj) {
3840
            $selects[] = $table_alias_with_model_relation_chain_prefix
3841
                         . $field_obj->get_table_alias()
3842
                         . "."
3843
                         . $field_obj->get_table_column()
3844
                         . " AS '"
3845
                         . $table_alias_with_model_relation_chain_prefix
3846
                         . $field_obj->get_table_alias()
3847
                         . "."
3848
                         . $field_obj->get_table_column()
3849
                         . "'";
3850
        }
3851
        //make sure we are also getting the PKs of each table
3852
        $tables = $this->get_tables();
3853
        if (count($tables) > 1) {
3854
            foreach ($tables as $table_obj) {
3855
                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3856
                                       . $table_obj->get_fully_qualified_pk_column();
3857
                if (! in_array($qualified_pk_column, $selects)) {
3858
                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3859
                }
3860
            }
3861
        }
3862
        return $selects;
3863
    }
3864
3865
3866
3867
    /**
3868
     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3869
     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3870
     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3871
     * SQL for joining, and the data types
3872
     *
3873
     * @param null|string                 $original_query_param
3874
     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3875
     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3876
     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3877
     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3878
     *                                                          column name. We only want model names, eg 'Event.Venue'
3879
     *                                                          or 'Registration's
3880
     * @param string                      $original_query_param what it originally was (eg
3881
     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3882
     *                                                          matches $query_param
3883
     * @throws EE_Error
3884
     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3885
     */
3886
    private function _extract_related_model_info_from_query_param(
3887
        $query_param,
3888
        EE_Model_Query_Info_Carrier $passed_in_query_info,
3889
        $query_param_type,
3890
        $original_query_param = null
3891
    ) {
3892
        if ($original_query_param === null) {
3893
            $original_query_param = $query_param;
3894
        }
3895
        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3896
        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3897
        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3898
        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3899
        //check to see if we have a field on this model
3900
        $this_model_fields = $this->field_settings(true);
3901
        if (array_key_exists($query_param, $this_model_fields)) {
3902
            if ($allow_fields) {
3903
                return;
3904
            }
3905
            throw new EE_Error(
3906
                sprintf(
3907
                    __(
3908
                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3909
                        "event_espresso"
3910
                    ),
3911
                    $query_param, get_class($this), $query_param_type, $original_query_param
3912
                )
3913
            );
3914
        }
3915
        //check if this is a special logic query param
3916
        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3917
            if ($allow_logic_query_params) {
3918
                return;
3919
            }
3920
            throw new EE_Error(
3921
                sprintf(
3922
                    __(
3923
                        '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',
3924
                        'event_espresso'
3925
                    ),
3926
                    implode('", "', $this->_logic_query_param_keys),
3927
                    $query_param,
3928
                    get_class($this),
3929
                    '<br />',
3930
                    "\t"
3931
                    . ' $passed_in_query_info = <pre>'
3932
                    . print_r($passed_in_query_info, true)
3933
                    . '</pre>'
3934
                    . "\n\t"
3935
                    . ' $query_param_type = '
3936
                    . $query_param_type
3937
                    . "\n\t"
3938
                    . ' $original_query_param = '
3939
                    . $original_query_param
3940
                )
3941
            );
3942
        }
3943
        //check if it's a custom selection
3944
        if (array_key_exists($query_param, $this->_custom_selections)) {
3945
            return;
3946
        }
3947
        //check if has a model name at the beginning
3948
        //and
3949
        //check if it's a field on a related model
3950
        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3951
            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3952
                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3953
                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3954
                if ($query_param === '') {
3955
                    //nothing left to $query_param
3956
                    //we should actually end in a field name, not a model like this!
3957
                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3958
                        "event_espresso"),
3959
                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3960
                }
3961
                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3962
                $related_model_obj->_extract_related_model_info_from_query_param(
3963
                    $query_param,
3964
                    $passed_in_query_info, $query_param_type, $original_query_param
3965
                );
3966
                return;
3967
            }
3968
            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...
3969
                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3970
                return;
3971
            }
3972
        }
3973
        //ok so $query_param didn't start with a model name
3974
        //and we previously confirmed it wasn't a logic query param or field on the current model
3975
        //it's wack, that's what it is
3976
        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",
3977
            "event_espresso"),
3978
            $query_param, get_class($this), $query_param_type, $original_query_param));
3979
    }
3980
3981
3982
3983
    /**
3984
     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3985
     * and store it on $passed_in_query_info
3986
     *
3987
     * @param string                      $model_name
3988
     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3989
     * @param string                      $original_query_param used to extract the relation chain between the queried
3990
     *                                                          model and $model_name. Eg, if we are querying Event,
3991
     *                                                          and are adding a join to 'Payment' with the original
3992
     *                                                          query param key
3993
     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3994
     *                                                          to extract 'Registration.Transaction.Payment', in case
3995
     *                                                          Payment wants to add default query params so that it
3996
     *                                                          will know what models to prepend onto its default query
3997
     *                                                          params or in case it wants to rename tables (in case
3998
     *                                                          there are multiple joins to the same table)
3999
     * @return void
4000
     * @throws EE_Error
4001
     */
4002
    private function _add_join_to_model(
4003
        $model_name,
4004
        EE_Model_Query_Info_Carrier $passed_in_query_info,
4005
        $original_query_param
4006
    ) {
4007
        $relation_obj = $this->related_settings_for($model_name);
4008
        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4009
        //check if the relation is HABTM, because then we're essentially doing two joins
4010
        //If so, join first to the JOIN table, and add its data types, and then continue as normal
4011
        if ($relation_obj instanceof EE_HABTM_Relation) {
4012
            $join_model_obj = $relation_obj->get_join_model();
4013
            //replace the model specified with the join model for this relation chain, whi
4014
            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4015
                $join_model_obj->get_this_model_name(), $model_relation_chain);
4016
            $passed_in_query_info->merge(
4017
                new EE_Model_Query_Info_Carrier(
4018
                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4019
                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4020
                )
4021
            );
4022
        }
4023
        //now just join to the other table pointed to by the relation object, and add its data types
4024
        $passed_in_query_info->merge(
4025
            new EE_Model_Query_Info_Carrier(
4026
                array($model_relation_chain => $model_name),
4027
                $relation_obj->get_join_statement($model_relation_chain)
4028
            )
4029
        );
4030
    }
4031
4032
4033
4034
    /**
4035
     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4036
     *
4037
     * @param array $where_params like EEM_Base::get_all
4038
     * @return string of SQL
4039
     * @throws EE_Error
4040
     */
4041
    private function _construct_where_clause($where_params)
4042
    {
4043
        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4044
        if ($SQL) {
4045
            return " WHERE " . $SQL;
4046
        }
4047
        return '';
4048
    }
4049
4050
4051
4052
    /**
4053
     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4054
     * and should be passed HAVING parameters, not WHERE parameters
4055
     *
4056
     * @param array $having_params
4057
     * @return string
4058
     * @throws EE_Error
4059
     */
4060
    private function _construct_having_clause($having_params)
4061
    {
4062
        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4063
        if ($SQL) {
4064
            return " HAVING " . $SQL;
4065
        }
4066
        return '';
4067
    }
4068
4069
4070
    /**
4071
     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4072
     * Event_Meta.meta_value = 'foo'))"
4073
     *
4074
     * @param array  $where_params see EEM_Base::get_all for documentation
4075
     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4076
     * @throws EE_Error
4077
     * @return string of SQL
4078
     */
4079
    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4080
    {
4081
        $where_clauses = array();
4082
        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4083
            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4084
            if (in_array($query_param, $this->_logic_query_param_keys)) {
4085
                switch ($query_param) {
4086
                    case 'not':
4087
                    case 'NOT':
4088
                        $where_clauses[] = "! ("
4089
                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4090
                                $glue)
4091
                                           . ")";
4092
                        break;
4093
                    case 'and':
4094
                    case 'AND':
4095
                        $where_clauses[] = " ("
4096
                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4097
                                ' AND ')
4098
                                           . ")";
4099
                        break;
4100
                    case 'or':
4101
                    case 'OR':
4102
                        $where_clauses[] = " ("
4103
                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4104
                                ' OR ')
4105
                                           . ")";
4106
                        break;
4107
                }
4108
            } else {
4109
                $field_obj = $this->_deduce_field_from_query_param($query_param);
4110
                //if it's not a normal field, maybe it's a custom selection?
4111
                if (! $field_obj) {
4112
                    if (isset($this->_custom_selections[$query_param][1])) {
4113
                        $field_obj = $this->_custom_selections[$query_param][1];
4114
                    } else {
4115
                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4116
                            "event_espresso"), $query_param));
4117
                    }
4118
                }
4119
                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4120
                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4121
            }
4122
        }
4123
        return $where_clauses ? implode($glue, $where_clauses) : '';
4124
    }
4125
4126
4127
4128
    /**
4129
     * Takes the input parameter and extract the table name (alias) and column name
4130
     *
4131
     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4132
     * @throws EE_Error
4133
     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4134
     */
4135
    private function _deduce_column_name_from_query_param($query_param)
4136
    {
4137
        $field = $this->_deduce_field_from_query_param($query_param);
4138
        if ($field) {
4139
            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4140
                $query_param);
4141
            return $table_alias_prefix . $field->get_qualified_column();
4142
        }
4143
        if (array_key_exists($query_param, $this->_custom_selections)) {
4144
            //maybe it's custom selection item?
4145
            //if so, just use it as the "column name"
4146
            return $query_param;
4147
        }
4148
        throw new EE_Error(
4149
            sprintf(
4150
                __(
4151
                    "%s is not a valid field on this model, nor a custom selection (%s)",
4152
                    "event_espresso"
4153
                ), $query_param, implode(",", $this->_custom_selections)
4154
            )
4155
        );
4156
    }
4157
4158
4159
4160
    /**
4161
     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4162
     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4163
     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4164
     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4165
     *
4166
     * @param string $condition_query_param_key
4167
     * @return string
4168
     */
4169 View Code Duplication
    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4170
    {
4171
        $pos_of_star = strpos($condition_query_param_key, '*');
4172
        if ($pos_of_star === false) {
4173
            return $condition_query_param_key;
4174
        }
4175
        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4176
        return $condition_query_param_sans_star;
4177
    }
4178
4179
4180
4181
    /**
4182
     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4183
     *
4184
     * @param                            mixed      array | string    $op_and_value
4185
     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4186
     * @throws EE_Error
4187
     * @return string
4188
     */
4189
    private function _construct_op_and_value($op_and_value, $field_obj)
4190
    {
4191
        if (is_array($op_and_value)) {
4192
            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4193
            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...
4194
                $php_array_like_string = array();
4195
                foreach ($op_and_value as $key => $value) {
4196
                    $php_array_like_string[] = "$key=>$value";
4197
                }
4198
                throw new EE_Error(
4199
                    sprintf(
4200
                        __(
4201
                            "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))",
4202
                            "event_espresso"
4203
                        ),
4204
                        implode(",", $php_array_like_string)
4205
                    )
4206
                );
4207
            }
4208
            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4209
        } else {
4210
            $operator = '=';
4211
            $value = $op_and_value;
4212
        }
4213
        //check to see if the value is actually another field
4214
        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4215
            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4216
        }
4217
        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4218
            //in this case, the value should be an array, or at least a comma-separated list
4219
            //it will need to handle a little differently
4220
            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4221
            //note: $cleaned_value has already been run through $wpdb->prepare()
4222
            return $operator . SP . $cleaned_value;
4223
        }
4224
        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4225
            //the value should be an array with count of two.
4226
            if (count($value) !== 2) {
4227
                throw new EE_Error(
4228
                    sprintf(
4229
                        __(
4230
                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4231
                            'event_espresso'
4232
                        ),
4233
                        "BETWEEN"
4234
                    )
4235
                );
4236
            }
4237
            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4238
            return $operator . SP . $cleaned_value;
4239
        }
4240 View Code Duplication
        if (in_array($operator, $this->valid_null_style_operators())) {
4241
            if ($value !== null) {
4242
                throw new EE_Error(
4243
                    sprintf(
4244
                        __(
4245
                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4246
                            "event_espresso"
4247
                        ),
4248
                        $value,
4249
                        $operator
4250
                    )
4251
                );
4252
            }
4253
            return $operator;
4254
        }
4255 View Code Duplication
        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4256
            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4257
            //remove other junk. So just treat it as a string.
4258
            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4259
        }
4260 View Code Duplication
        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4261
            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4262
        }
4263 View Code Duplication
        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4264
            throw new EE_Error(
4265
                sprintf(
4266
                    __(
4267
                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4268
                        'event_espresso'
4269
                    ),
4270
                    $operator,
4271
                    $operator
4272
                )
4273
            );
4274
        }
4275 View Code Duplication
        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4276
            throw new EE_Error(
4277
                sprintf(
4278
                    __(
4279
                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4280
                        'event_espresso'
4281
                    ),
4282
                    $operator,
4283
                    $operator
4284
                )
4285
            );
4286
        }
4287
        throw new EE_Error(
4288
            sprintf(
4289
                __(
4290
                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4291
                    "event_espresso"
4292
                ),
4293
                http_build_query($op_and_value)
4294
            )
4295
        );
4296
    }
4297
4298
4299
4300
    /**
4301
     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4302
     *
4303
     * @param array                      $values
4304
     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4305
     *                                              '%s'
4306
     * @return string
4307
     * @throws EE_Error
4308
     */
4309
    public function _construct_between_value($values, $field_obj)
4310
    {
4311
        $cleaned_values = array();
4312
        foreach ($values as $value) {
4313
            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4314
        }
4315
        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4316
    }
4317
4318
4319
4320
    /**
4321
     * Takes an array or a comma-separated list of $values and cleans them
4322
     * according to $data_type using $wpdb->prepare, and then makes the list a
4323
     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4324
     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4325
     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4326
     *
4327
     * @param mixed                      $values    array or comma-separated string
4328
     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4329
     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4330
     * @throws EE_Error
4331
     */
4332
    public function _construct_in_value($values, $field_obj)
4333
    {
4334
        //check if the value is a CSV list
4335
        if (is_string($values)) {
4336
            //in which case, turn it into an array
4337
            $values = explode(",", $values);
4338
        }
4339
        $cleaned_values = array();
4340
        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...
4341
            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4342
        }
4343
        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4344
        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4345
        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4346
        if (empty($cleaned_values)) {
4347
            $all_fields = $this->field_settings();
4348
            $a_field = array_shift($all_fields);
4349
            $main_table = $this->_get_main_table();
4350
            $cleaned_values[] = "SELECT "
4351
                                . $a_field->get_table_column()
4352
                                . " FROM "
4353
                                . $main_table->get_table_name()
4354
                                . " WHERE FALSE";
4355
        }
4356
        return "(" . implode(",", $cleaned_values) . ")";
4357
    }
4358
4359
4360
4361
    /**
4362
     * @param mixed                      $value
4363
     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4364
     * @throws EE_Error
4365
     * @return false|null|string
4366
     */
4367
    private function _wpdb_prepare_using_field($value, $field_obj)
4368
    {
4369
        /** @type WPDB $wpdb */
4370
        global $wpdb;
4371
        if ($field_obj instanceof EE_Model_Field_Base) {
4372
            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4373
                $this->_prepare_value_for_use_in_db($value, $field_obj));
4374
        } //$field_obj should really just be a data type
4375 View Code Duplication
        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4376
            throw new EE_Error(
4377
                sprintf(
4378
                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4379
                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4380
                )
4381
            );
4382
        }
4383
        return $wpdb->prepare($field_obj, $value);
4384
    }
4385
4386
4387
4388
    /**
4389
     * Takes the input parameter and finds the model field that it indicates.
4390
     *
4391
     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4392
     * @throws EE_Error
4393
     * @return EE_Model_Field_Base
4394
     */
4395
    protected function _deduce_field_from_query_param($query_param_name)
4396
    {
4397
        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4398
        //which will help us find the database table and column
4399
        $query_param_parts = explode(".", $query_param_name);
4400
        if (empty($query_param_parts)) {
4401
            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4402
                'event_espresso'), $query_param_name));
4403
        }
4404
        $number_of_parts = count($query_param_parts);
4405
        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4406
        if ($number_of_parts === 1) {
4407
            $field_name = $last_query_param_part;
4408
            $model_obj = $this;
4409
        } else {// $number_of_parts >= 2
4410
            //the last part is the column name, and there are only 2parts. therefore...
4411
            $field_name = $last_query_param_part;
4412
            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4413
        }
4414
        try {
4415
            return $model_obj->field_settings_for($field_name);
4416
        } catch (EE_Error $e) {
4417
            return null;
4418
        }
4419
    }
4420
4421
4422
4423
    /**
4424
     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4425
     * alias and column which corresponds to it
4426
     *
4427
     * @param string $field_name
4428
     * @throws EE_Error
4429
     * @return string
4430
     */
4431
    public function _get_qualified_column_for_field($field_name)
4432
    {
4433
        $all_fields = $this->field_settings();
4434
        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4435
        if ($field) {
4436
            return $field->get_qualified_column();
4437
        }
4438
        throw new EE_Error(
4439
            sprintf(
4440
                __(
4441
                    "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.",
4442
                    'event_espresso'
4443
                ), $field_name, get_class($this)
4444
            )
4445
        );
4446
    }
4447
4448
4449
4450
    /**
4451
     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4452
     * Example usage:
4453
     * EEM_Ticket::instance()->get_all_wpdb_results(
4454
     *      array(),
4455
     *      ARRAY_A,
4456
     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4457
     *  );
4458
     * is equivalent to
4459
     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4460
     * and
4461
     *  EEM_Event::instance()->get_all_wpdb_results(
4462
     *      array(
4463
     *          array(
4464
     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4465
     *          ),
4466
     *          ARRAY_A,
4467
     *          implode(
4468
     *              ', ',
4469
     *              array_merge(
4470
     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4471
     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4472
     *              )
4473
     *          )
4474
     *      )
4475
     *  );
4476
     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4477
     *
4478
     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4479
     *                                            and the one whose fields you are selecting for example: when querying
4480
     *                                            tickets model and selecting fields from the tickets model you would
4481
     *                                            leave this parameter empty, because no models are needed to join
4482
     *                                            between the queried model and the selected one. Likewise when
4483
     *                                            querying the datetime model and selecting fields from the tickets
4484
     *                                            model, it would also be left empty, because there is a direct
4485
     *                                            relation from datetimes to tickets, so no model is needed to join
4486
     *                                            them together. However, when querying from the event model and
4487
     *                                            selecting fields from the ticket model, you should provide the string
4488
     *                                            'Datetime', indicating that the event model must first join to the
4489
     *                                            datetime model in order to find its relation to ticket model.
4490
     *                                            Also, when querying from the venue model and selecting fields from
4491
     *                                            the ticket model, you should provide the string 'Event.Datetime',
4492
     *                                            indicating you need to join the venue model to the event model,
4493
     *                                            to the datetime model, in order to find its relation to the ticket model.
4494
     *                                            This string is used to deduce the prefix that gets added onto the
4495
     *                                            models' tables qualified columns
4496
     * @param bool   $return_string               if true, will return a string with qualified column names separated
4497
     *                                            by ', ' if false, will simply return a numerically indexed array of
4498
     *                                            qualified column names
4499
     * @return array|string
4500
     */
4501
    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4502
    {
4503
        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4504
        $qualified_columns = array();
4505
        foreach ($this->field_settings() as $field_name => $field) {
4506
            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4507
        }
4508
        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4509
    }
4510
4511
4512
4513
    /**
4514
     * constructs the select use on special limit joins
4515
     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4516
     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4517
     * (as that is typically where the limits would be set).
4518
     *
4519
     * @param  string       $table_alias The table the select is being built for
4520
     * @param  mixed|string $limit       The limit for this select
4521
     * @return string                The final select join element for the query.
4522
     */
4523
    public function _construct_limit_join_select($table_alias, $limit)
4524
    {
4525
        $SQL = '';
4526
        foreach ($this->_tables as $table_obj) {
4527
            if ($table_obj instanceof EE_Primary_Table) {
4528
                $SQL .= $table_alias === $table_obj->get_table_alias()
4529
                    ? $table_obj->get_select_join_limit($limit)
4530
                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4531
            } elseif ($table_obj instanceof EE_Secondary_Table) {
4532
                $SQL .= $table_alias === $table_obj->get_table_alias()
4533
                    ? $table_obj->get_select_join_limit_join($limit)
4534
                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4535
            }
4536
        }
4537
        return $SQL;
4538
    }
4539
4540
4541
4542
    /**
4543
     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4544
     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4545
     *
4546
     * @return string SQL
4547
     * @throws EE_Error
4548
     */
4549
    public function _construct_internal_join()
4550
    {
4551
        $SQL = $this->_get_main_table()->get_table_sql();
4552
        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4553
        return $SQL;
4554
    }
4555
4556
4557
4558
    /**
4559
     * Constructs the SQL for joining all the tables on this model.
4560
     * Normally $alias should be the primary table's alias, but in cases where
4561
     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4562
     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4563
     * alias, this will construct SQL like:
4564
     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4565
     * With $alias being a secondary table's alias, this will construct SQL like:
4566
     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4567
     *
4568
     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4569
     * @return string
4570
     */
4571
    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4572
    {
4573
        $SQL = '';
4574
        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4575
        foreach ($this->_tables as $table_obj) {
4576
            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4577
                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4578
                    //so we're joining to this table, meaning the table is already in
4579
                    //the FROM statement, BUT the primary table isn't. So we want
4580
                    //to add the inverse join sql
4581
                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4582
                } else {
4583
                    //just add a regular JOIN to this table from the primary table
4584
                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4585
                }
4586
            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4587
        }
4588
        return $SQL;
4589
    }
4590
4591
4592
4593
    /**
4594
     * Gets an array for storing all the data types on the next-to-be-executed-query.
4595
     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4596
     * their data type (eg, '%s', '%d', etc)
4597
     *
4598
     * @return array
4599
     */
4600
    public function _get_data_types()
4601
    {
4602
        $data_types = array();
4603
        foreach ($this->field_settings() as $field_obj) {
4604
            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4605
            /** @var $field_obj EE_Model_Field_Base */
4606
            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4607
        }
4608
        return $data_types;
4609
    }
4610
4611
4612
4613
    /**
4614
     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4615
     *
4616
     * @param string $model_name
4617
     * @throws EE_Error
4618
     * @return EEM_Base
4619
     */
4620
    public function get_related_model_obj($model_name)
4621
    {
4622
        $model_classname = "EEM_" . $model_name;
4623
        if (! class_exists($model_classname)) {
4624
            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",
4625
                'event_espresso'), $model_name, $model_classname));
4626
        }
4627
        return call_user_func($model_classname . "::instance");
4628
    }
4629
4630
4631
4632
    /**
4633
     * Returns the array of EE_ModelRelations for this model.
4634
     *
4635
     * @return EE_Model_Relation_Base[]
4636
     */
4637
    public function relation_settings()
4638
    {
4639
        return $this->_model_relations;
4640
    }
4641
4642
4643
4644
    /**
4645
     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4646
     * because without THOSE models, this model probably doesn't have much purpose.
4647
     * (Eg, without an event, datetimes have little purpose.)
4648
     *
4649
     * @return EE_Belongs_To_Relation[]
4650
     */
4651
    public function belongs_to_relations()
4652
    {
4653
        $belongs_to_relations = array();
4654
        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4655
            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4656
                $belongs_to_relations[$model_name] = $relation_obj;
4657
            }
4658
        }
4659
        return $belongs_to_relations;
4660
    }
4661
4662
4663
4664
    /**
4665
     * Returns the specified EE_Model_Relation, or throws an exception
4666
     *
4667
     * @param string $relation_name name of relation, key in $this->_relatedModels
4668
     * @throws EE_Error
4669
     * @return EE_Model_Relation_Base
4670
     */
4671
    public function related_settings_for($relation_name)
4672
    {
4673
        $relatedModels = $this->relation_settings();
4674 View Code Duplication
        if (! array_key_exists($relation_name, $relatedModels)) {
4675
            throw new EE_Error(
4676
                sprintf(
4677
                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4678
                        'event_espresso'),
4679
                    $relation_name,
4680
                    $this->_get_class_name(),
4681
                    implode(', ', array_keys($relatedModels))
4682
                )
4683
            );
4684
        }
4685
        return $relatedModels[$relation_name];
4686
    }
4687
4688
4689
4690
    /**
4691
     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4692
     * fields
4693
     *
4694
     * @param string $fieldName
4695
     * @param boolean $include_db_only_fields
4696
     * @throws EE_Error
4697
     * @return EE_Model_Field_Base
4698
     */
4699 View Code Duplication
    public function field_settings_for($fieldName, $include_db_only_fields = true)
4700
    {
4701
        $fieldSettings = $this->field_settings($include_db_only_fields);
4702
        if (! array_key_exists($fieldName, $fieldSettings)) {
4703
            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4704
                get_class($this)));
4705
        }
4706
        return $fieldSettings[$fieldName];
4707
    }
4708
4709
4710
4711
    /**
4712
     * Checks if this field exists on this model
4713
     *
4714
     * @param string $fieldName a key in the model's _field_settings array
4715
     * @return boolean
4716
     */
4717
    public function has_field($fieldName)
4718
    {
4719
        $fieldSettings = $this->field_settings(true);
4720
        if (isset($fieldSettings[$fieldName])) {
4721
            return true;
4722
        }
4723
        return false;
4724
    }
4725
4726
4727
4728
    /**
4729
     * Returns whether or not this model has a relation to the specified model
4730
     *
4731
     * @param string $relation_name possibly one of the keys in the relation_settings array
4732
     * @return boolean
4733
     */
4734
    public function has_relation($relation_name)
4735
    {
4736
        $relations = $this->relation_settings();
4737
        if (isset($relations[$relation_name])) {
4738
            return true;
4739
        }
4740
        return false;
4741
    }
4742
4743
4744
4745
    /**
4746
     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4747
     * Eg, on EE_Answer that would be ANS_ID field object
4748
     *
4749
     * @param $field_obj
4750
     * @return boolean
4751
     */
4752
    public function is_primary_key_field($field_obj)
4753
    {
4754
        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4755
    }
4756
4757
4758
4759
    /**
4760
     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4761
     * Eg, on EE_Answer that would be ANS_ID field object
4762
     *
4763
     * @return EE_Model_Field_Base
4764
     * @throws EE_Error
4765
     */
4766
    public function get_primary_key_field()
4767
    {
4768
        if ($this->_primary_key_field === null) {
4769
            foreach ($this->field_settings(true) as $field_obj) {
4770
                if ($this->is_primary_key_field($field_obj)) {
4771
                    $this->_primary_key_field = $field_obj;
4772
                    break;
4773
                }
4774
            }
4775
            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4776
                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4777
                    get_class($this)));
4778
            }
4779
        }
4780
        return $this->_primary_key_field;
4781
    }
4782
4783
4784
4785
    /**
4786
     * Returns whether or not not there is a primary key on this model.
4787
     * Internally does some caching.
4788
     *
4789
     * @return boolean
4790
     */
4791
    public function has_primary_key_field()
4792
    {
4793
        if ($this->_has_primary_key_field === null) {
4794
            try {
4795
                $this->get_primary_key_field();
4796
                $this->_has_primary_key_field = true;
4797
            } catch (EE_Error $e) {
4798
                $this->_has_primary_key_field = false;
4799
            }
4800
        }
4801
        return $this->_has_primary_key_field;
4802
    }
4803
4804
4805
4806
    /**
4807
     * Finds the first field of type $field_class_name.
4808
     *
4809
     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4810
     *                                 EE_Foreign_Key_Field, etc
4811
     * @return EE_Model_Field_Base or null if none is found
4812
     */
4813
    public function get_a_field_of_type($field_class_name)
4814
    {
4815
        foreach ($this->field_settings() as $field) {
4816
            if ($field instanceof $field_class_name) {
4817
                return $field;
4818
            }
4819
        }
4820
        return null;
4821
    }
4822
4823
4824
4825
    /**
4826
     * Gets a foreign key field pointing to model.
4827
     *
4828
     * @param string $model_name eg Event, Registration, not EEM_Event
4829
     * @return EE_Foreign_Key_Field_Base
4830
     * @throws EE_Error
4831
     */
4832
    public function get_foreign_key_to($model_name)
4833
    {
4834
        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4835
            foreach ($this->field_settings() as $field) {
4836
                if (
4837
                    $field instanceof EE_Foreign_Key_Field_Base
4838
                    && in_array($model_name, $field->get_model_names_pointed_to())
4839
                ) {
4840
                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4841
                    break;
4842
                }
4843
            }
4844 View Code Duplication
            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4845
                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4846
                    'event_espresso'), $model_name, get_class($this)));
4847
            }
4848
        }
4849
        return $this->_cache_foreign_key_to_fields[$model_name];
4850
    }
4851
4852
4853
4854
    /**
4855
     * Gets the table name (including $wpdb->prefix) for the table alias
4856
     *
4857
     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4858
     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4859
     *                            Either one works
4860
     * @return string
4861
     */
4862
    public function get_table_for_alias($table_alias)
4863
    {
4864
        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4865
        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4866
    }
4867
4868
4869
4870
    /**
4871
     * Returns a flat array of all field son this model, instead of organizing them
4872
     * by table_alias as they are in the constructor.
4873
     *
4874
     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4875
     * @return EE_Model_Field_Base[] where the keys are the field's name
4876
     */
4877
    public function field_settings($include_db_only_fields = false)
4878
    {
4879
        if ($include_db_only_fields) {
4880
            if ($this->_cached_fields === null) {
4881
                $this->_cached_fields = array();
4882
                foreach ($this->_fields as $fields_corresponding_to_table) {
4883
                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4884
                        $this->_cached_fields[$field_name] = $field_obj;
4885
                    }
4886
                }
4887
            }
4888
            return $this->_cached_fields;
4889
        }
4890
        if ($this->_cached_fields_non_db_only === null) {
4891
            $this->_cached_fields_non_db_only = array();
4892
            foreach ($this->_fields as $fields_corresponding_to_table) {
4893
                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4894
                    /** @var $field_obj EE_Model_Field_Base */
4895
                    if (! $field_obj->is_db_only_field()) {
4896
                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4897
                    }
4898
                }
4899
            }
4900
        }
4901
        return $this->_cached_fields_non_db_only;
4902
    }
4903
4904
4905
4906
    /**
4907
     *        cycle though array of attendees and create objects out of each item
4908
     *
4909
     * @access        private
4910
     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4911
     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4912
     *                           numerically indexed)
4913
     * @throws EE_Error
4914
     */
4915
    protected function _create_objects($rows = array())
4916
    {
4917
        $array_of_objects = array();
4918
        if (empty($rows)) {
4919
            return array();
4920
        }
4921
        $count_if_model_has_no_primary_key = 0;
4922
        $has_primary_key = $this->has_primary_key_field();
4923
        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4924
        foreach ((array)$rows as $row) {
4925
            if (empty($row)) {
4926
                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4927
                return array();
4928
            }
4929
            //check if we've already set this object in the results array,
4930
            //in which case there's no need to process it further (again)
4931
            if ($has_primary_key) {
4932
                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4933
                    $row,
4934
                    $primary_key_field->get_qualified_column(),
4935
                    $primary_key_field->get_table_column()
4936
                );
4937
                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4938
                    continue;
4939
                }
4940
            }
4941
            $classInstance = $this->instantiate_class_from_array_or_object($row);
4942 View Code Duplication
            if (! $classInstance) {
4943
                throw new EE_Error(
4944
                    sprintf(
4945
                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4946
                        $this->get_this_model_name(),
4947
                        http_build_query($row)
4948
                    )
4949
                );
4950
            }
4951
            //set the timezone on the instantiated objects
4952
            $classInstance->set_timezone($this->_timezone);
4953
            //make sure if there is any timezone setting present that we set the timezone for the object
4954
            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4955
            $array_of_objects[$key] = $classInstance;
4956
            //also, for all the relations of type BelongsTo, see if we can cache
4957
            //those related models
4958
            //(we could do this for other relations too, but if there are conditions
4959
            //that filtered out some fo the results, then we'd be caching an incomplete set
4960
            //so it requires a little more thought than just caching them immediately...)
4961
            foreach ($this->_model_relations as $modelName => $relation_obj) {
4962
                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4963
                    //check if this model's INFO is present. If so, cache it on the model
4964
                    $other_model = $relation_obj->get_other_model();
4965
                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4966
                    //if we managed to make a model object from the results, cache it on the main model object
4967
                    if ($other_model_obj_maybe) {
4968
                        //set timezone on these other model objects if they are present
4969
                        $other_model_obj_maybe->set_timezone($this->_timezone);
4970
                        $classInstance->cache($modelName, $other_model_obj_maybe);
4971
                    }
4972
                }
4973
            }
4974
        }
4975
        return $array_of_objects;
4976
    }
4977
4978
4979
4980
    /**
4981
     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4982
     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4983
     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4984
     * object (as set in the model_field!).
4985
     *
4986
     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4987
     */
4988
    public function create_default_object()
4989
    {
4990
        $this_model_fields_and_values = array();
4991
        //setup the row using default values;
4992
        foreach ($this->field_settings() as $field_name => $field_obj) {
4993
            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4994
        }
4995
        $className = $this->_get_class_name();
4996
        $classInstance = EE_Registry::instance()
4997
                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4998
        return $classInstance;
4999
    }
5000
5001
5002
5003
    /**
5004
     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5005
     *                             or an stdClass where each property is the name of a column,
5006
     * @return EE_Base_Class
5007
     * @throws EE_Error
5008
     */
5009
    public function instantiate_class_from_array_or_object($cols_n_values)
5010
    {
5011
        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5012
            $cols_n_values = get_object_vars($cols_n_values);
5013
        }
5014
        $primary_key = null;
5015
        //make sure the array only has keys that are fields/columns on this model
5016
        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5017
        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5018
            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5019
        }
5020
        $className = $this->_get_class_name();
5021
        //check we actually found results that we can use to build our model object
5022
        //if not, return null
5023
        if ($this->has_primary_key_field()) {
5024
            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5025
                return null;
5026
            }
5027
        } else if ($this->unique_indexes()) {
5028
            $first_column = reset($this_model_fields_n_values);
5029
            if (empty($first_column)) {
5030
                return null;
5031
            }
5032
        }
5033
        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5034
        if ($primary_key) {
5035
            $classInstance = $this->get_from_entity_map($primary_key);
5036
            if (! $classInstance) {
5037
                $classInstance = EE_Registry::instance()
5038
                                            ->load_class($className,
5039
                                                array($this_model_fields_n_values, $this->_timezone), true, false);
5040
                // add this new object to the entity map
5041
                $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...
5042
            }
5043
        } else {
5044
            $classInstance = EE_Registry::instance()
5045
                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5046
                                            true, false);
5047
        }
5048
        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
5049
        $this->set_timezone($classInstance->get_timezone());
5050
        return $classInstance;
5051
    }
5052
5053
5054
5055
    /**
5056
     * Gets the model object from the  entity map if it exists
5057
     *
5058
     * @param int|string $id the ID of the model object
5059
     * @return EE_Base_Class
5060
     */
5061
    public function get_from_entity_map($id)
5062
    {
5063
        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5064
            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5065
    }
5066
5067
5068
5069
    /**
5070
     * add_to_entity_map
5071
     * Adds the object to the model's entity mappings
5072
     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5073
     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5074
     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5075
     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5076
     *        then this method should be called immediately after the update query
5077
     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5078
     * so on multisite, the entity map is specific to the query being done for a specific site.
5079
     *
5080
     * @param    EE_Base_Class $object
5081
     * @throws EE_Error
5082
     * @return \EE_Base_Class
5083
     */
5084
    public function add_to_entity_map(EE_Base_Class $object)
5085
    {
5086
        $className = $this->_get_class_name();
5087
        if (! $object instanceof $className) {
5088
            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5089
                is_object($object) ? get_class($object) : $object, $className));
5090
        }
5091
        /** @var $object EE_Base_Class */
5092
        if (! $object->ID()) {
5093
            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5094
                "event_espresso"), get_class($this)));
5095
        }
5096
        // double check it's not already there
5097
        $classInstance = $this->get_from_entity_map($object->ID());
5098
        if ($classInstance) {
5099
            return $classInstance;
5100
        }
5101
        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5102
        return $object;
5103
    }
5104
5105
5106
5107
    /**
5108
     * if a valid identifier is provided, then that entity is unset from the entity map,
5109
     * if no identifier is provided, then the entire entity map is emptied
5110
     *
5111
     * @param int|string $id the ID of the model object
5112
     * @return boolean
5113
     */
5114
    public function clear_entity_map($id = null)
5115
    {
5116
        if (empty($id)) {
5117
            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5118
            return true;
5119
        }
5120 View Code Duplication
        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5121
            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5122
            return true;
5123
        }
5124
        return false;
5125
    }
5126
5127
5128
5129
    /**
5130
     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5131
     * Given an array where keys are column (or column alias) names and values,
5132
     * returns an array of their corresponding field names and database values
5133
     *
5134
     * @param array $cols_n_values
5135
     * @return array
5136
     */
5137
    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5138
    {
5139
        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5140
    }
5141
5142
5143
5144
    /**
5145
     * _deduce_fields_n_values_from_cols_n_values
5146
     * Given an array where keys are column (or column alias) names and values,
5147
     * returns an array of their corresponding field names and database values
5148
     *
5149
     * @param string $cols_n_values
5150
     * @return array
5151
     */
5152
    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5153
    {
5154
        $this_model_fields_n_values = array();
5155
        foreach ($this->get_tables() as $table_alias => $table_obj) {
5156
            $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...
5157
                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5158
            //there is a primary key on this table and its not set. Use defaults for all its columns
5159
            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5160
                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5161
                    if (! $field_obj->is_db_only_field()) {
5162
                        //prepare field as if its coming from db
5163
                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5164
                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5165
                    }
5166
                }
5167
            } else {
5168
                //the table's rows existed. Use their values
5169
                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5170
                    if (! $field_obj->is_db_only_field()) {
5171
                        $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...
5172
                            $cols_n_values, $field_obj->get_qualified_column(),
5173
                            $field_obj->get_table_column()
5174
                        );
5175
                    }
5176
                }
5177
            }
5178
        }
5179
        return $this_model_fields_n_values;
5180
    }
5181
5182
5183
5184
    /**
5185
     * @param $cols_n_values
5186
     * @param $qualified_column
5187
     * @param $regular_column
5188
     * @return null
5189
     */
5190
    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5191
    {
5192
        $value = null;
5193
        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5194
        //does the field on the model relate to this column retrieved from the db?
5195
        //or is it a db-only field? (not relating to the model)
5196
        if (isset($cols_n_values[$qualified_column])) {
5197
            $value = $cols_n_values[$qualified_column];
5198
        } elseif (isset($cols_n_values[$regular_column])) {
5199
            $value = $cols_n_values[$regular_column];
5200
        }
5201
        return $value;
5202
    }
5203
5204
5205
5206
    /**
5207
     * refresh_entity_map_from_db
5208
     * Makes sure the model object in the entity map at $id assumes the values
5209
     * of the database (opposite of EE_base_Class::save())
5210
     *
5211
     * @param int|string $id
5212
     * @return EE_Base_Class
5213
     * @throws EE_Error
5214
     */
5215
    public function refresh_entity_map_from_db($id)
5216
    {
5217
        $obj_in_map = $this->get_from_entity_map($id);
5218
        if ($obj_in_map) {
5219
            $wpdb_results = $this->_get_all_wpdb_results(
5220
                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5221
            );
5222
            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...
5223
                $one_row = reset($wpdb_results);
5224
                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5225
                    $obj_in_map->set_from_db($field_name, $db_value);
5226
                }
5227
                //clear the cache of related model objects
5228
                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5229
                    $obj_in_map->clear_cache($relation_name, null, true);
5230
                }
5231
            }
5232
            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5233
            return $obj_in_map;
5234
        }
5235
        return $this->get_one_by_ID($id);
5236
    }
5237
5238
5239
5240
    /**
5241
     * refresh_entity_map_with
5242
     * Leaves the entry in the entity map alone, but updates it to match the provided
5243
     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5244
     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5245
     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5246
     *
5247
     * @param int|string    $id
5248
     * @param EE_Base_Class $replacing_model_obj
5249
     * @return \EE_Base_Class
5250
     * @throws EE_Error
5251
     */
5252
    public function refresh_entity_map_with($id, $replacing_model_obj)
5253
    {
5254
        $obj_in_map = $this->get_from_entity_map($id);
5255
        if ($obj_in_map) {
5256
            if ($replacing_model_obj instanceof EE_Base_Class) {
5257
                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5258
                    $obj_in_map->set($field_name, $value);
5259
                }
5260
                //make the model object in the entity map's cache match the $replacing_model_obj
5261
                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5262
                    $obj_in_map->clear_cache($relation_name, null, true);
5263
                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5264
                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5265
                    }
5266
                }
5267
            }
5268
            return $obj_in_map;
5269
        }
5270
        $this->add_to_entity_map($replacing_model_obj);
5271
        return $replacing_model_obj;
5272
    }
5273
5274
5275
5276
    /**
5277
     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5278
     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5279
     * require_once($this->_getClassName().".class.php");
5280
     *
5281
     * @return string
5282
     */
5283
    private function _get_class_name()
5284
    {
5285
        return "EE_" . $this->get_this_model_name();
5286
    }
5287
5288
5289
5290
    /**
5291
     * Get the name of the items this model represents, for the quantity specified. Eg,
5292
     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5293
     * it would be 'Events'.
5294
     *
5295
     * @param int $quantity
5296
     * @return string
5297
     */
5298
    public function item_name($quantity = 1)
5299
    {
5300
        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5301
    }
5302
5303
5304
5305
    /**
5306
     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5307
     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5308
     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5309
     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5310
     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5311
     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5312
     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5313
     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5314
     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5315
     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5316
     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5317
     *        return $previousReturnValue.$returnString;
5318
     * }
5319
     * require('EEM_Answer.model.php');
5320
     * $answer=EEM_Answer::instance();
5321
     * echo $answer->my_callback('monkeys',100);
5322
     * //will output "you called my_callback! and passed args:monkeys,100"
5323
     *
5324
     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5325
     * @param array  $args       array of original arguments passed to the function
5326
     * @throws EE_Error
5327
     * @return mixed whatever the plugin which calls add_filter decides
5328
     */
5329 View Code Duplication
    public function __call($methodName, $args)
5330
    {
5331
        $className = get_class($this);
5332
        $tagName = "FHEE__{$className}__{$methodName}";
5333
        if (! has_filter($tagName)) {
5334
            throw new EE_Error(
5335
                sprintf(
5336
                    __('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 );',
5337
                        'event_espresso'),
5338
                    $methodName,
5339
                    $className,
5340
                    $tagName,
5341
                    '<br />'
5342
                )
5343
            );
5344
        }
5345
        return apply_filters($tagName, null, $this, $args);
5346
    }
5347
5348
5349
5350
    /**
5351
     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5352
     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5353
     *
5354
     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5355
     *                                                       the EE_Base_Class object that corresponds to this Model,
5356
     *                                                       the object's class name
5357
     *                                                       or object's ID
5358
     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5359
     *                                                       exists in the database. If it does not, we add it
5360
     * @throws EE_Error
5361
     * @return EE_Base_Class
5362
     */
5363
    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5364
    {
5365
        $className = $this->_get_class_name();
5366
        if ($base_class_obj_or_id instanceof $className) {
5367
            $model_object = $base_class_obj_or_id;
5368
        } else {
5369
            $primary_key_field = $this->get_primary_key_field();
5370
            if (
5371
                $primary_key_field instanceof EE_Primary_Key_Int_Field
5372
                && (
5373
                    is_int($base_class_obj_or_id)
5374
                    || is_string($base_class_obj_or_id)
5375
                )
5376
            ) {
5377
                // assume it's an ID.
5378
                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5379
                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5380
            } else if (
5381
                $primary_key_field instanceof EE_Primary_Key_String_Field
5382
                && is_string($base_class_obj_or_id)
5383
            ) {
5384
                // assume its a string representation of the object
5385
                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5386
            } else {
5387
                throw new EE_Error(
5388
                    sprintf(
5389
                        __(
5390
                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5391
                            'event_espresso'
5392
                        ),
5393
                        $base_class_obj_or_id,
5394
                        $this->_get_class_name(),
5395
                        print_r($base_class_obj_or_id, true)
5396
                    )
5397
                );
5398
            }
5399
        }
5400
        if ($ensure_is_in_db && $model_object->ID() !== null) {
5401
            $model_object->save();
5402
        }
5403
        return $model_object;
5404
    }
5405
5406
5407
5408
    /**
5409
     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5410
     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5411
     * returns it ID.
5412
     *
5413
     * @param EE_Base_Class|int|string $base_class_obj_or_id
5414
     * @return int|string depending on the type of this model object's ID
5415
     * @throws EE_Error
5416
     */
5417
    public function ensure_is_ID($base_class_obj_or_id)
5418
    {
5419
        $className = $this->_get_class_name();
5420
        if ($base_class_obj_or_id instanceof $className) {
5421
            /** @var $base_class_obj_or_id EE_Base_Class */
5422
            $id = $base_class_obj_or_id->ID();
5423
        } elseif (is_int($base_class_obj_or_id)) {
5424
            //assume it's an ID
5425
            $id = $base_class_obj_or_id;
5426
        } elseif (is_string($base_class_obj_or_id)) {
5427
            //assume its a string representation of the object
5428
            $id = $base_class_obj_or_id;
5429
        } else {
5430
            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5431
                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5432
                print_r($base_class_obj_or_id, true)));
5433
        }
5434
        return $id;
5435
    }
5436
5437
5438
5439
    /**
5440
     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5441
     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5442
     * been sanitized and converted into the appropriate domain.
5443
     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5444
     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5445
     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5446
     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5447
     * $EVT = EEM_Event::instance(); $old_setting =
5448
     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5449
     * $EVT->assume_values_already_prepared_by_model_object(true);
5450
     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5451
     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5452
     *
5453
     * @param int $values_already_prepared like one of the constants on EEM_Base
5454
     * @return void
5455
     */
5456
    public function assume_values_already_prepared_by_model_object(
5457
        $values_already_prepared = self::not_prepared_by_model_object
5458
    ) {
5459
        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5460
    }
5461
5462
5463
5464
    /**
5465
     * Read comments for assume_values_already_prepared_by_model_object()
5466
     *
5467
     * @return int
5468
     */
5469
    public function get_assumption_concerning_values_already_prepared_by_model_object()
5470
    {
5471
        return $this->_values_already_prepared_by_model_object;
5472
    }
5473
5474
5475
5476
    /**
5477
     * Gets all the indexes on this model
5478
     *
5479
     * @return EE_Index[]
5480
     */
5481
    public function indexes()
5482
    {
5483
        return $this->_indexes;
5484
    }
5485
5486
5487
5488
    /**
5489
     * Gets all the Unique Indexes on this model
5490
     *
5491
     * @return EE_Unique_Index[]
5492
     */
5493
    public function unique_indexes()
5494
    {
5495
        $unique_indexes = array();
5496
        foreach ($this->_indexes as $name => $index) {
5497
            if ($index instanceof EE_Unique_Index) {
5498
                $unique_indexes [$name] = $index;
5499
            }
5500
        }
5501
        return $unique_indexes;
5502
    }
5503
5504
5505
5506
    /**
5507
     * Gets all the fields which, when combined, make the primary key.
5508
     * This is usually just an array with 1 element (the primary key), but in cases
5509
     * where there is no primary key, it's a combination of fields as defined
5510
     * on a primary index
5511
     *
5512
     * @return EE_Model_Field_Base[] indexed by the field's name
5513
     * @throws EE_Error
5514
     */
5515
    public function get_combined_primary_key_fields()
5516
    {
5517
        foreach ($this->indexes() as $index) {
5518
            if ($index instanceof EE_Primary_Key_Index) {
5519
                return $index->fields();
5520
            }
5521
        }
5522
        return array($this->primary_key_name() => $this->get_primary_key_field());
5523
    }
5524
5525
5526
5527
    /**
5528
     * Used to build a primary key string (when the model has no primary key),
5529
     * which can be used a unique string to identify this model object.
5530
     *
5531
     * @param array $cols_n_values keys are field names, values are their values
5532
     * @return string
5533
     * @throws EE_Error
5534
     */
5535
    public function get_index_primary_key_string($cols_n_values)
5536
    {
5537
        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5538
            $this->get_combined_primary_key_fields());
5539
        return http_build_query($cols_n_values_for_primary_key_index);
5540
    }
5541
5542
5543
5544
    /**
5545
     * Gets the field values from the primary key string
5546
     *
5547
     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5548
     * @param string $index_primary_key_string
5549
     * @return null|array
5550
     * @throws EE_Error
5551
     */
5552
    public function parse_index_primary_key_string($index_primary_key_string)
5553
    {
5554
        $key_fields = $this->get_combined_primary_key_fields();
5555
        //check all of them are in the $id
5556
        $key_vals_in_combined_pk = array();
5557
        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5558
        foreach ($key_fields as $key_field_name => $field_obj) {
5559
            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5560
                return null;
5561
            }
5562
        }
5563
        return $key_vals_in_combined_pk;
5564
    }
5565
5566
5567
5568
    /**
5569
     * verifies that an array of key-value pairs for model fields has a key
5570
     * for each field comprising the primary key index
5571
     *
5572
     * @param array $key_vals
5573
     * @return boolean
5574
     * @throws EE_Error
5575
     */
5576
    public function has_all_combined_primary_key_fields($key_vals)
5577
    {
5578
        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5579
        foreach ($keys_it_should_have as $key) {
5580
            if (! isset($key_vals[$key])) {
5581
                return false;
5582
            }
5583
        }
5584
        return true;
5585
    }
5586
5587
5588
5589
    /**
5590
     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5591
     * We consider something to be a copy if all the attributes match (except the ID, of course).
5592
     *
5593
     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5594
     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5595
     * @throws EE_Error
5596
     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5597
     *                                                              indexed)
5598
     */
5599
    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5600
    {
5601 View Code Duplication
        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5602
            $attributes_array = $model_object_or_attributes_array->model_field_array();
5603
        } elseif (is_array($model_object_or_attributes_array)) {
5604
            $attributes_array = $model_object_or_attributes_array;
5605
        } else {
5606
            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",
5607
                "event_espresso"), $model_object_or_attributes_array));
5608
        }
5609
        //even copies obviously won't have the same ID, so remove the primary key
5610
        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5611
        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5612
            unset($attributes_array[$this->primary_key_name()]);
5613
        }
5614
        if (isset($query_params[0])) {
5615
            $query_params[0] = array_merge($attributes_array, $query_params);
5616
        } else {
5617
            $query_params[0] = $attributes_array;
5618
        }
5619
        return $this->get_all($query_params);
5620
    }
5621
5622
5623
5624
    /**
5625
     * Gets the first copy we find. See get_all_copies for more details
5626
     *
5627
     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5628
     * @param array $query_params
5629
     * @return EE_Base_Class
5630
     * @throws EE_Error
5631
     */
5632 View Code Duplication
    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5633
    {
5634
        if (! is_array($query_params)) {
5635
            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5636
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5637
                    gettype($query_params)), '4.6.0');
5638
            $query_params = array();
5639
        }
5640
        $query_params['limit'] = 1;
5641
        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5642
        if (is_array($copies)) {
5643
            return array_shift($copies);
5644
        }
5645
        return null;
5646
    }
5647
5648
5649
5650
    /**
5651
     * Updates the item with the specified id. Ignores default query parameters because
5652
     * we have specified the ID, and its assumed we KNOW what we're doing
5653
     *
5654
     * @param array      $fields_n_values keys are field names, values are their new values
5655
     * @param int|string $id              the value of the primary key to update
5656
     * @return int number of rows updated
5657
     * @throws EE_Error
5658
     */
5659
    public function update_by_ID($fields_n_values, $id)
5660
    {
5661
        $query_params = array(
5662
            0                          => array($this->get_primary_key_field()->get_name() => $id),
5663
            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5664
        );
5665
        return $this->update($fields_n_values, $query_params);
5666
    }
5667
5668
5669
5670
    /**
5671
     * Changes an operator which was supplied to the models into one usable in SQL
5672
     *
5673
     * @param string $operator_supplied
5674
     * @return string an operator which can be used in SQL
5675
     * @throws EE_Error
5676
     */
5677
    private function _prepare_operator_for_sql($operator_supplied)
5678
    {
5679
        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5680
            : null;
5681
        if ($sql_operator) {
5682
            return $sql_operator;
5683
        }
5684
        throw new EE_Error(
5685
            sprintf(
5686
                __(
5687
                    "The operator '%s' is not in the list of valid operators: %s",
5688
                    "event_espresso"
5689
                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5690
            )
5691
        );
5692
    }
5693
5694
5695
5696
    /**
5697
     * Gets the valid operators
5698
     * @return array keys are accepted strings, values are the SQL they are converted to
5699
     */
5700
    public function valid_operators(){
5701
        return $this->_valid_operators;
5702
    }
5703
5704
5705
5706
    /**
5707
     * Gets the between-style operators (take 2 arguments).
5708
     * @return array keys are accepted strings, values are the SQL they are converted to
5709
     */
5710
    public function valid_between_style_operators()
5711
    {
5712
        return array_intersect(
5713
            $this->valid_operators(),
5714
            $this->_between_style_operators
5715
        );
5716
    }
5717
5718
    /**
5719
     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5720
     * @return array keys are accepted strings, values are the SQL they are converted to
5721
     */
5722
    public function valid_like_style_operators()
5723
    {
5724
        return array_intersect(
5725
            $this->valid_operators(),
5726
            $this->_like_style_operators
5727
        );
5728
    }
5729
5730
    /**
5731
     * Gets the "in"-style operators
5732
     * @return array keys are accepted strings, values are the SQL they are converted to
5733
     */
5734
    public function valid_in_style_operators()
5735
    {
5736
        return array_intersect(
5737
            $this->valid_operators(),
5738
            $this->_in_style_operators
5739
        );
5740
    }
5741
5742
    /**
5743
     * Gets the "null"-style operators (accept no arguments)
5744
     * @return array keys are accepted strings, values are the SQL they are converted to
5745
     */
5746
    public function valid_null_style_operators()
5747
    {
5748
        return array_intersect(
5749
            $this->valid_operators(),
5750
            $this->_null_style_operators
5751
        );
5752
    }
5753
5754
    /**
5755
     * Gets an array where keys are the primary keys and values are their 'names'
5756
     * (as determined by the model object's name() function, which is often overridden)
5757
     *
5758
     * @param array $query_params like get_all's
5759
     * @return string[]
5760
     * @throws EE_Error
5761
     */
5762
    public function get_all_names($query_params = array())
5763
    {
5764
        $objs = $this->get_all($query_params);
5765
        $names = array();
5766
        foreach ($objs as $obj) {
5767
            $names[$obj->ID()] = $obj->name();
5768
        }
5769
        return $names;
5770
    }
5771
5772
5773
5774
    /**
5775
     * Gets an array of primary keys from the model objects. If you acquired the model objects
5776
     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5777
     * this is duplicated effort and reduces efficiency) you would be better to use
5778
     * array_keys() on $model_objects.
5779
     *
5780
     * @param \EE_Base_Class[] $model_objects
5781
     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5782
     *                                               in the returned array
5783
     * @return array
5784
     * @throws EE_Error
5785
     */
5786
    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5787
    {
5788
        if (! $this->has_primary_key_field()) {
5789
            if (WP_DEBUG) {
5790
                EE_Error::add_error(
5791
                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5792
                    __FILE__,
5793
                    __FUNCTION__,
5794
                    __LINE__
5795
                );
5796
            }
5797
        }
5798
        $IDs = array();
5799
        foreach ($model_objects as $model_object) {
5800
            $id = $model_object->ID();
5801
            if (! $id) {
5802
                if ($filter_out_empty_ids) {
5803
                    continue;
5804
                }
5805
                if (WP_DEBUG) {
5806
                    EE_Error::add_error(
5807
                        __(
5808
                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5809
                            'event_espresso'
5810
                        ),
5811
                        __FILE__,
5812
                        __FUNCTION__,
5813
                        __LINE__
5814
                    );
5815
                }
5816
            }
5817
            $IDs[] = $id;
5818
        }
5819
        return $IDs;
5820
    }
5821
5822
5823
5824
    /**
5825
     * Returns the string used in capabilities relating to this model. If there
5826
     * are no capabilities that relate to this model returns false
5827
     *
5828
     * @return string|false
5829
     */
5830
    public function cap_slug()
5831
    {
5832
        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5833
    }
5834
5835
5836
5837
    /**
5838
     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5839
     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5840
     * only returns the cap restrictions array in that context (ie, the array
5841
     * at that key)
5842
     *
5843
     * @param string $context
5844
     * @return EE_Default_Where_Conditions[] indexed by associated capability
5845
     * @throws EE_Error
5846
     */
5847
    public function cap_restrictions($context = EEM_Base::caps_read)
5848
    {
5849
        EEM_Base::verify_is_valid_cap_context($context);
5850
        //check if we ought to run the restriction generator first
5851
        if (
5852
            isset($this->_cap_restriction_generators[$context])
5853
            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5854
            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5855
        ) {
5856
            $this->_cap_restrictions[$context] = array_merge(
5857
                $this->_cap_restrictions[$context],
5858
                $this->_cap_restriction_generators[$context]->generate_restrictions()
5859
            );
5860
        }
5861
        //and make sure we've finalized the construction of each restriction
5862
        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5863
            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5864
                $where_conditions_obj->_finalize_construct($this);
5865
            }
5866
        }
5867
        return $this->_cap_restrictions[$context];
5868
    }
5869
5870
5871
5872
    /**
5873
     * Indicating whether or not this model thinks its a wp core model
5874
     *
5875
     * @return boolean
5876
     */
5877
    public function is_wp_core_model()
5878
    {
5879
        return $this->_wp_core_model;
5880
    }
5881
5882
5883
5884
    /**
5885
     * Gets all the caps that are missing which impose a restriction on
5886
     * queries made in this context
5887
     *
5888
     * @param string $context one of EEM_Base::caps_ constants
5889
     * @return EE_Default_Where_Conditions[] indexed by capability name
5890
     * @throws EE_Error
5891
     */
5892
    public function caps_missing($context = EEM_Base::caps_read)
5893
    {
5894
        $missing_caps = array();
5895
        $cap_restrictions = $this->cap_restrictions($context);
5896
        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5897
            if (! EE_Capabilities::instance()
5898
                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5899
            ) {
5900
                $missing_caps[$cap] = $restriction_if_no_cap;
5901
            }
5902
        }
5903
        return $missing_caps;
5904
    }
5905
5906
5907
5908
    /**
5909
     * Gets the mapping from capability contexts to action strings used in capability names
5910
     *
5911
     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5912
     * one of 'read', 'edit', or 'delete'
5913
     */
5914
    public function cap_contexts_to_cap_action_map()
5915
    {
5916
        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5917
            $this);
5918
    }
5919
5920
5921
5922
    /**
5923
     * Gets the action string for the specified capability context
5924
     *
5925
     * @param string $context
5926
     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5927
     * @throws EE_Error
5928
     */
5929
    public function cap_action_for_context($context)
5930
    {
5931
        $mapping = $this->cap_contexts_to_cap_action_map();
5932
        if (isset($mapping[$context])) {
5933
            return $mapping[$context];
5934
        }
5935
        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5936
            return $action;
5937
        }
5938
        throw new EE_Error(
5939
            sprintf(
5940
                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5941
                $context,
5942
                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5943
            )
5944
        );
5945
    }
5946
5947
5948
5949
    /**
5950
     * Returns all the capability contexts which are valid when querying models
5951
     *
5952
     * @return array
5953
     */
5954
    public static function valid_cap_contexts()
5955
    {
5956
        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5957
            self::caps_read,
5958
            self::caps_read_admin,
5959
            self::caps_edit,
5960
            self::caps_delete,
5961
        ));
5962
    }
5963
5964
5965
5966
    /**
5967
     * Returns all valid options for 'default_where_conditions'
5968
     *
5969
     * @return array
5970
     */
5971
    public static function valid_default_where_conditions()
5972
    {
5973
        return array(
5974
            EEM_Base::default_where_conditions_all,
5975
            EEM_Base::default_where_conditions_this_only,
5976
            EEM_Base::default_where_conditions_others_only,
5977
            EEM_Base::default_where_conditions_minimum_all,
5978
            EEM_Base::default_where_conditions_minimum_others,
5979
            EEM_Base::default_where_conditions_none
5980
        );
5981
    }
5982
5983
    // public static function default_where_conditions_full
5984
    /**
5985
     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5986
     *
5987
     * @param string $context
5988
     * @return bool
5989
     * @throws EE_Error
5990
     */
5991
    static public function verify_is_valid_cap_context($context)
5992
    {
5993
        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5994
        if (in_array($context, $valid_cap_contexts)) {
5995
            return true;
5996
        }
5997
        throw new EE_Error(
5998
            sprintf(
5999
                __(
6000
                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6001
                    'event_espresso'
6002
                ),
6003
                $context,
6004
                'EEM_Base',
6005
                implode(',', $valid_cap_contexts)
6006
            )
6007
        );
6008
    }
6009
6010
6011
6012
    /**
6013
     * Clears all the models field caches. This is only useful when a sub-class
6014
     * might have added a field or something and these caches might be invalidated
6015
     */
6016
    protected function _invalidate_field_caches()
6017
    {
6018
        $this->_cache_foreign_key_to_fields = array();
6019
        $this->_cached_fields = null;
6020
        $this->_cached_fields_non_db_only = null;
6021
    }
6022
6023
6024
6025
    /**
6026
     * Gets the list of all the where query param keys that relate to logic instead of field names
6027
     * (eg "and", "or", "not").
6028
     *
6029
     * @return array
6030
     */
6031
    public function logic_query_param_keys()
6032
    {
6033
        return $this->_logic_query_param_keys;
6034
    }
6035
6036
6037
6038
    /**
6039
     * Determines whether or not the where query param array key is for a logic query param.
6040
     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6041
     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6042
     *
6043
     * @param $query_param_key
6044
     * @return bool
6045
     */
6046
    public function is_logic_query_param_key($query_param_key)
6047
    {
6048
        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6049
            if ($query_param_key === $logic_query_param_key
6050
                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6051
            ) {
6052
                return true;
6053
            }
6054
        }
6055
        return false;
6056
    }
6057
6058
6059
6060
}
6061