Completed
Branch FET-9222-rest-api-writes (a8f519)
by
unknown
76:34 queued 64:09
created

EEM_Base::second_table()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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