Completed
Branch FET-10898-venue-meta-shortcode (bb8106)
by
unknown
65:31 queued 54:25
created

EEM_Base::delete_permanently()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 99
Code Lines 42

Duplication

Lines 3
Ratio 3.03 %

Importance

Changes 0
Metric Value
cc 8
eloc 42
nc 6
nop 2
dl 3
loc 99
rs 5.2996
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
use EventEspresso\core\exceptions\InvalidDataTypeException;
3
use EventEspresso\core\exceptions\InvalidInterfaceException;
4
use EventEspresso\core\interfaces\ResettableInterface;
5
use EventEspresso\core\services\orm\ModelFieldFactory;
6
use EventEspresso\core\services\loaders\LoaderFactory;
7
8
/**
9
 * Class EEM_Base
10
 * Multi-table model. Especially handles joins when querying.
11
 * An important note about values dealt with in models and model objects:
12
 * values used by models exist in basically 3 different domains, which the EE_Model_Fields help convert between:
13
 * 1. Client-code values (eg, controller code may refer to a date as "March 21, 2013")
14
 * 2. Model object values (eg, after the model object has called set() on the value and saves it onto the model object,
15
 * it may become a unix timestamp, eg 12312412412)
16
 * 3. Database values (eg, we may later decide to store dates as mysql dates, in which case they'd be stored as
17
 * '2013-03-21 00:00:00') Sometimes these values are the same, but often they are not. When your client code is using a
18
 * model's functions, you need to be aware which domain your data exists in. If it is client-code values (ie, it hasn't
19
 * had a EE_Model_Field call prepare_for_set on it) then use the model functions as normal. However, if you are calling
20
 * the model functions with values from the model object domain (ie, the code your writing is probably within a model
21
 * object, and all the values you're dealing with have had an EE_Model_Field call prepare_for_set on them), then you'll
22
 * want to set $values_already_prepared_by_model_object to FALSE within the argument-list of the functions you call (in
23
 * order to avoid re-processing those values). If your values are already in the database values domain, you'll either
24
 * way to convert them into the model object domain by creating model objects from those raw db values (ie,using
25
 * EEM_Base::_create_objects), or just use $wpdb directly.
26
 *
27
 * @package               Event Espresso
28
 * @subpackage            core
29
 * @author                Michael Nelson
30
 * @since                 EE4
31
 */
32
abstract class EEM_Base extends EE_Base implements ResettableInterface
33
{
34
35
    //admin posty
36
    //basic -> grants access to mine -> if they don't have it, select none
37
    //*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
38
    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
39
    //*_published -> grants access to published -> if they dont have it, select non-published
40
    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
41
    //publish_{thing} -> can change status TO publish; SPECIAL CASE
42
    //frontend posty
43
    //by default has access to published
44
    //basic -> grants access to mine that aren't published, and all published
45
    //*_others ->grants access to others that aren't private, all mine
46
    //*_private -> grants full access
47
    //frontend non-posty
48
    //like admin posty
49
    //category-y
50
    //assign -> grants access to join-table
51
    //(delete, edit)
52
    //payment-method-y
53
    //for each registered payment method,
54
    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
55
    /**
56
     * Flag to indicate whether the values provided to EEM_Base have already been prepared
57
     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
58
     * They almost always WILL NOT, but it's not necessarily a requirement.
59
     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
60
     *
61
     * @var boolean
62
     */
63
    private $_values_already_prepared_by_model_object = 0;
64
65
    /**
66
     * when $_values_already_prepared_by_model_object equals this, we assume
67
     * the data is just like form input that needs to have the model fields'
68
     * prepare_for_set and prepare_for_use_in_db called on it
69
     */
70
    const not_prepared_by_model_object = 0;
71
72
    /**
73
     * when $_values_already_prepared_by_model_object equals this, we
74
     * assume this value is coming from a model object and doesn't need to have
75
     * prepare_for_set called on it, just prepare_for_use_in_db is used
76
     */
77
    const prepared_by_model_object = 1;
78
79
    /**
80
     * when $_values_already_prepared_by_model_object equals this, we assume
81
     * the values are already to be used in the database (ie no processing is done
82
     * on them by the model's fields)
83
     */
84
    const prepared_for_use_in_db = 2;
85
86
87
    protected $singular_item = 'Item';
88
89
    protected $plural_item   = 'Items';
90
91
    /**
92
     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
93
     */
94
    protected $_tables;
95
96
    /**
97
     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
98
     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
99
     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
100
     *
101
     * @var \EE_Model_Field_Base[] $_fields
102
     */
103
    protected $_fields;
104
105
    /**
106
     * array of different kinds of relations
107
     *
108
     * @var \EE_Model_Relation_Base[] $_model_relations
109
     */
110
    protected $_model_relations;
111
112
    /**
113
     * @var \EE_Index[] $_indexes
114
     */
115
    protected $_indexes = array();
116
117
    /**
118
     * Default strategy for getting where conditions on this model. This strategy is used to get default
119
     * where conditions which are added to get_all, update, and delete queries. They can be overridden
120
     * by setting the same columns as used in these queries in the query yourself.
121
     *
122
     * @var EE_Default_Where_Conditions
123
     */
124
    protected $_default_where_conditions_strategy;
125
126
    /**
127
     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
128
     * This is particularly useful when you want something between 'none' and 'default'
129
     *
130
     * @var EE_Default_Where_Conditions
131
     */
132
    protected $_minimum_where_conditions_strategy;
133
134
    /**
135
     * String describing how to find the "owner" of this model's objects.
136
     * When there is a foreign key on this model to the wp_users table, this isn't needed.
137
     * But when there isn't, this indicates which related model, or transiently-related model,
138
     * has the foreign key to the wp_users table.
139
     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
140
     * related to events, and events have a foreign key to wp_users.
141
     * On EEM_Transaction, this would be 'Transaction.Event'
142
     *
143
     * @var string
144
     */
145
    protected $_model_chain_to_wp_user = '';
146
147
    /**
148
     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
149
     * don't need it (particularly CPT models)
150
     *
151
     * @var bool
152
     */
153
    protected $_ignore_where_strategy = false;
154
155
    /**
156
     * String used in caps relating to this model. Eg, if the caps relating to this
157
     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
158
     *
159
     * @var string. If null it hasn't been initialized yet. If false then we
160
     * have indicated capabilities don't apply to this
161
     */
162
    protected $_caps_slug = null;
163
164
    /**
165
     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
166
     * and next-level keys are capability names, and each's value is a
167
     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
168
     * they specify which context to use (ie, frontend, backend, edit or delete)
169
     * and then each capability in the corresponding sub-array that they're missing
170
     * adds the where conditions onto the query.
171
     *
172
     * @var array
173
     */
174
    protected $_cap_restrictions = array(
175
        self::caps_read       => array(),
176
        self::caps_read_admin => array(),
177
        self::caps_edit       => array(),
178
        self::caps_delete     => array(),
179
    );
180
181
    /**
182
     * Array defining which cap restriction generators to use to create default
183
     * cap restrictions to put in EEM_Base::_cap_restrictions.
184
     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
185
     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
186
     * automatically set this to false (not just null).
187
     *
188
     * @var EE_Restriction_Generator_Base[]
189
     */
190
    protected $_cap_restriction_generators = array();
191
192
    /**
193
     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
194
     */
195
    const caps_read       = 'read';
196
197
    const caps_read_admin = 'read_admin';
198
199
    const caps_edit       = 'edit';
200
201
    const caps_delete     = 'delete';
202
203
    /**
204
     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
205
     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
206
     * maps to 'read' because when looking for relevant permissions we're going to use
207
     * 'read' in teh capabilities names like 'ee_read_events' etc.
208
     *
209
     * @var array
210
     */
211
    protected $_cap_contexts_to_cap_action_map = array(
212
        self::caps_read       => 'read',
213
        self::caps_read_admin => 'read',
214
        self::caps_edit       => 'edit',
215
        self::caps_delete     => 'delete',
216
    );
217
218
    /**
219
     * Timezone
220
     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
221
     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
222
     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
223
     * EE_Datetime_Field data type will have access to it.
224
     *
225
     * @var string
226
     */
227
    protected $_timezone;
228
229
230
    /**
231
     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
232
     * multisite.
233
     *
234
     * @var int
235
     */
236
    protected static $_model_query_blog_id;
237
238
    /**
239
     * A copy of _fields, except the array keys are the model names pointed to by
240
     * the field
241
     *
242
     * @var EE_Model_Field_Base[]
243
     */
244
    private $_cache_foreign_key_to_fields = array();
245
246
    /**
247
     * Cached list of all the fields on the model, indexed by their name
248
     *
249
     * @var EE_Model_Field_Base[]
250
     */
251
    private $_cached_fields = null;
252
253
    /**
254
     * Cached list of all the fields on the model, except those that are
255
     * marked as only pertinent to the database
256
     *
257
     * @var EE_Model_Field_Base[]
258
     */
259
    private $_cached_fields_non_db_only = null;
260
261
    /**
262
     * A cached reference to the primary key for quick lookup
263
     *
264
     * @var EE_Model_Field_Base
265
     */
266
    private $_primary_key_field = null;
267
268
    /**
269
     * Flag indicating whether this model has a primary key or not
270
     *
271
     * @var boolean
272
     */
273
    protected $_has_primary_key_field = null;
274
275
    /**
276
     * Whether or not this model is based off a table in WP core only (CPTs should set
277
     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
278
     *
279
     * @var boolean
280
     */
281
    protected $_wp_core_model = false;
282
283
    /**
284
     *    List of valid operators that can be used for querying.
285
     * The keys are all operators we'll accept, the values are the real SQL
286
     * operators used
287
     *
288
     * @var array
289
     */
290
    protected $_valid_operators = array(
291
        '='           => '=',
292
        '<='          => '<=',
293
        '<'           => '<',
294
        '>='          => '>=',
295
        '>'           => '>',
296
        '!='          => '!=',
297
        'LIKE'        => 'LIKE',
298
        'like'        => 'LIKE',
299
        'NOT_LIKE'    => 'NOT LIKE',
300
        'not_like'    => 'NOT LIKE',
301
        'NOT LIKE'    => 'NOT LIKE',
302
        'not like'    => 'NOT LIKE',
303
        'IN'          => 'IN',
304
        'in'          => 'IN',
305
        'NOT_IN'      => 'NOT IN',
306
        'not_in'      => 'NOT IN',
307
        'NOT IN'      => 'NOT IN',
308
        'not in'      => 'NOT IN',
309
        'between'     => 'BETWEEN',
310
        'BETWEEN'     => 'BETWEEN',
311
        'IS_NOT_NULL' => 'IS NOT NULL',
312
        'is_not_null' => 'IS NOT NULL',
313
        'IS NOT NULL' => 'IS NOT NULL',
314
        'is not null' => 'IS NOT NULL',
315
        'IS_NULL'     => 'IS NULL',
316
        'is_null'     => 'IS NULL',
317
        'IS NULL'     => 'IS NULL',
318
        'is null'     => 'IS NULL',
319
        'REGEXP'      => 'REGEXP',
320
        'regexp'      => 'REGEXP',
321
        'NOT_REGEXP'  => 'NOT REGEXP',
322
        'not_regexp'  => 'NOT REGEXP',
323
        'NOT REGEXP'  => 'NOT REGEXP',
324
        'not regexp'  => 'NOT REGEXP',
325
    );
326
327
    /**
328
     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
329
     *
330
     * @var array
331
     */
332
    protected $_in_style_operators = array('IN', 'NOT IN');
333
334
    /**
335
     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
336
     * '12-31-2012'"
337
     *
338
     * @var array
339
     */
340
    protected $_between_style_operators = array('BETWEEN');
341
342
    /**
343
     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
344
     * on a join table.
345
     *
346
     * @var array
347
     */
348
    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
349
350
    /**
351
     * Allowed values for $query_params['order'] for ordering in queries
352
     *
353
     * @var array
354
     */
355
    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
356
357
    /**
358
     * When these are keys in a WHERE or HAVING clause, they are handled much differently
359
     * than regular field names. It is assumed that their values are an array of WHERE conditions
360
     *
361
     * @var array
362
     */
363
    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
364
365
    /**
366
     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
367
     * 'where', but 'where' clauses are so common that we thought we'd omit it
368
     *
369
     * @var array
370
     */
371
    private $_allowed_query_params = array(
372
        0,
373
        'limit',
374
        'order_by',
375
        'group_by',
376
        'having',
377
        'force_join',
378
        'order',
379
        'on_join_limit',
380
        'default_where_conditions',
381
        'caps',
382
    );
383
384
    /**
385
     * All the data types that can be used in $wpdb->prepare statements.
386
     *
387
     * @var array
388
     */
389
    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
390
391
    /**
392
     *    EE_Registry Object
393
     *
394
     * @var    object
395
     * @access    protected
396
     */
397
    protected $EE = null;
398
399
400
    /**
401
     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
402
     *
403
     * @var int
404
     */
405
    protected $_show_next_x_db_queries = 0;
406
407
    /**
408
     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
409
     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
410
     *
411
     * @var array
412
     */
413
    protected $_custom_selections = array();
414
415
    /**
416
     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
417
     * caches every model object we've fetched from the DB on this request
418
     *
419
     * @var array
420
     */
421
    protected $_entity_map;
422
423
    /**
424
     * constant used to show EEM_Base has not yet verified the db on this http request
425
     */
426
    const db_verified_none = 0;
427
428
    /**
429
     * constant used to show EEM_Base has verified the EE core db on this http request,
430
     * but not the addons' dbs
431
     */
432
    const db_verified_core = 1;
433
434
    /**
435
     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
436
     * the EE core db too)
437
     */
438
    const db_verified_addons = 2;
439
440
    /**
441
     * indicates whether an EEM_Base child has already re-verified the DB
442
     * is ok (we don't want to do it repetitively). Should be set to one the constants
443
     * looking like EEM_Base::db_verified_*
444
     *
445
     * @var int - 0 = none, 1 = core, 2 = addons
446
     */
447
    protected static $_db_verification_level = EEM_Base::db_verified_none;
448
449
    /**
450
     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
451
     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
452
     *        registrations for non-trashed tickets for non-trashed datetimes)
453
     */
454
    const default_where_conditions_all = 'all';
455
456
    /**
457
     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
458
     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
459
     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
460
     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
461
     *        models which share tables with other models, this can return data for the wrong model.
462
     */
463
    const default_where_conditions_this_only = 'this_model_only';
464
465
    /**
466
     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
467
     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
468
     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
469
     */
470
    const default_where_conditions_others_only = 'other_models_only';
471
472
    /**
473
     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
474
     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
475
     *        their table with other models, like the Event and Venue models. For example, when querying for events
476
     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
477
     *        (regardless of whether those events and venues are trashed)
478
     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
479
     *        events.
480
     */
481
    const default_where_conditions_minimum_all = 'minimum';
482
483
    /**
484
     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
485
     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
486
     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
487
     *        not)
488
     */
489
    const default_where_conditions_minimum_others = 'full_this_minimum_others';
490
491
    /**
492
     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
493
     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
494
     *        it's possible it will return table entries for other models. You should use
495
     *        EEM_Base::default_where_conditions_minimum_all instead.
496
     */
497
    const default_where_conditions_none = 'none';
498
499
500
501
    /**
502
     * About all child constructors:
503
     * they should define the _tables, _fields and _model_relations arrays.
504
     * Should ALWAYS be called after child constructor.
505
     * In order to make the child constructors to be as simple as possible, this parent constructor
506
     * finalizes constructing all the object's attributes.
507
     * Generally, rather than requiring a child to code
508
     * $this->_tables = array(
509
     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
510
     *        ...);
511
     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
512
     * each EE_Table has a function to set the table's alias after the constructor, using
513
     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
514
     * do something similar.
515
     *
516
     * @param null $timezone
517
     * @throws EE_Error
518
     */
519
    protected function __construct($timezone = null)
520
    {
521
        // check that the model has not been loaded too soon
522
        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
523
            throw new EE_Error (
524
                sprintf(
525
                    __('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.',
526
                        'event_espresso'),
527
                    get_class($this)
528
                )
529
            );
530
        }
531
        /**
532
         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
533
         */
534
        if (empty(EEM_Base::$_model_query_blog_id)) {
535
            EEM_Base::set_model_query_blog_id();
536
        }
537
        /**
538
         * Filters the list of tables on a model. It is best to NOT use this directly and instead
539
         * just use EE_Register_Model_Extension
540
         *
541
         * @var EE_Table_Base[] $_tables
542
         */
543
        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
544
        foreach ($this->_tables as $table_alias => $table_obj) {
545
            /** @var $table_obj EE_Table_Base */
546
            $table_obj->_construct_finalize_with_alias($table_alias);
547
            if ($table_obj instanceof EE_Secondary_Table) {
548
                /** @var $table_obj EE_Secondary_Table */
549
                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
550
            }
551
        }
552
        /**
553
         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
554
         * EE_Register_Model_Extension
555
         *
556
         * @param EE_Model_Field_Base[] $_fields
557
         */
558
        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
559
        $this->_invalidate_field_caches();
560
        foreach ($this->_fields as $table_alias => $fields_for_table) {
561
            if (! array_key_exists($table_alias, $this->_tables)) {
562
                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
563
                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
564
            }
565
            foreach ($fields_for_table as $field_name => $field_obj) {
566
                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
                //primary key field base has a slightly different _construct_finalize
568
                /** @var $field_obj EE_Model_Field_Base */
569
                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
            }
571
        }
572
        // everything is related to Extra_Meta
573
        if (get_class($this) !== 'EEM_Extra_Meta') {
574
            //make extra meta related to everything, but don't block deleting things just
575
            //because they have related extra meta info. For now just orphan those extra meta
576
            //in the future we should automatically delete them
577
            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
        }
579
        //and change logs
580
        if (get_class($this) !== 'EEM_Change_Log') {
581
            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
        }
583
        /**
584
         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
         * EE_Register_Model_Extension
586
         *
587
         * @param EE_Model_Relation_Base[] $_model_relations
588
         */
589
        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
590
            $this->_model_relations);
591
        foreach ($this->_model_relations as $model_name => $relation_obj) {
592
            /** @var $relation_obj EE_Model_Relation_Base */
593
            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
594
        }
595
        foreach ($this->_indexes as $index_name => $index_obj) {
596
            /** @var $index_obj EE_Index */
597
            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
598
        }
599
        $this->set_timezone($timezone);
600
        //finalize default where condition strategy, or set default
601
        if (! $this->_default_where_conditions_strategy) {
602
            //nothing was set during child constructor, so set default
603
            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
604
        }
605
        $this->_default_where_conditions_strategy->_finalize_construct($this);
606
        if (! $this->_minimum_where_conditions_strategy) {
607
            //nothing was set during child constructor, so set default
608
            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
609
        }
610
        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
611
        //if the cap slug hasn't been set, and we haven't set it to false on purpose
612
        //to indicate to NOT set it, set it to the logical default
613
        if ($this->_caps_slug === null) {
614
            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
615
        }
616
        //initialize the standard cap restriction generators if none were specified by the child constructor
617
        if ($this->_cap_restriction_generators !== false) {
618
            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
619
                if (! isset($this->_cap_restriction_generators[$cap_context])) {
620
                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
621
                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
622
                        new EE_Restriction_Generator_Protected(),
623
                        $cap_context,
624
                        $this
625
                    );
626
                }
627
            }
628
        }
629
        //if there are cap restriction generators, use them to make the default cap restrictions
630
        if ($this->_cap_restriction_generators !== false) {
631
            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
632
                if (! $generator_object) {
633
                    continue;
634
                }
635 View Code Duplication
                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
636
                    throw new EE_Error(
637
                        sprintf(
638
                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
639
                                'event_espresso'),
640
                            $context,
641
                            $this->get_this_model_name()
642
                        )
643
                    );
644
                }
645
                $action = $this->cap_action_for_context($context);
646
                if (! $generator_object->construction_finalized()) {
647
                    $generator_object->_construct_finalize($this, $action);
648
                }
649
            }
650
        }
651
        do_action('AHEE__' . get_class($this) . '__construct__end');
652
    }
653
654
655
656
    /**
657
     * Generates the cap restrictions for the given context, or if they were
658
     * already generated just gets what's cached
659
     *
660
     * @param string $context one of EEM_Base::valid_cap_contexts()
661
     * @return EE_Default_Where_Conditions[]
662
     */
663
    protected function _generate_cap_restrictions($context)
664
    {
665
        if (isset($this->_cap_restriction_generators[$context])
666
            && $this->_cap_restriction_generators[$context]
667
               instanceof
668
               EE_Restriction_Generator_Base
669
        ) {
670
            return $this->_cap_restriction_generators[$context]->generate_restrictions();
671
        } else {
672
            return array();
673
        }
674
    }
675
676
677
678
    /**
679
     * Used to set the $_model_query_blog_id static property.
680
     *
681
     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
682
     *                      value for get_current_blog_id() will be used.
683
     */
684
    public static function set_model_query_blog_id($blog_id = 0)
685
    {
686
        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
687
    }
688
689
690
691
    /**
692
     * Returns whatever is set as the internal $model_query_blog_id.
693
     *
694
     * @return int
695
     */
696
    public static function get_model_query_blog_id()
697
    {
698
        return EEM_Base::$_model_query_blog_id;
699
    }
700
701
702
703
    /**
704
     * This function is a singleton method used to instantiate the Espresso_model object
705
     *
706
     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
707
     *                                (and any incoming timezone data that gets saved).
708
     *                                Note this just sends the timezone info to the date time model field objects.
709
     *                                Default is NULL
710
     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
711
     * @return static (as in the concrete child class)
712
     * @throws InvalidArgumentException
713
     * @throws InvalidInterfaceException
714
     * @throws InvalidDataTypeException
715
     * @throws EE_Error
716
     */
717
    public static function instance($timezone = null)
718
    {
719
        // check if instance of Espresso_model already exists
720
        if (! static::$_instance instanceof static) {
721
            // instantiate Espresso_model
722
            static::$_instance = new static(
723
                $timezone,
724
                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
725
            );
726
        }
727
        //we might have a timezone set, let set_timezone decide what to do with it
728
        static::$_instance->set_timezone($timezone);
729
        // Espresso_model object
730
        return static::$_instance;
731
    }
732
733
734
735
    /**
736
     * resets the model and returns it
737
     *
738
     * @param null | string $timezone
739
     * @return EEM_Base|null (if the model was already instantiated, returns it, with
740
     * @throws ReflectionException
741
     * all its properties reset; if it wasn't instantiated, returns null)
742
     * @throws EE_Error
743
     * @throws InvalidArgumentException
744
     * @throws InvalidDataTypeException
745
     * @throws InvalidInterfaceException
746
     */
747
    public static function reset($timezone = null)
748
    {
749
        if (static::$_instance instanceof EEM_Base) {
750
            //let's try to NOT swap out the current instance for a new one
751
            //because if someone has a reference to it, we can't remove their reference
752
            //so it's best to keep using the same reference, but change the original object
753
            //reset all its properties to their original values as defined in the class
754
            $r = new ReflectionClass(get_class(static::$_instance));
755
            $static_properties = $r->getStaticProperties();
756
            foreach ($r->getDefaultProperties() as $property => $value) {
757
                //don't set instance to null like it was originally,
758
                //but it's static anyways, and we're ignoring static properties (for now at least)
759
                if (! isset($static_properties[$property])) {
760
                    static::$_instance->{$property} = $value;
761
                }
762
            }
763
            //and then directly call its constructor again, like we would if we were creating a new one
764
            static::$_instance->__construct(
765
                $timezone,
766
                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
767
            );
768
            return self::instance();
769
        }
770
        return null;
771
    }
772
773
774
775
    /**
776
     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
777
     *
778
     * @param  boolean $translated return localized strings or JUST the array.
779
     * @return array
780
     * @throws EE_Error
781
     */
782
    public function status_array($translated = false)
783
    {
784
        if (! array_key_exists('Status', $this->_model_relations)) {
785
            return array();
786
        }
787
        $model_name = $this->get_this_model_name();
788
        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
789
        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
790
        $status_array = array();
791
        foreach ($stati as $status) {
792
            $status_array[$status->ID()] = $status->get('STS_code');
793
        }
794
        return $translated
795
            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
796
            : $status_array;
797
    }
798
799
800
801
    /**
802
     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
803
     *
804
     * @param array $query_params             {
805
     * @var array $0 (where) array {
806
     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
807
     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
808
     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
809
     *                                        conditions based on related models (and even
810
     *                                        models-related-to-related-models) prepend the model's name onto the field
811
     *                                        name. Eg,
812
     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
813
     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
814
     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
815
     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
816
     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
817
     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
818
     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
819
     *                                        to Venues (even when each of those models actually consisted of two
820
     *                                        tables). Also, you may chain the model relations together. Eg instead of
821
     *                                        just having
822
     *                                        "Venue.VNU_ID", you could have
823
     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
824
     *                                        events are related to Registrations, which are related to Attendees). You
825
     *                                        can take it even further with
826
     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
827
     *                                        (from the default of '='), change the value to an numerically-indexed
828
     *                                        array, where the first item in the list is the operator. eg: array(
829
     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
830
     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
831
     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
832
     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
833
     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
834
     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
835
     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
836
     *                                        the operator is IN. Also, values can actually be field names. To indicate
837
     *                                        the value is a field, simply provide a third array item (true) to the
838
     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
839
     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
840
     *                                        Note: you can also use related model field names like you would any other
841
     *                                        field name. eg:
842
     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
843
     *                                        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__>' =>
844
     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
845
     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
846
     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
847
     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
848
     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
849
     *                                        to be what you last specified. IE, "AND"s by default, but if you had
850
     *                                        previously specified to use ORs to join, ORs will continue to be used.
851
     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
852
     *                                        "stick" until you specify an AND. eg
853
     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
854
     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
855
     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
856
     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
857
     *                                        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 >>
858
     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
859
     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
860
     *                                        too, eg:
861
     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
862
     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
863
     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
864
     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
865
     *                                        Remember when you provide two numbers for the limit, the 1st number is
866
     *                                        the OFFSET, the 2nd is the LIMIT
867
     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
868
     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
869
     *                                        following format array('on_join_limit'
870
     *                                        => array( 'table_alias', array(1,2) ) ).
871
     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
872
     *                                        values are either 'ASC' or 'DESC'.
873
     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
874
     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
875
     *                                        DESC..." respectively. Like the
876
     *                                        'where' conditions, these fields can be on related models. Eg
877
     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
878
     *                                        perfectly valid from any model related to 'Registration' (like Event,
879
     *                                        Attendee, Price, Datetime, etc.)
880
     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
881
     *                                        'order' specifies whether to order the field specified in 'order_by' in
882
     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
883
     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
884
     *                                        order by the primary key. Eg,
885
     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
886
     *                                        //(will join with the Datetime model's table(s) and order by its field
887
     *                                        DTT_EVT_start) or
888
     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
889
     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
890
     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
891
     *                                        'group_by'=>'VNU_ID', or
892
     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
893
     *                                        if no
894
     *                                        $group_by is specified, and a limit is set, automatically groups by the
895
     *                                        model's primary key (or combined primary keys). This avoids some
896
     *                                        weirdness that results when using limits, tons of joins, and no group by,
897
     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
898
     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
899
     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
900
     *                                        results)
901
     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
902
     *                                        array where values are models to be joined in the query.Eg
903
     *                                        array('Attendee','Payment','Datetime'). You may join with transient
904
     *                                        models using period, eg "Registration.Transaction.Payment". You will
905
     *                                        probably only want to do this in hopes of increasing efficiency, as
906
     *                                        related models which belongs to the current model
907
     *                                        (ie, the current model has a foreign key to them, like how Registration
908
     *                                        belongs to Attendee) can be cached in order to avoid future queries
909
     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
910
     *                                        set this to 'none' to disable all default where conditions. Eg, usually
911
     *                                        soft-deleted objects are filtered-out if you want to include them, set
912
     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
913
     *                                        default where conditions set it to 'other_models_only'. If you only want
914
     *                                        this model's default where conditions added to the query, use
915
     *                                        'this_model_only'. If you want to use all default where conditions
916
     *                                        (default), set to 'all'.
917
     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
918
     *                                        we just NOT apply any capabilities/permissions/restrictions and return
919
     *                                        everything? Or should we only show the current user items they should be
920
     *                                        able to view on the frontend, backend, edit, or delete? can be set to
921
     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
922
     *                                        }
923
     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
924
     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
925
     *                                        again. Array keys are object IDs (if there is a primary key on the model.
926
     *                                        if not, numerically indexed) Some full examples: get 10 transactions
927
     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
928
     *                                        array( array(
929
     *                                        'OR'=>array(
930
     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
931
     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
932
     *                                        )
933
     *                                        ),
934
     *                                        'limit'=>10,
935
     *                                        'group_by'=>'TXN_ID'
936
     *                                        ));
937
     *                                        get all the answers to the question titled "shirt size" for event with id
938
     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
939
     *                                        'Question.QST_display_text'=>'shirt size',
940
     *                                        'Registration.Event.EVT_ID'=>12
941
     *                                        ),
942
     *                                        'order_by'=>array('ANS_value'=>'ASC')
943
     *                                        ));
944
     * @throws EE_Error
945
     */
946
    public function get_all($query_params = array())
947
    {
948
        if (isset($query_params['limit'])
949
            && ! isset($query_params['group_by'])
950
        ) {
951
            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
952
        }
953
        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
954
    }
955
956
957
958
    /**
959
     * Modifies the query parameters so we only get back model objects
960
     * that "belong" to the current user
961
     *
962
     * @param array $query_params @see EEM_Base::get_all()
963
     * @return array like EEM_Base::get_all
964
     */
965
    public function alter_query_params_to_only_include_mine($query_params = array())
966
    {
967
        $wp_user_field_name = $this->wp_user_field_name();
968
        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...
969
            $query_params[0][$wp_user_field_name] = get_current_user_id();
970
        }
971
        return $query_params;
972
    }
973
974
975
976
    /**
977
     * Returns the name of the field's name that points to the WP_User table
978
     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
979
     * foreign key to the WP_User table)
980
     *
981
     * @return string|boolean string on success, boolean false when there is no
982
     * foreign key to the WP_User table
983
     */
984
    public function wp_user_field_name()
985
    {
986
        try {
987
            if (! empty($this->_model_chain_to_wp_user)) {
988
                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
989
                $last_model_name = end($models_to_follow_to_wp_users);
990
                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
991
                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
992
            } else {
993
                $model_with_fk_to_wp_users = $this;
994
                $model_chain_to_wp_user = '';
995
            }
996
            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
997
            return $model_chain_to_wp_user . $wp_user_field->get_name();
998
        } catch (EE_Error $e) {
999
            return false;
1000
        }
1001
    }
1002
1003
1004
1005
    /**
1006
     * Returns the _model_chain_to_wp_user string, which indicates which related model
1007
     * (or transiently-related model) has a foreign key to the wp_users table;
1008
     * useful for finding if model objects of this type are 'owned' by the current user.
1009
     * This is an empty string when the foreign key is on this model and when it isn't,
1010
     * but is only non-empty when this model's ownership is indicated by a RELATED model
1011
     * (or transiently-related model)
1012
     *
1013
     * @return string
1014
     */
1015
    public function model_chain_to_wp_user()
1016
    {
1017
        return $this->_model_chain_to_wp_user;
1018
    }
1019
1020
1021
1022
    /**
1023
     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1024
     * like how registrations don't have a foreign key to wp_users, but the
1025
     * events they are for are), or is unrelated to wp users.
1026
     * generally available
1027
     *
1028
     * @return boolean
1029
     */
1030
    public function is_owned()
1031
    {
1032
        if ($this->model_chain_to_wp_user()) {
1033
            return true;
1034
        }
1035
        try {
1036
            $this->get_foreign_key_to('WP_User');
1037
            return true;
1038
        } catch (EE_Error $e) {
1039
            return false;
1040
        }
1041
    }
1042
1043
1044
1045
    /**
1046
     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1047
     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1048
     * the model)
1049
     *
1050
     * @param array  $query_params      like EEM_Base::get_all's $query_params
1051
     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1052
     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1053
     *                                  fields on the model, and the models we joined to in the query. However, you can
1054
     *                                  override this and set the select to "*", or a specific column name, like
1055
     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1056
     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1057
     *                                  the aliases used to refer to this selection, and values are to be
1058
     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1059
     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1060
     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1061
     * @throws EE_Error
1062
     */
1063
    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1064
    {
1065
        // remember the custom selections, if any, and type cast as array
1066
        // (unless $columns_to_select is an object, then just set as an empty array)
1067
        // Note: (array) 'some string' === array( 'some string' )
1068
        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1069
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1070
        $select_expressions = $columns_to_select !== null
1071
            ? $this->_construct_select_from_input($columns_to_select)
1072
            : $this->_construct_default_select_sql($model_query_info);
1073
        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1074
        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1075
    }
1076
1077
1078
1079
    /**
1080
     * Gets an array of rows from the database just like $wpdb->get_results would,
1081
     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1082
     * take care of joins, field preparation etc.
1083
     *
1084
     * @param array  $query_params      like EEM_Base::get_all's $query_params
1085
     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1086
     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1087
     *                                  fields on the model, and the models we joined to in the query. However, you can
1088
     *                                  override this and set the select to "*", or a specific column name, like
1089
     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1090
     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1091
     *                                  the aliases used to refer to this selection, and values are to be
1092
     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1093
     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1094
     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1095
     * @throws EE_Error
1096
     */
1097
    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1098
    {
1099
        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1100
    }
1101
1102
1103
1104
    /**
1105
     * For creating a custom select statement
1106
     *
1107
     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1108
     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1109
     *                                 SQL, and 1=>is the datatype
1110
     * @throws EE_Error
1111
     * @return string
1112
     */
1113
    private function _construct_select_from_input($columns_to_select)
1114
    {
1115
        if (is_array($columns_to_select)) {
1116
            $select_sql_array = array();
1117
            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1118
                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1119
                    throw new EE_Error(
1120
                        sprintf(
1121
                            __(
1122
                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1123
                                "event_espresso"
1124
                            ),
1125
                            $selection_and_datatype,
1126
                            $alias
1127
                        )
1128
                    );
1129
                }
1130
                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1131
                    throw new EE_Error(
1132
                        sprintf(
1133
                            __(
1134
                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1135
                                "event_espresso"
1136
                            ),
1137
                            $selection_and_datatype[1],
1138
                            $selection_and_datatype[0],
1139
                            $alias,
1140
                            implode(",", $this->_valid_wpdb_data_types)
1141
                        )
1142
                    );
1143
                }
1144
                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1145
            }
1146
            $columns_to_select_string = implode(", ", $select_sql_array);
1147
        } else {
1148
            $columns_to_select_string = $columns_to_select;
1149
        }
1150
        return $columns_to_select_string;
1151
    }
1152
1153
1154
1155
    /**
1156
     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1157
     *
1158
     * @return string
1159
     * @throws EE_Error
1160
     */
1161
    public function primary_key_name()
1162
    {
1163
        return $this->get_primary_key_field()->get_name();
1164
    }
1165
1166
1167
1168
    /**
1169
     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1170
     * If there is no primary key on this model, $id is treated as primary key string
1171
     *
1172
     * @param mixed $id int or string, depending on the type of the model's primary key
1173
     * @return EE_Base_Class
1174
     */
1175
    public function get_one_by_ID($id)
1176
    {
1177
        if ($this->get_from_entity_map($id)) {
1178
            return $this->get_from_entity_map($id);
1179
        }
1180
        return $this->get_one(
1181
            $this->alter_query_params_to_restrict_by_ID(
1182
                $id,
1183
                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1184
            )
1185
        );
1186
    }
1187
1188
1189
1190
    /**
1191
     * Alters query parameters to only get items with this ID are returned.
1192
     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1193
     * or could just be a simple primary key ID
1194
     *
1195
     * @param int   $id
1196
     * @param array $query_params
1197
     * @return array of normal query params, @see EEM_Base::get_all
1198
     * @throws EE_Error
1199
     */
1200
    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1201
    {
1202
        if (! isset($query_params[0])) {
1203
            $query_params[0] = array();
1204
        }
1205
        $conditions_from_id = $this->parse_index_primary_key_string($id);
1206
        if ($conditions_from_id === null) {
1207
            $query_params[0][$this->primary_key_name()] = $id;
1208
        } else {
1209
            //no primary key, so the $id must be from the get_index_primary_key_string()
1210
            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1211
        }
1212
        return $query_params;
1213
    }
1214
1215
1216
1217
    /**
1218
     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1219
     * array. If no item is found, null is returned.
1220
     *
1221
     * @param array $query_params like EEM_Base's $query_params variable.
1222
     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1223
     * @throws EE_Error
1224
     */
1225 View Code Duplication
    public function get_one($query_params = array())
1226
    {
1227
        if (! is_array($query_params)) {
1228
            EE_Error::doing_it_wrong('EEM_Base::get_one',
1229
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1230
                    gettype($query_params)), '4.6.0');
1231
            $query_params = array();
1232
        }
1233
        $query_params['limit'] = 1;
1234
        $items = $this->get_all($query_params);
1235
        if (empty($items)) {
1236
            return null;
1237
        }
1238
        return array_shift($items);
1239
    }
1240
1241
1242
1243
    /**
1244
     * Returns the next x number of items in sequence from the given value as
1245
     * found in the database matching the given query conditions.
1246
     *
1247
     * @param mixed $current_field_value    Value used for the reference point.
1248
     * @param null  $field_to_order_by      What field is used for the
1249
     *                                      reference point.
1250
     * @param int   $limit                  How many to return.
1251
     * @param array $query_params           Extra conditions on the query.
1252
     * @param null  $columns_to_select      If left null, then an array of
1253
     *                                      EE_Base_Class objects is returned,
1254
     *                                      otherwise you can indicate just the
1255
     *                                      columns you want returned.
1256
     * @return EE_Base_Class[]|array
1257
     * @throws EE_Error
1258
     */
1259
    public function next_x(
1260
        $current_field_value,
1261
        $field_to_order_by = null,
1262
        $limit = 1,
1263
        $query_params = array(),
1264
        $columns_to_select = null
1265
    ) {
1266
        return $this->_get_consecutive(
1267
            $current_field_value,
1268
            '>',
1269
            $field_to_order_by,
1270
            $limit,
1271
            $query_params,
1272
            $columns_to_select
1273
        );
1274
    }
1275
1276
1277
1278
    /**
1279
     * Returns the previous x number of items in sequence from the given value
1280
     * as found in the database matching the given query conditions.
1281
     *
1282
     * @param mixed $current_field_value    Value used for the reference point.
1283
     * @param null  $field_to_order_by      What field is used for the
1284
     *                                      reference point.
1285
     * @param int   $limit                  How many to return.
1286
     * @param array $query_params           Extra conditions on the query.
1287
     * @param null  $columns_to_select      If left null, then an array of
1288
     *                                      EE_Base_Class objects is returned,
1289
     *                                      otherwise you can indicate just the
1290
     *                                      columns you want returned.
1291
     * @return EE_Base_Class[]|array
1292
     * @throws EE_Error
1293
     */
1294
    public function previous_x(
1295
        $current_field_value,
1296
        $field_to_order_by = null,
1297
        $limit = 1,
1298
        $query_params = array(),
1299
        $columns_to_select = null
1300
    ) {
1301
        return $this->_get_consecutive(
1302
            $current_field_value,
1303
            '<',
1304
            $field_to_order_by,
1305
            $limit,
1306
            $query_params,
1307
            $columns_to_select
1308
        );
1309
    }
1310
1311
1312
1313
    /**
1314
     * Returns the next item in sequence from the given value as found in the
1315
     * database matching the given query conditions.
1316
     *
1317
     * @param mixed $current_field_value    Value used for the reference point.
1318
     * @param null  $field_to_order_by      What field is used for the
1319
     *                                      reference point.
1320
     * @param array $query_params           Extra conditions on the query.
1321
     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1322
     *                                      object is returned, otherwise you
1323
     *                                      can indicate just the columns you
1324
     *                                      want and a single array indexed by
1325
     *                                      the columns will be returned.
1326
     * @return EE_Base_Class|null|array()
1327
     * @throws EE_Error
1328
     */
1329 View Code Duplication
    public function next(
1330
        $current_field_value,
1331
        $field_to_order_by = null,
1332
        $query_params = array(),
1333
        $columns_to_select = null
1334
    ) {
1335
        $results = $this->_get_consecutive(
1336
            $current_field_value,
1337
            '>',
1338
            $field_to_order_by,
1339
            1,
1340
            $query_params,
1341
            $columns_to_select
1342
        );
1343
        return empty($results) ? null : reset($results);
1344
    }
1345
1346
1347
1348
    /**
1349
     * Returns the previous item in sequence from the given value as found in
1350
     * the database matching the given query conditions.
1351
     *
1352
     * @param mixed $current_field_value    Value used for the reference point.
1353
     * @param null  $field_to_order_by      What field is used for the
1354
     *                                      reference point.
1355
     * @param array $query_params           Extra conditions on the query.
1356
     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1357
     *                                      object is returned, otherwise you
1358
     *                                      can indicate just the columns you
1359
     *                                      want and a single array indexed by
1360
     *                                      the columns will be returned.
1361
     * @return EE_Base_Class|null|array()
1362
     * @throws EE_Error
1363
     */
1364 View Code Duplication
    public function previous(
1365
        $current_field_value,
1366
        $field_to_order_by = null,
1367
        $query_params = array(),
1368
        $columns_to_select = null
1369
    ) {
1370
        $results = $this->_get_consecutive(
1371
            $current_field_value,
1372
            '<',
1373
            $field_to_order_by,
1374
            1,
1375
            $query_params,
1376
            $columns_to_select
1377
        );
1378
        return empty($results) ? null : reset($results);
1379
    }
1380
1381
1382
1383
    /**
1384
     * Returns the a consecutive number of items in sequence from the given
1385
     * value as found in the database matching the given query conditions.
1386
     *
1387
     * @param mixed  $current_field_value   Value used for the reference point.
1388
     * @param string $operand               What operand is used for the sequence.
1389
     * @param string $field_to_order_by     What field is used for the reference point.
1390
     * @param int    $limit                 How many to return.
1391
     * @param array  $query_params          Extra conditions on the query.
1392
     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1393
     *                                      otherwise you can indicate just the columns you want returned.
1394
     * @return EE_Base_Class[]|array
1395
     * @throws EE_Error
1396
     */
1397
    protected function _get_consecutive(
1398
        $current_field_value,
1399
        $operand = '>',
1400
        $field_to_order_by = null,
1401
        $limit = 1,
1402
        $query_params = array(),
1403
        $columns_to_select = null
1404
    ) {
1405
        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1406
        if (empty($field_to_order_by)) {
1407
            if ($this->has_primary_key_field()) {
1408
                $field_to_order_by = $this->get_primary_key_field()->get_name();
1409
            } else {
1410
                if (WP_DEBUG) {
1411
                    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).',
1412
                        'event_espresso'));
1413
                }
1414
                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1415
                return array();
1416
            }
1417
        }
1418
        if (! is_array($query_params)) {
1419
            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1420
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1421
                    gettype($query_params)), '4.6.0');
1422
            $query_params = array();
1423
        }
1424
        //let's add the where query param for consecutive look up.
1425
        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1426
        $query_params['limit'] = $limit;
1427
        //set direction
1428
        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1429
        $query_params['order_by'] = $operand === '>'
1430
            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1431
            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1432
        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1433
        if (empty($columns_to_select)) {
1434
            return $this->get_all($query_params);
1435
        }
1436
        //getting just the fields
1437
        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1438
    }
1439
1440
1441
1442
    /**
1443
     * This sets the _timezone property after model object has been instantiated.
1444
     *
1445
     * @param null | string $timezone valid PHP DateTimeZone timezone string
1446
     */
1447
    public function set_timezone($timezone)
1448
    {
1449
        if ($timezone !== null) {
1450
            $this->_timezone = $timezone;
1451
        }
1452
        //note we need to loop through relations and set the timezone on those objects as well.
1453
        foreach ($this->_model_relations as $relation) {
1454
            $relation->set_timezone($timezone);
1455
        }
1456
        //and finally we do the same for any datetime fields
1457
        foreach ($this->_fields as $field) {
1458
            if ($field instanceof EE_Datetime_Field) {
1459
                $field->set_timezone($timezone);
1460
            }
1461
        }
1462
    }
1463
1464
1465
1466
    /**
1467
     * This just returns whatever is set for the current timezone.
1468
     *
1469
     * @access public
1470
     * @return string
1471
     */
1472
    public function get_timezone()
1473
    {
1474
        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1475
        if (empty($this->_timezone)) {
1476
            foreach ($this->_fields as $field) {
1477
                if ($field instanceof EE_Datetime_Field) {
1478
                    $this->set_timezone($field->get_timezone());
1479
                    break;
1480
                }
1481
            }
1482
        }
1483
        //if timezone STILL empty then return the default timezone for the site.
1484
        if (empty($this->_timezone)) {
1485
            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1486
        }
1487
        return $this->_timezone;
1488
    }
1489
1490
1491
1492
    /**
1493
     * This returns the date formats set for the given field name and also ensures that
1494
     * $this->_timezone property is set correctly.
1495
     *
1496
     * @since 4.6.x
1497
     * @param string $field_name The name of the field the formats are being retrieved for.
1498
     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1499
     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1500
     * @return array formats in an array with the date format first, and the time format last.
1501
     */
1502
    public function get_formats_for($field_name, $pretty = false)
1503
    {
1504
        $field_settings = $this->field_settings_for($field_name);
1505
        //if not a valid EE_Datetime_Field then throw error
1506
        if (! $field_settings instanceof EE_Datetime_Field) {
1507
            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.',
1508
                'event_espresso'), $field_name));
1509
        }
1510
        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1511
        //the field.
1512
        $this->_timezone = $field_settings->get_timezone();
1513
        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1514
    }
1515
1516
1517
1518
    /**
1519
     * This returns the current time in a format setup for a query on this model.
1520
     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1521
     * it will return:
1522
     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1523
     *  NOW
1524
     *  - or a unix timestamp (equivalent to time())
1525
     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1526
     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1527
     * the time returned to be the current time down to the exact second, set $timestamp to true.
1528
     * @since 4.6.x
1529
     * @param string $field_name       The field the current time is needed for.
1530
     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1531
     *                                 formatted string matching the set format for the field in the set timezone will
1532
     *                                 be returned.
1533
     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1534
     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1535
     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1536
     *                                 exception is triggered.
1537
     */
1538
    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1539
    {
1540
        $formats = $this->get_formats_for($field_name);
1541
        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1542
        if ($timestamp) {
1543
            return $DateTime->format('U');
1544
        }
1545
        //not returning timestamp, so return formatted string in timezone.
1546
        switch ($what) {
1547
            case 'time' :
1548
                return $DateTime->format($formats[1]);
1549
                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...
1550
            case 'date' :
1551
                return $DateTime->format($formats[0]);
1552
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

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

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

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

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

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

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

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

Loading history...
1556
        }
1557
    }
1558
1559
1560
1561
    /**
1562
     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1563
     * for the model are.  Returns a DateTime object.
1564
     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1565
     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1566
     * ignored.
1567
     *
1568
     * @param string $field_name      The field being setup.
1569
     * @param string $timestring      The date time string being used.
1570
     * @param string $incoming_format The format for the time string.
1571
     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1572
     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1573
     *                                format is
1574
     *                                'U', this is ignored.
1575
     * @return DateTime
1576
     * @throws EE_Error
1577
     */
1578
    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1579
    {
1580
        //just using this to ensure the timezone is set correctly internally
1581
        $this->get_formats_for($field_name);
1582
        //load EEH_DTT_Helper
1583
        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1584
        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1585
        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1586
    }
1587
1588
1589
1590
    /**
1591
     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1592
     *
1593
     * @return EE_Table_Base[]
1594
     */
1595
    public function get_tables()
1596
    {
1597
        return $this->_tables;
1598
    }
1599
1600
1601
1602
    /**
1603
     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1604
     * also updates all the model objects, where the criteria expressed in $query_params are met..
1605
     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1606
     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1607
     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1608
     * model object with EVT_ID = 1
1609
     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1610
     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1611
     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1612
     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1613
     * are not specified)
1614
     *
1615
     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1616
     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1617
     *                                         are to be serialized. Basically, the values are what you'd expect to be
1618
     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1619
     *                                         we wanted to update only the TXN_details on any Transactions where its
1620
     *                                         ID=34, we'd use this method as follows:
1621
     *                                         EEM_Transaction::instance()->update(
1622
     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1623
     *                                         array(array('TXN_ID'=>34)));
1624
     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1625
     *                                         in client code into what's expected to be stored on each field. Eg,
1626
     *                                         consider updating Question's QST_admin_label field is of type
1627
     *                                         Simple_HTML. If you use this function to update that field to $new_value
1628
     *                                         = (note replace 8's with appropriate opening and closing tags in the
1629
     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1630
     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1631
     *                                         TRUE, it is assumed that you've already called
1632
     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1633
     *                                         malicious javascript. However, if
1634
     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1635
     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1636
     *                                         and every other field, before insertion. We provide this parameter
1637
     *                                         because model objects perform their prepare_for_set function on all
1638
     *                                         their values, and so don't need to be called again (and in many cases,
1639
     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1640
     *                                         prepare_for_set method...)
1641
     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1642
     *                                         in this model's entity map according to $fields_n_values that match
1643
     *                                         $query_params. This obviously has some overhead, so you can disable it
1644
     *                                         by setting this to FALSE, but be aware that model objects being used
1645
     *                                         could get out-of-sync with the database
1646
     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1647
     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1648
     *                                         bad)
1649
     * @throws EE_Error
1650
     */
1651
    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1652
    {
1653
        if (! is_array($query_params)) {
1654
            EE_Error::doing_it_wrong('EEM_Base::update',
1655
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1656
                    gettype($query_params)), '4.6.0');
1657
            $query_params = array();
1658
        }
1659
        /**
1660
         * Action called before a model update call has been made.
1661
         *
1662
         * @param EEM_Base $model
1663
         * @param array    $fields_n_values the updated fields and their new values
1664
         * @param array    $query_params    @see EEM_Base::get_all()
1665
         */
1666
        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1667
        /**
1668
         * Filters the fields about to be updated given the query parameters. You can provide the
1669
         * $query_params to $this->get_all() to find exactly which records will be updated
1670
         *
1671
         * @param array    $fields_n_values fields and their new values
1672
         * @param EEM_Base $model           the model being queried
1673
         * @param array    $query_params    see EEM_Base::get_all()
1674
         */
1675
        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1676
            $query_params);
1677
        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1678
        //to do that, for each table, verify that it's PK isn't null.
1679
        $tables = $this->get_tables();
1680
        //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
1681
        //NOTE: we should make this code more efficient by NOT querying twice
1682
        //before the real update, but that needs to first go through ALPHA testing
1683
        //as it's dangerous. says Mike August 8 2014
1684
        //we want to make sure the default_where strategy is ignored
1685
        $this->_ignore_where_strategy = true;
1686
        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1687
        foreach ($wpdb_select_results as $wpdb_result) {
1688
            // type cast stdClass as array
1689
            $wpdb_result = (array)$wpdb_result;
1690
            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1691
            if ($this->has_primary_key_field()) {
1692
                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1693
            } else {
1694
                //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)
1695
                $main_table_pk_value = null;
1696
            }
1697
            //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
1698
            //and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1699
            if (count($tables) > 1) {
1700
                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1701
                //in that table, and so we'll want to insert one
1702
                foreach ($tables as $table_obj) {
1703
                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1704
                    //if there is no private key for this table on the results, it means there's no entry
1705
                    //in this table, right? so insert a row in the current table, using any fields available
1706
                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1707
                           && $wpdb_result[$this_table_pk_column])
1708
                    ) {
1709
                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1710
                            $main_table_pk_value);
1711
                        //if we died here, report the error
1712
                        if (! $success) {
1713
                            return false;
1714
                        }
1715
                    }
1716
                }
1717
            }
1718
            //				//and now check that if we have cached any models by that ID on the model, that
1719
            //				//they also get updated properly
1720
            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1721
            //				if( $model_object ){
1722
            //					foreach( $fields_n_values as $field => $value ){
1723
            //						$model_object->set($field, $value);
1724
            //let's make sure default_where strategy is followed now
1725
            $this->_ignore_where_strategy = false;
1726
        }
1727
        //if we want to keep model objects in sync, AND
1728
        //if this wasn't called from a model object (to update itself)
1729
        //then we want to make sure we keep all the existing
1730
        //model objects in sync with the db
1731
        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1732
            if ($this->has_primary_key_field()) {
1733
                $model_objs_affected_ids = $this->get_col($query_params);
1734
            } else {
1735
                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1736
                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1737
                $model_objs_affected_ids = array();
1738
                foreach ($models_affected_key_columns as $row) {
1739
                    $combined_index_key = $this->get_index_primary_key_string($row);
1740
                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1741
                }
1742
            }
1743
            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...
1744
                //wait wait wait- if nothing was affected let's stop here
1745
                return 0;
1746
            }
1747
            foreach ($model_objs_affected_ids as $id) {
1748
                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1749
                if ($model_obj_in_entity_map) {
1750
                    foreach ($fields_n_values as $field => $new_value) {
1751
                        $model_obj_in_entity_map->set($field, $new_value);
1752
                    }
1753
                }
1754
            }
1755
            //if there is a primary key on this model, we can now do a slight optimization
1756
            if ($this->has_primary_key_field()) {
1757
                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1758
                $query_params = array(
1759
                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1760
                    'limit'                    => count($model_objs_affected_ids),
1761
                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1762
                );
1763
            }
1764
        }
1765
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1766
        $SQL = "UPDATE "
1767
               . $model_query_info->get_full_join_sql()
1768
               . " SET "
1769
               . $this->_construct_update_sql($fields_n_values)
1770
               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1771
        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1772
        /**
1773
         * Action called after a model update call has been made.
1774
         *
1775
         * @param EEM_Base $model
1776
         * @param array    $fields_n_values the updated fields and their new values
1777
         * @param array    $query_params    @see EEM_Base::get_all()
1778
         * @param int      $rows_affected
1779
         */
1780
        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1781
        return $rows_affected;//how many supposedly got updated
1782
    }
1783
1784
1785
1786
    /**
1787
     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1788
     * are teh values of the field specified (or by default the primary key field)
1789
     * that matched the query params. Note that you should pass the name of the
1790
     * model FIELD, not the database table's column name.
1791
     *
1792
     * @param array  $query_params @see EEM_Base::get_all()
1793
     * @param string $field_to_select
1794
     * @return array just like $wpdb->get_col()
1795
     * @throws EE_Error
1796
     */
1797
    public function get_col($query_params = array(), $field_to_select = null)
1798
    {
1799
        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...
1800
            $field = $this->field_settings_for($field_to_select);
1801
        } elseif ($this->has_primary_key_field()) {
1802
            $field = $this->get_primary_key_field();
1803
        } else {
1804
            //no primary key, just grab the first column
1805
            $field = reset($this->field_settings());
1806
        }
1807
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1808
        $select_expressions = $field->get_qualified_column();
1809
        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1810
        return $this->_do_wpdb_query('get_col', array($SQL));
1811
    }
1812
1813
1814
1815
    /**
1816
     * Returns a single column value for a single row from the database
1817
     *
1818
     * @param array  $query_params    @see EEM_Base::get_all()
1819
     * @param string $field_to_select @see EEM_Base::get_col()
1820
     * @return string
1821
     * @throws EE_Error
1822
     */
1823
    public function get_var($query_params = array(), $field_to_select = null)
1824
    {
1825
        $query_params['limit'] = 1;
1826
        $col = $this->get_col($query_params, $field_to_select);
1827
        if (! empty($col)) {
1828
            return reset($col);
1829
        }
1830
        return null;
1831
    }
1832
1833
1834
1835
    /**
1836
     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1837
     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1838
     * injection, but currently no further filtering is done
1839
     *
1840
     * @global      $wpdb
1841
     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1842
     *                               be updated to in the DB
1843
     * @return string of SQL
1844
     * @throws EE_Error
1845
     */
1846
    public function _construct_update_sql($fields_n_values)
1847
    {
1848
        /** @type WPDB $wpdb */
1849
        global $wpdb;
1850
        $cols_n_values = array();
1851
        foreach ($fields_n_values as $field_name => $value) {
1852
            $field_obj = $this->field_settings_for($field_name);
1853
            //if the value is NULL, we want to assign the value to that.
1854
            //wpdb->prepare doesn't really handle that properly
1855
            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1856
            $value_sql = $prepared_value === null ? 'NULL'
1857
                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1858
            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1859
        }
1860
        return implode(",", $cols_n_values);
1861
    }
1862
1863
1864
1865
    /**
1866
     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1867
     * Performs a HARD delete, meaning the database row should always be removed,
1868
     * not just have a flag field on it switched
1869
     * Wrapper for EEM_Base::delete_permanently()
1870
     *
1871
     * @param mixed $id
1872
     * @return boolean whether the row got deleted or not
1873
     * @throws EE_Error
1874
     */
1875
    public function delete_permanently_by_ID($id)
1876
    {
1877
        return $this->delete_permanently(
1878
            array(
1879
                array($this->get_primary_key_field()->get_name() => $id),
1880
                'limit' => 1,
1881
            )
1882
        );
1883
    }
1884
1885
1886
1887
    /**
1888
     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1889
     * Wrapper for EEM_Base::delete()
1890
     *
1891
     * @param mixed $id
1892
     * @return boolean whether the row got deleted or not
1893
     * @throws EE_Error
1894
     */
1895
    public function delete_by_ID($id)
1896
    {
1897
        return $this->delete(
1898
            array(
1899
                array($this->get_primary_key_field()->get_name() => $id),
1900
                'limit' => 1,
1901
            )
1902
        );
1903
    }
1904
1905
1906
1907
    /**
1908
     * Identical to delete_permanently, but does a "soft" delete if possible,
1909
     * meaning if the model has a field that indicates its been "trashed" or
1910
     * "soft deleted", we will just set that instead of actually deleting the rows.
1911
     *
1912
     * @see EEM_Base::delete_permanently
1913
     * @param array   $query_params
1914
     * @param boolean $allow_blocking
1915
     * @return int how many rows got deleted
1916
     * @throws EE_Error
1917
     */
1918
    public function delete($query_params, $allow_blocking = true)
1919
    {
1920
        return $this->delete_permanently($query_params, $allow_blocking);
1921
    }
1922
1923
1924
1925
    /**
1926
     * Deletes the model objects that meet the query params. Note: this method is overridden
1927
     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1928
     * as archived, not actually deleted
1929
     *
1930
     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1931
     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1932
     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1933
     *                                deletes regardless of other objects which may depend on it. Its generally
1934
     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1935
     *                                DB
1936
     * @return int how many rows got deleted
1937
     * @throws EE_Error
1938
     */
1939
    public function delete_permanently($query_params, $allow_blocking = true)
1940
    {
1941
        /**
1942
         * Action called just before performing a real deletion query. You can use the
1943
         * model and its $query_params to find exactly which items will be deleted
1944
         *
1945
         * @param EEM_Base $model
1946
         * @param array    $query_params   @see EEM_Base::get_all()
1947
         * @param boolean  $allow_blocking whether or not to allow related model objects
1948
         *                                 to block (prevent) this deletion
1949
         */
1950
        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1951
        //some MySQL databases may be running safe mode, which may restrict
1952
        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1953
        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1954
        //to delete them
1955
        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1956
        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1957
        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1958
            $columns_and_ids_for_deleting
1959
        );
1960
        /**
1961
         * Allows client code to act on the items being deleted before the query is actually executed.
1962
         *
1963
         * @param EEM_Base $this  The model instance being acted on.
1964
         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1965
         * @param bool     $allow_blocking @see param description in method phpdoc block.
1966
         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1967
         *                                                  derived from the incoming query parameters.
1968
         *                                                  @see details on the structure of this array in the phpdocs
1969
         *                                                  for the `_get_ids_for_delete_method`
1970
         *
1971
         */
1972
        do_action('AHEE__EEM_Base__delete__before_query',
1973
            $this,
1974
            $query_params,
1975
            $allow_blocking,
1976
            $columns_and_ids_for_deleting
1977
        );
1978
        if ($deletion_where_query_part) {
1979
            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1980
            $table_aliases = array_keys($this->_tables);
1981
            $SQL = "DELETE "
1982
                   . implode(", ", $table_aliases)
1983
                   . " FROM "
1984
                   . $model_query_info->get_full_join_sql()
1985
                   . " WHERE "
1986
                   . $deletion_where_query_part;
1987
            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1988
        } else {
1989
            $rows_deleted = 0;
1990
        }
1991
1992
        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1993
        //there was no error with the delete query.
1994
        if ($this->has_primary_key_field()
1995
            && $rows_deleted !== false
1996
            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1997
        ) {
1998
            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1999
            foreach ($ids_for_removal as $id) {
2000 View Code Duplication
                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2001
                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2002
                }
2003
            }
2004
2005
            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2006
            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2007
            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2008
            // (although it is possible).
2009
            //Note this can be skipped by using the provided filter and returning false.
2010
            if (apply_filters(
2011
                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2012
                ! $this instanceof EEM_Extra_Meta,
2013
                $this
2014
            )) {
2015
                EEM_Extra_Meta::instance()->delete_permanently(array(
2016
                    0 => array(
2017
                        'EXM_type' => $this->get_this_model_name(),
2018
                        'OBJ_ID'   => array(
2019
                            'IN',
2020
                            $ids_for_removal
2021
                        )
2022
                    )
2023
                ));
2024
            }
2025
        }
2026
2027
        /**
2028
         * Action called just after performing a real deletion query. Although at this point the
2029
         * items should have been deleted
2030
         *
2031
         * @param EEM_Base $model
2032
         * @param array    $query_params @see EEM_Base::get_all()
2033
         * @param int      $rows_deleted
2034
         */
2035
        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2036
        return $rows_deleted;//how many supposedly got deleted
2037
    }
2038
2039
2040
2041
    /**
2042
     * Checks all the relations that throw error messages when there are blocking related objects
2043
     * for related model objects. If there are any related model objects on those relations,
2044
     * adds an EE_Error, and return true
2045
     *
2046
     * @param EE_Base_Class|int $this_model_obj_or_id
2047
     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2048
     *                                                 should be ignored when determining whether there are related
2049
     *                                                 model objects which block this model object's deletion. Useful
2050
     *                                                 if you know A is related to B and are considering deleting A,
2051
     *                                                 but want to see if A has any other objects blocking its deletion
2052
     *                                                 before removing the relation between A and B
2053
     * @return boolean
2054
     * @throws EE_Error
2055
     */
2056
    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2057
    {
2058
        //first, if $ignore_this_model_obj was supplied, get its model
2059
        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2060
            $ignored_model = $ignore_this_model_obj->get_model();
2061
        } else {
2062
            $ignored_model = null;
2063
        }
2064
        //now check all the relations of $this_model_obj_or_id and see if there
2065
        //are any related model objects blocking it?
2066
        $is_blocked = false;
2067
        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2068
            if ($relation_obj->block_delete_if_related_models_exist()) {
2069
                //if $ignore_this_model_obj was supplied, then for the query
2070
                //on that model needs to be told to ignore $ignore_this_model_obj
2071
                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2072
                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2073
                        array(
2074
                            $ignored_model->get_primary_key_field()->get_name() => array(
2075
                                '!=',
2076
                                $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...
2077
                            ),
2078
                        ),
2079
                    ));
2080
                } else {
2081
                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2082
                }
2083
                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...
2084
                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2085
                    $is_blocked = true;
2086
                }
2087
            }
2088
        }
2089
        return $is_blocked;
2090
    }
2091
2092
2093
    /**
2094
     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2095
     * @param array $row_results_for_deleting
2096
     * @param bool  $allow_blocking
2097
     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2098
     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2099
     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2100
     *                 deleted. Example:
2101
     *                      array('Event.EVT_ID' => array( 1,2,3))
2102
     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2103
     *                 where each element is a group of columns and values that get deleted. Example:
2104
     *                      array(
2105
     *                          0 => array(
2106
     *                              'Term_Relationship.object_id' => 1
2107
     *                              'Term_Relationship.term_taxonomy_id' => 5
2108
     *                          ),
2109
     *                          1 => array(
2110
     *                              'Term_Relationship.object_id' => 1
2111
     *                              'Term_Relationship.term_taxonomy_id' => 6
2112
     *                          )
2113
     *                      )
2114
     * @throws EE_Error
2115
     */
2116
    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2117
    {
2118
        $ids_to_delete_indexed_by_column = array();
2119
        if ($this->has_primary_key_field()) {
2120
            $primary_table = $this->_get_main_table();
2121
            $other_tables = $this->_get_other_tables();
0 ignored issues
show
Unused Code introduced by
$other_tables is not used, you could remove the assignment.

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

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

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

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

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

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

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

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

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

Loading history...
2123
            foreach ($row_results_for_deleting as $item_to_delete) {
2124
                //before we mark this item for deletion,
2125
                //make sure there's no related entities blocking its deletion (if we're checking)
2126
                if (
2127
                    $allow_blocking
2128
                    && $this->delete_is_blocked_by_related_models(
2129
                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2130
                    )
2131
                ) {
2132
                    continue;
2133
                }
2134
                //primary table deletes
2135
                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2136
                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2137
                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2138
                }
2139
            }
2140
        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2141
            $fields = $this->get_combined_primary_key_fields();
2142
            foreach ($row_results_for_deleting as $item_to_delete) {
2143
                $ids_to_delete_indexed_by_column_for_row = array();
2144
                foreach ($fields as $cpk_field) {
2145
                    if ($cpk_field instanceof EE_Model_Field_Base) {
2146
                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2147
                            $item_to_delete[$cpk_field->get_qualified_column()];
2148
                    }
2149
                }
2150
                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2151
            }
2152
        } else {
2153
            //so there's no primary key and no combined key...
2154
            //sorry, can't help you
2155
            throw new EE_Error(
2156
                sprintf(
2157
                    __(
2158
                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2159
                        "event_espresso"
2160
                    ), get_class($this)
2161
                )
2162
            );
2163
        }
2164
        return $ids_to_delete_indexed_by_column;
2165
    }
2166
2167
2168
    /**
2169
     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2170
     * the corresponding query_part for the query performing the delete.
2171
     *
2172
     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2173
     * @return string
2174
     * @throws EE_Error
2175
     */
2176
    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2177
        $query_part = '';
2178
        if (empty($ids_to_delete_indexed_by_column)) {
2179
            return $query_part;
2180
        } elseif ($this->has_primary_key_field()) {
2181
            $query = array();
2182
            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2183
                //make sure we have unique $ids
2184
                $ids = array_unique($ids);
2185
                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2186
            }
2187
            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2188
        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2189
            $ways_to_identify_a_row = array();
2190
            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2191
                $values_for_each_combined_primary_key_for_a_row = array();
2192
                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2193
                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2194
                }
2195
                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2196
            }
2197
            $query_part = implode(' OR ', $ways_to_identify_a_row);
2198
        }
2199
        return $query_part;
2200
    }
2201
2202
2203
2204
2205
    /**
2206
     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2207
     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2208
     * column
2209
     *
2210
     * @param array  $query_params   like EEM_Base::get_all's
2211
     * @param string $field_to_count field on model to count by (not column name)
2212
     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2213
     *                               that by the setting $distinct to TRUE;
2214
     * @return int
2215
     * @throws EE_Error
2216
     */
2217
    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2218
    {
2219
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2220
        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...
2221
            $field_obj = $this->field_settings_for($field_to_count);
2222
            $column_to_count = $field_obj->get_qualified_column();
2223
        } elseif ($this->has_primary_key_field()) {
2224
            $pk_field_obj = $this->get_primary_key_field();
2225
            $column_to_count = $pk_field_obj->get_qualified_column();
2226
        } else {
2227
            //there's no primary key
2228
            //if we're counting distinct items, and there's no primary key,
2229
            //we need to list out the columns for distinction;
2230
            //otherwise we can just use star
2231
            if ($distinct) {
2232
                $columns_to_use = array();
2233
                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2234
                    $columns_to_use[] = $field_obj->get_qualified_column();
2235
                }
2236
                $column_to_count = implode(',', $columns_to_use);
2237
            } else {
2238
                $column_to_count = '*';
2239
            }
2240
        }
2241
        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2242
        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2243
        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2244
    }
2245
2246
2247
2248
    /**
2249
     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2250
     *
2251
     * @param array  $query_params like EEM_Base::get_all
2252
     * @param string $field_to_sum name of field (array key in $_fields array)
2253
     * @return float
2254
     * @throws EE_Error
2255
     */
2256
    public function sum($query_params, $field_to_sum = null)
2257
    {
2258
        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2259
        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...
2260
            $field_obj = $this->field_settings_for($field_to_sum);
2261
        } else {
2262
            $field_obj = $this->get_primary_key_field();
2263
        }
2264
        $column_to_count = $field_obj->get_qualified_column();
2265
        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2266
        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2267
        $data_type = $field_obj->get_wpdb_data_type();
2268
        if ($data_type === '%d' || $data_type === '%s') {
2269
            return (float)$return_value;
2270
        }
2271
        //must be %f
2272
        return (float)$return_value;
2273
    }
2274
2275
2276
2277
    /**
2278
     * Just calls the specified method on $wpdb with the given arguments
2279
     * Consolidates a little extra error handling code
2280
     *
2281
     * @param string $wpdb_method
2282
     * @param array  $arguments_to_provide
2283
     * @throws EE_Error
2284
     * @global wpdb  $wpdb
2285
     * @return mixed
2286
     */
2287
    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2288
    {
2289
        //if we're in maintenance mode level 2, DON'T run any queries
2290
        //because level 2 indicates the database needs updating and
2291
        //is probably out of sync with the code
2292
        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2293
            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.",
2294
                "event_espresso")));
2295
        }
2296
        /** @type WPDB $wpdb */
2297
        global $wpdb;
2298 View Code Duplication
        if (! method_exists($wpdb, $wpdb_method)) {
2299
            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2300
                'event_espresso'), $wpdb_method));
2301
        }
2302
        if (WP_DEBUG) {
2303
            $old_show_errors_value = $wpdb->show_errors;
2304
            $wpdb->show_errors(false);
2305
        }
2306
        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2307
        $this->show_db_query_if_previously_requested($wpdb->last_query);
2308
        if (WP_DEBUG) {
2309
            $wpdb->show_errors($old_show_errors_value);
2310
            if (! empty($wpdb->last_error)) {
2311
                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2312
            }
2313
            if ($result === false) {
2314
                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"',
2315
                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2316
            }
2317
        } elseif ($result === false) {
2318
            EE_Error::add_error(
2319
                sprintf(
2320
                    __('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"',
2321
                        'event_espresso'),
2322
                    $wpdb_method,
2323
                    var_export($arguments_to_provide, true),
2324
                    $wpdb->last_error
2325
                ),
2326
                __FILE__,
2327
                __FUNCTION__,
2328
                __LINE__
2329
            );
2330
        }
2331
        return $result;
2332
    }
2333
2334
2335
2336
    /**
2337
     * Attempts to run the indicated WPDB method with the provided arguments,
2338
     * and if there's an error tries to verify the DB is correct. Uses
2339
     * the static property EEM_Base::$_db_verification_level to determine whether
2340
     * we should try to fix the EE core db, the addons, or just give up
2341
     *
2342
     * @param string $wpdb_method
2343
     * @param array  $arguments_to_provide
2344
     * @return mixed
2345
     */
2346
    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2347
    {
2348
        /** @type WPDB $wpdb */
2349
        global $wpdb;
2350
        $wpdb->last_error = null;
2351
        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2352
        // was there an error running the query? but we don't care on new activations
2353
        // (we're going to setup the DB anyway on new activations)
2354
        if (($result === false || ! empty($wpdb->last_error))
2355
            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2356
        ) {
2357
            switch (EEM_Base::$_db_verification_level) {
2358
                case EEM_Base::db_verified_none :
2359
                    // let's double-check core's DB
2360
                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2361
                    break;
2362
                case EEM_Base::db_verified_core :
2363
                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2364
                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2365
                    break;
2366
                case EEM_Base::db_verified_addons :
2367
                    // ummmm... you in trouble
2368
                    return $result;
2369
                    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...
2370
            }
2371
            if (! empty($error_message)) {
2372
                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2373
                trigger_error($error_message);
2374
            }
2375
            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2376
        }
2377
        return $result;
2378
    }
2379
2380
2381
2382
    /**
2383
     * Verifies the EE core database is up-to-date and records that we've done it on
2384
     * EEM_Base::$_db_verification_level
2385
     *
2386
     * @param string $wpdb_method
2387
     * @param array  $arguments_to_provide
2388
     * @return string
2389
     */
2390 View Code Duplication
    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2391
    {
2392
        /** @type WPDB $wpdb */
2393
        global $wpdb;
2394
        //ok remember that we've already attempted fixing the core db, in case the problem persists
2395
        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2396
        $error_message = sprintf(
2397
            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2398
                'event_espresso'),
2399
            $wpdb->last_error,
2400
            $wpdb_method,
2401
            wp_json_encode($arguments_to_provide)
2402
        );
2403
        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2404
        return $error_message;
2405
    }
2406
2407
2408
2409
    /**
2410
     * Verifies the EE addons' database is up-to-date and records that we've done it on
2411
     * EEM_Base::$_db_verification_level
2412
     *
2413
     * @param $wpdb_method
2414
     * @param $arguments_to_provide
2415
     * @return string
2416
     */
2417 View Code Duplication
    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2418
    {
2419
        /** @type WPDB $wpdb */
2420
        global $wpdb;
2421
        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2422
        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2423
        $error_message = sprintf(
2424
            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2425
                'event_espresso'),
2426
            $wpdb->last_error,
2427
            $wpdb_method,
2428
            wp_json_encode($arguments_to_provide)
2429
        );
2430
        EE_System::instance()->initialize_addons();
2431
        return $error_message;
2432
    }
2433
2434
2435
2436
    /**
2437
     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2438
     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2439
     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2440
     * ..."
2441
     *
2442
     * @param EE_Model_Query_Info_Carrier $model_query_info
2443
     * @return string
2444
     */
2445
    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2446
    {
2447
        return " FROM " . $model_query_info->get_full_join_sql() .
2448
               $model_query_info->get_where_sql() .
2449
               $model_query_info->get_group_by_sql() .
2450
               $model_query_info->get_having_sql() .
2451
               $model_query_info->get_order_by_sql() .
2452
               $model_query_info->get_limit_sql();
2453
    }
2454
2455
2456
2457
    /**
2458
     * Set to easily debug the next X queries ran from this model.
2459
     *
2460
     * @param int $count
2461
     */
2462
    public function show_next_x_db_queries($count = 1)
2463
    {
2464
        $this->_show_next_x_db_queries = $count;
2465
    }
2466
2467
2468
2469
    /**
2470
     * @param $sql_query
2471
     */
2472
    public function show_db_query_if_previously_requested($sql_query)
2473
    {
2474
        if ($this->_show_next_x_db_queries > 0) {
2475
            echo $sql_query;
2476
            $this->_show_next_x_db_queries--;
2477
        }
2478
    }
2479
2480
2481
2482
    /**
2483
     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2484
     * There are the 3 cases:
2485
     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2486
     * $otherModelObject has no ID, it is first saved.
2487
     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2488
     * has no ID, it is first saved.
2489
     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2490
     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2491
     * join table
2492
     *
2493
     * @param        EE_Base_Class                     /int $thisModelObject
2494
     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2495
     * @param string $relationName                     , key in EEM_Base::_relations
2496
     *                                                 an attendee to a group, you also want to specify which role they
2497
     *                                                 will have in that group. So you would use this parameter to
2498
     *                                                 specify array('role-column-name'=>'role-id')
2499
     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2500
     *                                                 to for relation to methods that allow you to further specify
2501
     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2502
     *                                                 only acceptable query_params is strict "col" => "value" pairs
2503
     *                                                 because these will be inserted in any new rows created as well.
2504
     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2505
     * @throws EE_Error
2506
     */
2507
    public function add_relationship_to(
2508
        $id_or_obj,
2509
        $other_model_id_or_obj,
2510
        $relationName,
2511
        $extra_join_model_fields_n_values = array()
2512
    ) {
2513
        $relation_obj = $this->related_settings_for($relationName);
2514
        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2515
    }
2516
2517
2518
2519
    /**
2520
     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2521
     * There are the 3 cases:
2522
     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2523
     * error
2524
     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2525
     * an error
2526
     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2527
     *
2528
     * @param        EE_Base_Class /int $id_or_obj
2529
     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2530
     * @param string $relationName key in EEM_Base::_relations
2531
     * @return boolean of success
2532
     * @throws EE_Error
2533
     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2534
     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2535
     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2536
     *                             because these will be inserted in any new rows created as well.
2537
     */
2538
    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2539
    {
2540
        $relation_obj = $this->related_settings_for($relationName);
2541
        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2542
    }
2543
2544
2545
2546
    /**
2547
     * @param mixed           $id_or_obj
2548
     * @param string          $relationName
2549
     * @param array           $where_query_params
2550
     * @param EE_Base_Class[] objects to which relations were removed
2551
     * @return \EE_Base_Class[]
2552
     * @throws EE_Error
2553
     */
2554
    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2555
    {
2556
        $relation_obj = $this->related_settings_for($relationName);
2557
        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2558
    }
2559
2560
2561
2562
    /**
2563
     * Gets all the related items of the specified $model_name, using $query_params.
2564
     * Note: by default, we remove the "default query params"
2565
     * because we want to get even deleted items etc.
2566
     *
2567
     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2568
     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2569
     * @param array  $query_params like EEM_Base::get_all
2570
     * @return EE_Base_Class[]
2571
     * @throws EE_Error
2572
     */
2573
    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2574
    {
2575
        $model_obj = $this->ensure_is_obj($id_or_obj);
2576
        $relation_settings = $this->related_settings_for($model_name);
2577
        return $relation_settings->get_all_related($model_obj, $query_params);
2578
    }
2579
2580
2581
2582
    /**
2583
     * Deletes all the model objects across the relation indicated by $model_name
2584
     * which are related to $id_or_obj which meet the criteria set in $query_params.
2585
     * However, if the model objects can't be deleted because of blocking related model objects, then
2586
     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2587
     *
2588
     * @param EE_Base_Class|int|string $id_or_obj
2589
     * @param string                   $model_name
2590
     * @param array                    $query_params
2591
     * @return int how many deleted
2592
     * @throws EE_Error
2593
     */
2594
    public function delete_related($id_or_obj, $model_name, $query_params = array())
2595
    {
2596
        $model_obj = $this->ensure_is_obj($id_or_obj);
2597
        $relation_settings = $this->related_settings_for($model_name);
2598
        return $relation_settings->delete_all_related($model_obj, $query_params);
2599
    }
2600
2601
2602
2603
    /**
2604
     * Hard deletes all the model objects across the relation indicated by $model_name
2605
     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2606
     * the model objects can't be hard deleted because of blocking related model objects,
2607
     * just does a soft-delete on them instead.
2608
     *
2609
     * @param EE_Base_Class|int|string $id_or_obj
2610
     * @param string                   $model_name
2611
     * @param array                    $query_params
2612
     * @return int how many deleted
2613
     * @throws EE_Error
2614
     */
2615
    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2616
    {
2617
        $model_obj = $this->ensure_is_obj($id_or_obj);
2618
        $relation_settings = $this->related_settings_for($model_name);
2619
        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2620
    }
2621
2622
2623
2624
    /**
2625
     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2626
     * unless otherwise specified in the $query_params
2627
     *
2628
     * @param        int             /EE_Base_Class $id_or_obj
2629
     * @param string $model_name     like 'Event', or 'Registration'
2630
     * @param array  $query_params   like EEM_Base::get_all's
2631
     * @param string $field_to_count name of field to count by. By default, uses primary key
2632
     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2633
     *                               that by the setting $distinct to TRUE;
2634
     * @return int
2635
     * @throws EE_Error
2636
     */
2637
    public function count_related(
2638
        $id_or_obj,
2639
        $model_name,
2640
        $query_params = array(),
2641
        $field_to_count = null,
2642
        $distinct = false
2643
    ) {
2644
        $related_model = $this->get_related_model_obj($model_name);
2645
        //we're just going to use the query params on the related model's normal get_all query,
2646
        //except add a condition to say to match the current mod
2647
        if (! isset($query_params['default_where_conditions'])) {
2648
            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2649
        }
2650
        $this_model_name = $this->get_this_model_name();
2651
        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2652
        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2653
        return $related_model->count($query_params, $field_to_count, $distinct);
2654
    }
2655
2656
2657
2658
    /**
2659
     * Instead of getting the related model objects, simply sums up the values of the specified field.
2660
     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2661
     *
2662
     * @param        int           /EE_Base_Class $id_or_obj
2663
     * @param string $model_name   like 'Event', or 'Registration'
2664
     * @param array  $query_params like EEM_Base::get_all's
2665
     * @param string $field_to_sum name of field to count by. By default, uses primary key
2666
     * @return float
2667
     * @throws EE_Error
2668
     */
2669
    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2670
    {
2671
        $related_model = $this->get_related_model_obj($model_name);
2672
        if (! is_array($query_params)) {
2673
            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2674
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2675
                    gettype($query_params)), '4.6.0');
2676
            $query_params = array();
2677
        }
2678
        //we're just going to use the query params on the related model's normal get_all query,
2679
        //except add a condition to say to match the current mod
2680
        if (! isset($query_params['default_where_conditions'])) {
2681
            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2682
        }
2683
        $this_model_name = $this->get_this_model_name();
2684
        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2685
        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2686
        return $related_model->sum($query_params, $field_to_sum);
2687
    }
2688
2689
2690
2691
    /**
2692
     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2693
     * $modelObject
2694
     *
2695
     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2696
     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2697
     * @param array               $query_params     like EEM_Base::get_all's
2698
     * @return EE_Base_Class
2699
     * @throws EE_Error
2700
     */
2701
    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2702
    {
2703
        $query_params['limit'] = 1;
2704
        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2705
        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...
2706
            return array_shift($results);
2707
        }
2708
        return null;
2709
    }
2710
2711
2712
2713
    /**
2714
     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2715
     *
2716
     * @return string
2717
     */
2718
    public function get_this_model_name()
2719
    {
2720
        return str_replace("EEM_", "", get_class($this));
2721
    }
2722
2723
2724
2725
    /**
2726
     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2727
     *
2728
     * @return EE_Any_Foreign_Model_Name_Field
2729
     * @throws EE_Error
2730
     */
2731
    public function get_field_containing_related_model_name()
2732
    {
2733
        foreach ($this->field_settings(true) as $field) {
2734
            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2735
                $field_with_model_name = $field;
2736
            }
2737
        }
2738 View Code Duplication
        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2739
            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2740
                $this->get_this_model_name()));
2741
        }
2742
        return $field_with_model_name;
2743
    }
2744
2745
2746
2747
    /**
2748
     * Inserts a new entry into the database, for each table.
2749
     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2750
     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2751
     * we also know there is no model object with the newly inserted item's ID at the moment (because
2752
     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2753
     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2754
     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2755
     *
2756
     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2757
     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2758
     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2759
     *                              of EEM_Base)
2760
     * @return int new primary key on main table that got inserted
2761
     * @throws EE_Error
2762
     */
2763
    public function insert($field_n_values)
2764
    {
2765
        /**
2766
         * Filters the fields and their values before inserting an item using the models
2767
         *
2768
         * @param array    $fields_n_values keys are the fields and values are their new values
2769
         * @param EEM_Base $model           the model used
2770
         */
2771
        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2772
        if ($this->_satisfies_unique_indexes($field_n_values)) {
2773
            $main_table = $this->_get_main_table();
2774
            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2775
            if ($new_id !== false) {
2776
                foreach ($this->_get_other_tables() as $other_table) {
2777
                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2778
                }
2779
            }
2780
            /**
2781
             * Done just after attempting to insert a new model object
2782
             *
2783
             * @param EEM_Base   $model           used
2784
             * @param array      $fields_n_values fields and their values
2785
             * @param int|string the              ID of the newly-inserted model object
2786
             */
2787
            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2788
            return $new_id;
2789
        }
2790
        return false;
2791
    }
2792
2793
2794
2795
    /**
2796
     * Checks that the result would satisfy the unique indexes on this model
2797
     *
2798
     * @param array  $field_n_values
2799
     * @param string $action
2800
     * @return boolean
2801
     * @throws EE_Error
2802
     */
2803
    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2804
    {
2805
        foreach ($this->unique_indexes() as $index_name => $index) {
2806
            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2807
            if ($this->exists(array($uniqueness_where_params))) {
2808
                EE_Error::add_error(
2809
                    sprintf(
2810
                        __(
2811
                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2812
                            "event_espresso"
2813
                        ),
2814
                        $action,
2815
                        $this->_get_class_name(),
2816
                        $index_name,
2817
                        implode(",", $index->field_names()),
2818
                        http_build_query($uniqueness_where_params)
2819
                    ),
2820
                    __FILE__,
2821
                    __FUNCTION__,
2822
                    __LINE__
2823
                );
2824
                return false;
2825
            }
2826
        }
2827
        return true;
2828
    }
2829
2830
2831
2832
    /**
2833
     * Checks the database for an item that conflicts (ie, if this item were
2834
     * saved to the DB would break some uniqueness requirement, like a primary key
2835
     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2836
     * can be either an EE_Base_Class or an array of fields n values
2837
     *
2838
     * @param EE_Base_Class|array $obj_or_fields_array
2839
     * @param boolean             $include_primary_key whether to use the model object's primary key
2840
     *                                                 when looking for conflicts
2841
     *                                                 (ie, if false, we ignore the model object's primary key
2842
     *                                                 when finding "conflicts". If true, it's also considered).
2843
     *                                                 Only works for INT primary key,
2844
     *                                                 STRING primary keys cannot be ignored
2845
     * @throws EE_Error
2846
     * @return EE_Base_Class|array
2847
     */
2848
    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2849
    {
2850 View Code Duplication
        if ($obj_or_fields_array instanceof EE_Base_Class) {
2851
            $fields_n_values = $obj_or_fields_array->model_field_array();
2852
        } elseif (is_array($obj_or_fields_array)) {
2853
            $fields_n_values = $obj_or_fields_array;
2854
        } else {
2855
            throw new EE_Error(
2856
                sprintf(
2857
                    __(
2858
                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2859
                        "event_espresso"
2860
                    ),
2861
                    get_class($this),
2862
                    $obj_or_fields_array
2863
                )
2864
            );
2865
        }
2866
        $query_params = array();
2867
        if ($this->has_primary_key_field()
2868
            && ($include_primary_key
2869
                || $this->get_primary_key_field()
2870
                   instanceof
2871
                   EE_Primary_Key_String_Field)
2872
            && isset($fields_n_values[$this->primary_key_name()])
2873
        ) {
2874
            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2875
        }
2876
        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2877
            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2878
            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2879
        }
2880
        //if there is nothing to base this search on, then we shouldn't find anything
2881
        if (empty($query_params)) {
2882
            return array();
2883
        }
2884
        return $this->get_one($query_params);
2885
    }
2886
2887
2888
2889
    /**
2890
     * Like count, but is optimized and returns a boolean instead of an int
2891
     *
2892
     * @param array $query_params
2893
     * @return boolean
2894
     * @throws EE_Error
2895
     */
2896
    public function exists($query_params)
2897
    {
2898
        $query_params['limit'] = 1;
2899
        return $this->count($query_params) > 0;
2900
    }
2901
2902
2903
2904
    /**
2905
     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2906
     *
2907
     * @param int|string $id
2908
     * @return boolean
2909
     * @throws EE_Error
2910
     */
2911
    public function exists_by_ID($id)
2912
    {
2913
        return $this->exists(
2914
            array(
2915
                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2916
                array(
2917
                    $this->primary_key_name() => $id,
2918
                ),
2919
            )
2920
        );
2921
    }
2922
2923
2924
2925
    /**
2926
     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2927
     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2928
     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2929
     * on the main table)
2930
     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2931
     * cases where we want to call it directly rather than via insert().
2932
     *
2933
     * @access   protected
2934
     * @param EE_Table_Base $table
2935
     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2936
     *                                       float
2937
     * @param int           $new_id          for now we assume only int keys
2938
     * @throws EE_Error
2939
     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2940
     * @return int ID of new row inserted, or FALSE on failure
2941
     */
2942
    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2943
    {
2944
        global $wpdb;
2945
        $insertion_col_n_values = array();
2946
        $format_for_insertion = array();
2947
        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2948
        foreach ($fields_on_table as $field_name => $field_obj) {
2949
            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2950
            if ($field_obj->is_auto_increment()) {
2951
                continue;
2952
            }
2953
            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2954
            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2955
            if ($prepared_value !== null) {
2956
                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2957
                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2958
            }
2959
        }
2960
        if ($table instanceof EE_Secondary_Table && $new_id) {
2961
            //its not the main table, so we should have already saved the main table's PK which we just inserted
2962
            //so add the fk to the main table as a column
2963
            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2964
            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2965
        }
2966
        //insert the new entry
2967
        $result = $this->_do_wpdb_query('insert',
2968
            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2969
        if ($result === false) {
2970
            return false;
2971
        }
2972
        //ok, now what do we return for the ID of the newly-inserted thing?
2973
        if ($this->has_primary_key_field()) {
2974
            if ($this->get_primary_key_field()->is_auto_increment()) {
2975
                return $wpdb->insert_id;
2976
            }
2977
            //it's not an auto-increment primary key, so
2978
            //it must have been supplied
2979
            return $fields_n_values[$this->get_primary_key_field()->get_name()];
2980
        }
2981
        //we can't return a  primary key because there is none. instead return
2982
        //a unique string indicating this model
2983
        return $this->get_index_primary_key_string($fields_n_values);
2984
    }
2985
2986
2987
2988
    /**
2989
     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2990
     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2991
     * and there is no default, we pass it along. WPDB will take care of it)
2992
     *
2993
     * @param EE_Model_Field_Base $field_obj
2994
     * @param array               $fields_n_values
2995
     * @return mixed string|int|float depending on what the table column will be expecting
2996
     * @throws EE_Error
2997
     */
2998
    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2999
    {
3000
        //if this field doesn't allow nullable, don't allow it
3001
        if (
3002
            ! $field_obj->is_nullable()
3003
            && (
3004
                ! isset($fields_n_values[$field_obj->get_name()])
3005
                || $fields_n_values[$field_obj->get_name()] === null
3006
            )
3007
        ) {
3008
            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3009
        }
3010
        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3011
            ? $fields_n_values[$field_obj->get_name()]
3012
            : null;
3013
        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3014
    }
3015
3016
3017
3018
    /**
3019
     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3020
     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3021
     * the field's prepare_for_set() method.
3022
     *
3023
     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3024
     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3025
     *                                   top of file)
3026
     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3027
     *                                   $value is a custom selection
3028
     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3029
     */
3030
    private function _prepare_value_for_use_in_db($value, $field)
3031
    {
3032
        if ($field && $field instanceof EE_Model_Field_Base) {
3033
            switch ($this->_values_already_prepared_by_model_object) {
3034
                /** @noinspection PhpMissingBreakStatementInspection */
3035
                case self::not_prepared_by_model_object:
3036
                    $value = $field->prepare_for_set($value);
3037
                //purposefully left out "return"
3038
                case self::prepared_by_model_object:
3039
                    /** @noinspection SuspiciousAssignmentsInspection */
3040
                    $value = $field->prepare_for_use_in_db($value);
3041
                case self::prepared_for_use_in_db:
3042
                    //leave the value alone
3043
            }
3044
            return $value;
3045
        }
3046
        return $value;
3047
    }
3048
3049
3050
3051
    /**
3052
     * Returns the main table on this model
3053
     *
3054
     * @return EE_Primary_Table
3055
     * @throws EE_Error
3056
     */
3057
    protected function _get_main_table()
3058
    {
3059
        foreach ($this->_tables as $table) {
3060
            if ($table instanceof EE_Primary_Table) {
3061
                return $table;
3062
            }
3063
        }
3064
        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3065
            'event_espresso'), get_class($this)));
3066
    }
3067
3068
3069
3070
    /**
3071
     * table
3072
     * returns EE_Primary_Table table name
3073
     *
3074
     * @return string
3075
     * @throws EE_Error
3076
     */
3077
    public function table()
3078
    {
3079
        return $this->_get_main_table()->get_table_name();
3080
    }
3081
3082
3083
3084
    /**
3085
     * table
3086
     * returns first EE_Secondary_Table table name
3087
     *
3088
     * @return string
3089
     */
3090
    public function second_table()
3091
    {
3092
        // grab second table from tables array
3093
        $second_table = end($this->_tables);
3094
        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3095
    }
3096
3097
3098
3099
    /**
3100
     * get_table_obj_by_alias
3101
     * returns table name given it's alias
3102
     *
3103
     * @param string $table_alias
3104
     * @return EE_Primary_Table | EE_Secondary_Table
3105
     */
3106
    public function get_table_obj_by_alias($table_alias = '')
3107
    {
3108
        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3109
    }
3110
3111
3112
3113
    /**
3114
     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3115
     *
3116
     * @return EE_Secondary_Table[]
3117
     */
3118
    protected function _get_other_tables()
3119
    {
3120
        $other_tables = array();
3121
        foreach ($this->_tables as $table_alias => $table) {
3122
            if ($table instanceof EE_Secondary_Table) {
3123
                $other_tables[$table_alias] = $table;
3124
            }
3125
        }
3126
        return $other_tables;
3127
    }
3128
3129
3130
3131
    /**
3132
     * Finds all the fields that correspond to the given table
3133
     *
3134
     * @param string $table_alias , array key in EEM_Base::_tables
3135
     * @return EE_Model_Field_Base[]
3136
     */
3137
    public function _get_fields_for_table($table_alias)
3138
    {
3139
        return $this->_fields[$table_alias];
3140
    }
3141
3142
3143
3144
    /**
3145
     * Recurses through all the where parameters, and finds all the related models we'll need
3146
     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3147
     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3148
     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3149
     * related Registration, Transaction, and Payment models.
3150
     *
3151
     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3152
     * @return EE_Model_Query_Info_Carrier
3153
     * @throws EE_Error
3154
     */
3155
    public function _extract_related_models_from_query($query_params)
3156
    {
3157
        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3158
        if (array_key_exists(0, $query_params)) {
3159
            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3160
        }
3161 View Code Duplication
        if (array_key_exists('group_by', $query_params)) {
3162
            if (is_array($query_params['group_by'])) {
3163
                $this->_extract_related_models_from_sub_params_array_values(
3164
                    $query_params['group_by'],
3165
                    $query_info_carrier,
3166
                    'group_by'
3167
                );
3168
            } elseif (! empty ($query_params['group_by'])) {
3169
                $this->_extract_related_model_info_from_query_param(
3170
                    $query_params['group_by'],
3171
                    $query_info_carrier,
3172
                    'group_by'
3173
                );
3174
            }
3175
        }
3176
        if (array_key_exists('having', $query_params)) {
3177
            $this->_extract_related_models_from_sub_params_array_keys(
3178
                $query_params[0],
3179
                $query_info_carrier,
3180
                'having'
3181
            );
3182
        }
3183 View Code Duplication
        if (array_key_exists('order_by', $query_params)) {
3184
            if (is_array($query_params['order_by'])) {
3185
                $this->_extract_related_models_from_sub_params_array_keys(
3186
                    $query_params['order_by'],
3187
                    $query_info_carrier,
3188
                    'order_by'
3189
                );
3190
            } elseif (! empty($query_params['order_by'])) {
3191
                $this->_extract_related_model_info_from_query_param(
3192
                    $query_params['order_by'],
3193
                    $query_info_carrier,
3194
                    'order_by'
3195
                );
3196
            }
3197
        }
3198
        if (array_key_exists('force_join', $query_params)) {
3199
            $this->_extract_related_models_from_sub_params_array_values(
3200
                $query_params['force_join'],
3201
                $query_info_carrier,
3202
                'force_join'
3203
            );
3204
        }
3205
        return $query_info_carrier;
3206
    }
3207
3208
3209
3210
    /**
3211
     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3212
     *
3213
     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3214
     *                                                      $query_params['having']
3215
     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3216
     * @param string                      $query_param_type one of $this->_allowed_query_params
3217
     * @throws EE_Error
3218
     * @return \EE_Model_Query_Info_Carrier
3219
     */
3220
    private function _extract_related_models_from_sub_params_array_keys(
3221
        $sub_query_params,
3222
        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3223
        $query_param_type
3224
    ) {
3225
        if (! empty($sub_query_params)) {
3226
            $sub_query_params = (array)$sub_query_params;
3227
            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3228
                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3229
                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3230
                    $query_param_type);
3231
                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3232
                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3233
                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3234
                //of array('Registration.TXN_ID'=>23)
3235
                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3236
                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3237
                    if (! is_array($possibly_array_of_params)) {
3238
                        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'))",
3239
                            "event_espresso"),
3240
                            $param, $possibly_array_of_params));
3241
                    }
3242
                    $this->_extract_related_models_from_sub_params_array_keys(
3243
                        $possibly_array_of_params,
3244
                        $model_query_info_carrier, $query_param_type
3245
                    );
3246
                } 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...
3247
                          && is_array($possibly_array_of_params)
3248
                          && isset($possibly_array_of_params[2])
3249
                          && $possibly_array_of_params[2] == true
3250
                ) {
3251
                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3252
                    //indicating that $possible_array_of_params[1] is actually a field name,
3253
                    //from which we should extract query parameters!
3254 View Code Duplication
                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3255
                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3256
                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3257
                    }
3258
                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3259
                        $model_query_info_carrier, $query_param_type);
3260
                }
3261
            }
3262
        }
3263
        return $model_query_info_carrier;
3264
    }
3265
3266
3267
3268
    /**
3269
     * For extracting related models from forced_joins, where the array values contain the info about what
3270
     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3271
     *
3272
     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3273
     *                                                      $query_params['having']
3274
     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3275
     * @param string                      $query_param_type one of $this->_allowed_query_params
3276
     * @throws EE_Error
3277
     * @return \EE_Model_Query_Info_Carrier
3278
     */
3279
    private function _extract_related_models_from_sub_params_array_values(
3280
        $sub_query_params,
3281
        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3282
        $query_param_type
3283
    ) {
3284
        if (! empty($sub_query_params)) {
3285
            if (! is_array($sub_query_params)) {
3286
                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3287
                    $sub_query_params));
3288
            }
3289
            foreach ($sub_query_params as $param) {
3290
                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3291
                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3292
                    $query_param_type);
3293
            }
3294
        }
3295
        return $model_query_info_carrier;
3296
    }
3297
3298
3299
3300
    /**
3301
     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3302
     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3303
     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3304
     * but use them in a different order. Eg, we need to know what models we are querying
3305
     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3306
     * other models before we can finalize the where clause SQL.
3307
     *
3308
     * @param array $query_params
3309
     * @throws EE_Error
3310
     * @return EE_Model_Query_Info_Carrier
3311
     */
3312
    public function _create_model_query_info_carrier($query_params)
3313
    {
3314
        if (! is_array($query_params)) {
3315
            EE_Error::doing_it_wrong(
3316
                'EEM_Base::_create_model_query_info_carrier',
3317
                sprintf(
3318
                    __(
3319
                        '$query_params should be an array, you passed a variable of type %s',
3320
                        'event_espresso'
3321
                    ),
3322
                    gettype($query_params)
3323
                ),
3324
                '4.6.0'
3325
            );
3326
            $query_params = array();
3327
        }
3328
        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3329
        //first check if we should alter the query to account for caps or not
3330
        //because the caps might require us to do extra joins
3331
        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3332
            $query_params[0] = $where_query_params = array_replace_recursive(
3333
                $where_query_params,
3334
                $this->caps_where_conditions(
3335
                    $query_params['caps']
3336
                )
3337
            );
3338
        }
3339
        $query_object = $this->_extract_related_models_from_query($query_params);
3340
        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3341
        foreach ($where_query_params as $key => $value) {
3342
            if (is_int($key)) {
3343
                throw new EE_Error(
3344
                    sprintf(
3345
                        __(
3346
                            "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.",
3347
                            "event_espresso"
3348
                        ),
3349
                        $key,
3350
                        var_export($value, true),
3351
                        var_export($query_params, true),
3352
                        get_class($this)
3353
                    )
3354
                );
3355
            }
3356
        }
3357
        if (
3358
            array_key_exists('default_where_conditions', $query_params)
3359
            && ! empty($query_params['default_where_conditions'])
3360
        ) {
3361
            $use_default_where_conditions = $query_params['default_where_conditions'];
3362
        } else {
3363
            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3364
        }
3365
        $where_query_params = array_merge(
3366
            $this->_get_default_where_conditions_for_models_in_query(
3367
                $query_object,
3368
                $use_default_where_conditions,
3369
                $where_query_params
3370
            ),
3371
            $where_query_params
3372
        );
3373
        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3374
        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3375
        // So we need to setup a subquery and use that for the main join.
3376
        // Note for now this only works on the primary table for the model.
3377
        // So for instance, you could set the limit array like this:
3378
        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3379
        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3380
            $query_object->set_main_model_join_sql(
3381
                $this->_construct_limit_join_select(
3382
                    $query_params['on_join_limit'][0],
3383
                    $query_params['on_join_limit'][1]
3384
                )
3385
            );
3386
        }
3387
        //set limit
3388
        if (array_key_exists('limit', $query_params)) {
3389
            if (is_array($query_params['limit'])) {
3390
                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3391
                    $e = sprintf(
3392
                        __(
3393
                            "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)",
3394
                            "event_espresso"
3395
                        ),
3396
                        http_build_query($query_params['limit'])
3397
                    );
3398
                    throw new EE_Error($e . "|" . $e);
3399
                }
3400
                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3401
                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3402
            } elseif (! empty ($query_params['limit'])) {
3403
                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3404
            }
3405
        }
3406
        //set order by
3407
        if (array_key_exists('order_by', $query_params)) {
3408
            if (is_array($query_params['order_by'])) {
3409
                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3410
                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3411
                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3412
                if (array_key_exists('order', $query_params)) {
3413
                    throw new EE_Error(
3414
                        sprintf(
3415
                            __(
3416
                                "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 ",
3417
                                "event_espresso"
3418
                            ),
3419
                            get_class($this),
3420
                            implode(", ", array_keys($query_params['order_by'])),
3421
                            implode(", ", $query_params['order_by']),
3422
                            $query_params['order']
3423
                        )
3424
                    );
3425
                }
3426
                $this->_extract_related_models_from_sub_params_array_keys(
3427
                    $query_params['order_by'],
3428
                    $query_object,
3429
                    'order_by'
3430
                );
3431
                //assume it's an array of fields to order by
3432
                $order_array = array();
3433
                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3434
                    $order = $this->_extract_order($order);
3435
                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3436
                }
3437
                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3438
            } elseif (! empty ($query_params['order_by'])) {
3439
                $this->_extract_related_model_info_from_query_param(
3440
                    $query_params['order_by'],
3441
                    $query_object,
3442
                    'order',
3443
                    $query_params['order_by']
3444
                );
3445
                $order = isset($query_params['order'])
3446
                    ? $this->_extract_order($query_params['order'])
3447
                    : 'DESC';
3448
                $query_object->set_order_by_sql(
3449
                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3450
                );
3451
            }
3452
        }
3453
        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3454
        if (! array_key_exists('order_by', $query_params)
3455
            && array_key_exists('order', $query_params)
3456
            && ! empty($query_params['order'])
3457
        ) {
3458
            $pk_field = $this->get_primary_key_field();
3459
            $order = $this->_extract_order($query_params['order']);
3460
            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3461
        }
3462
        //set group by
3463
        if (array_key_exists('group_by', $query_params)) {
3464
            if (is_array($query_params['group_by'])) {
3465
                //it's an array, so assume we'll be grouping by a bunch of stuff
3466
                $group_by_array = array();
3467
                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3468
                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3469
                }
3470
                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3471
            } elseif (! empty ($query_params['group_by'])) {
3472
                $query_object->set_group_by_sql(
3473
                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3474
                );
3475
            }
3476
        }
3477
        //set having
3478
        if (array_key_exists('having', $query_params) && $query_params['having']) {
3479
            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3480
        }
3481
        //now, just verify they didn't pass anything wack
3482
        foreach ($query_params as $query_key => $query_value) {
3483 View Code Duplication
            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3484
                throw new EE_Error(
3485
                    sprintf(
3486
                        __(
3487
                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3488
                            'event_espresso'
3489
                        ),
3490
                        $query_key,
3491
                        get_class($this),
3492
                        //						print_r( $this->_allowed_query_params, TRUE )
3493
                        implode(',', $this->_allowed_query_params)
3494
                    )
3495
                );
3496
            }
3497
        }
3498
        $main_model_join_sql = $query_object->get_main_model_join_sql();
3499
        if (empty($main_model_join_sql)) {
3500
            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3501
        }
3502
        return $query_object;
3503
    }
3504
3505
3506
3507
    /**
3508
     * Gets the where conditions that should be imposed on the query based on the
3509
     * context (eg reading frontend, backend, edit or delete).
3510
     *
3511
     * @param string $context one of EEM_Base::valid_cap_contexts()
3512
     * @return array like EEM_Base::get_all() 's $query_params[0]
3513
     * @throws EE_Error
3514
     */
3515
    public function caps_where_conditions($context = self::caps_read)
3516
    {
3517
        EEM_Base::verify_is_valid_cap_context($context);
3518
        $cap_where_conditions = array();
3519
        $cap_restrictions = $this->caps_missing($context);
3520
        /**
3521
         * @var $cap_restrictions EE_Default_Where_Conditions[]
3522
         */
3523
        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3524
            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3525
                $restriction_if_no_cap->get_default_where_conditions());
3526
        }
3527
        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3528
            $cap_restrictions);
3529
    }
3530
3531
3532
3533
    /**
3534
     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3535
     * otherwise throws an exception
3536
     *
3537
     * @param string $should_be_order_string
3538
     * @return string either ASC, asc, DESC or desc
3539
     * @throws EE_Error
3540
     */
3541 View Code Duplication
    private function _extract_order($should_be_order_string)
3542
    {
3543
        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3544
            return $should_be_order_string;
3545
        }
3546
        throw new EE_Error(
3547
            sprintf(
3548
                __(
3549
                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3550
                    "event_espresso"
3551
                ), get_class($this), $should_be_order_string
3552
            )
3553
        );
3554
    }
3555
3556
3557
3558
    /**
3559
     * Looks at all the models which are included in this query, and asks each
3560
     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3561
     * so they can be merged
3562
     *
3563
     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3564
     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3565
     *                                                                  'none' means NO default where conditions will
3566
     *                                                                  be used AT ALL during this query.
3567
     *                                                                  'other_models_only' means default where
3568
     *                                                                  conditions from other models will be used, but
3569
     *                                                                  not for this primary model. 'all', the default,
3570
     *                                                                  means default where conditions will apply as
3571
     *                                                                  normal
3572
     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3573
     * @throws EE_Error
3574
     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3575
     */
3576
    private function _get_default_where_conditions_for_models_in_query(
3577
        EE_Model_Query_Info_Carrier $query_info_carrier,
3578
        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3579
        $where_query_params = array()
3580
    ) {
3581
        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3582
        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3583
            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3584
                "event_espresso"), $use_default_where_conditions,
3585
                implode(", ", $allowed_used_default_where_conditions_values)));
3586
        }
3587
        $universal_query_params = array();
3588
        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3589
            $universal_query_params = $this->_get_default_where_conditions();
3590
        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3591
            $universal_query_params = $this->_get_minimum_where_conditions();
3592
        }
3593
        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3594
            $related_model = $this->get_related_model_obj($model_name);
3595
            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3596
                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3597
            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3598
                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3599
            } else {
3600
                //we don't want to add full or even minimum default where conditions from this model, so just continue
3601
                continue;
3602
            }
3603
            $overrides = $this->_override_defaults_or_make_null_friendly(
3604
                $related_model_universal_where_params,
3605
                $where_query_params,
3606
                $related_model,
3607
                $model_relation_path
3608
            );
3609
            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3610
                $universal_query_params,
3611
                $overrides
3612
            );
3613
        }
3614
        return $universal_query_params;
3615
    }
3616
3617
3618
3619
    /**
3620
     * Determines whether or not we should use default where conditions for the model in question
3621
     * (this model, or other related models).
3622
     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3623
     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3624
     * We should use default where conditions on related models when they requested to use default where conditions
3625
     * on all models, or specifically just on other related models
3626
     * @param      $default_where_conditions_value
3627
     * @param bool $for_this_model false means this is for OTHER related models
3628
     * @return bool
3629
     */
3630
    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3631
    {
3632
        return (
3633
                   $for_this_model
3634
                   && in_array(
3635
                       $default_where_conditions_value,
3636
                       array(
3637
                           EEM_Base::default_where_conditions_all,
3638
                           EEM_Base::default_where_conditions_this_only,
3639
                           EEM_Base::default_where_conditions_minimum_others,
3640
                       ),
3641
                       true
3642
                   )
3643
               )
3644
               || (
3645
                   ! $for_this_model
3646
                   && in_array(
3647
                       $default_where_conditions_value,
3648
                       array(
3649
                           EEM_Base::default_where_conditions_all,
3650
                           EEM_Base::default_where_conditions_others_only,
3651
                       ),
3652
                       true
3653
                   )
3654
               );
3655
    }
3656
3657
    /**
3658
     * Determines whether or not we should use default minimum conditions for the model in question
3659
     * (this model, or other related models).
3660
     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3661
     * where conditions.
3662
     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3663
     * on this model or others
3664
     * @param      $default_where_conditions_value
3665
     * @param bool $for_this_model false means this is for OTHER related models
3666
     * @return bool
3667
     */
3668
    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3669
    {
3670
        return (
3671
                   $for_this_model
3672
                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3673
               )
3674
               || (
3675
                   ! $for_this_model
3676
                   && in_array(
3677
                       $default_where_conditions_value,
3678
                       array(
3679
                           EEM_Base::default_where_conditions_minimum_others,
3680
                           EEM_Base::default_where_conditions_minimum_all,
3681
                       ),
3682
                       true
3683
                   )
3684
               );
3685
    }
3686
3687
3688
    /**
3689
     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3690
     * then we also add a special where condition which allows for that model's primary key
3691
     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3692
     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3693
     *
3694
     * @param array    $default_where_conditions
3695
     * @param array    $provided_where_conditions
3696
     * @param EEM_Base $model
3697
     * @param string   $model_relation_path like 'Transaction.Payment.'
3698
     * @return array like EEM_Base::get_all's $query_params[0]
3699
     * @throws EE_Error
3700
     */
3701
    private function _override_defaults_or_make_null_friendly(
3702
        $default_where_conditions,
3703
        $provided_where_conditions,
3704
        $model,
3705
        $model_relation_path
3706
    ) {
3707
        $null_friendly_where_conditions = array();
3708
        $none_overridden = true;
3709
        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3710
        foreach ($default_where_conditions as $key => $val) {
3711
            if (isset($provided_where_conditions[$key])) {
3712
                $none_overridden = false;
3713
            } else {
3714
                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3715
            }
3716
        }
3717
        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...
3718
            if ($model->has_primary_key_field()) {
3719
                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3720
                                                                                . "."
3721
                                                                                . $model->primary_key_name()] = array('IS NULL');
3722
            }/*else{
3723
				//@todo NO PK, use other defaults
3724
			}*/
3725
        }
3726
        return $null_friendly_where_conditions;
3727
    }
3728
3729
3730
3731
    /**
3732
     * Uses the _default_where_conditions_strategy set during __construct() to get
3733
     * default where conditions on all get_all, update, and delete queries done by this model.
3734
     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3735
     * NOT array('Event_CPT.post_type'=>'esp_event').
3736
     *
3737
     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3738
     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3739
     */
3740
    private function _get_default_where_conditions($model_relation_path = null)
3741
    {
3742
        if ($this->_ignore_where_strategy) {
3743
            return array();
3744
        }
3745
        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3746
    }
3747
3748
3749
3750
    /**
3751
     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3752
     * minimum where conditions on all get_all, update, and delete queries done by this model.
3753
     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3754
     * NOT array('Event_CPT.post_type'=>'esp_event').
3755
     * Similar to _get_default_where_conditions
3756
     *
3757
     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3758
     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3759
     */
3760
    protected function _get_minimum_where_conditions($model_relation_path = null)
3761
    {
3762
        if ($this->_ignore_where_strategy) {
3763
            return array();
3764
        }
3765
        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3766
    }
3767
3768
3769
3770
    /**
3771
     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3772
     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3773
     *
3774
     * @param EE_Model_Query_Info_Carrier $model_query_info
3775
     * @return string
3776
     * @throws EE_Error
3777
     */
3778
    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3779
    {
3780
        $selects = $this->_get_columns_to_select_for_this_model();
3781
        foreach (
3782
            $model_query_info->get_model_names_included() as $model_relation_chain =>
3783
            $name_of_other_model_included
3784
        ) {
3785
            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3786
            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3787
            foreach ($other_model_selects as $key => $value) {
3788
                $selects[] = $value;
3789
            }
3790
        }
3791
        return implode(", ", $selects);
3792
    }
3793
3794
3795
3796
    /**
3797
     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3798
     * So that's going to be the columns for all the fields on the model
3799
     *
3800
     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3801
     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3802
     */
3803
    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3804
    {
3805
        $fields = $this->field_settings();
3806
        $selects = array();
3807
        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3808
            $this->get_this_model_name());
3809
        foreach ($fields as $field_obj) {
3810
            $selects[] = $table_alias_with_model_relation_chain_prefix
3811
                         . $field_obj->get_table_alias()
3812
                         . "."
3813
                         . $field_obj->get_table_column()
3814
                         . " AS '"
3815
                         . $table_alias_with_model_relation_chain_prefix
3816
                         . $field_obj->get_table_alias()
3817
                         . "."
3818
                         . $field_obj->get_table_column()
3819
                         . "'";
3820
        }
3821
        //make sure we are also getting the PKs of each table
3822
        $tables = $this->get_tables();
3823
        if (count($tables) > 1) {
3824
            foreach ($tables as $table_obj) {
3825
                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3826
                                       . $table_obj->get_fully_qualified_pk_column();
3827
                if (! in_array($qualified_pk_column, $selects)) {
3828
                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3829
                }
3830
            }
3831
        }
3832
        return $selects;
3833
    }
3834
3835
3836
3837
    /**
3838
     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3839
     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3840
     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3841
     * SQL for joining, and the data types
3842
     *
3843
     * @param null|string                 $original_query_param
3844
     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3845
     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3846
     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3847
     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3848
     *                                                          column name. We only want model names, eg 'Event.Venue'
3849
     *                                                          or 'Registration's
3850
     * @param string                      $original_query_param what it originally was (eg
3851
     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3852
     *                                                          matches $query_param
3853
     * @throws EE_Error
3854
     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3855
     */
3856
    private function _extract_related_model_info_from_query_param(
3857
        $query_param,
3858
        EE_Model_Query_Info_Carrier $passed_in_query_info,
3859
        $query_param_type,
3860
        $original_query_param = null
3861
    ) {
3862
        if ($original_query_param === null) {
3863
            $original_query_param = $query_param;
3864
        }
3865
        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3866
        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3867
        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3868
        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3869
        //check to see if we have a field on this model
3870
        $this_model_fields = $this->field_settings(true);
3871 View Code Duplication
        if (array_key_exists($query_param, $this_model_fields)) {
3872
            if ($allow_fields) {
3873
                return;
3874
            }
3875
            throw new EE_Error(
3876
                sprintf(
3877
                    __(
3878
                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3879
                        "event_espresso"
3880
                    ),
3881
                    $query_param, get_class($this), $query_param_type, $original_query_param
3882
                )
3883
            );
3884
        }
3885
        //check if this is a special logic query param
3886
        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3887
            if ($allow_logic_query_params) {
3888
                return;
3889
            }
3890
            throw new EE_Error(
3891
                sprintf(
3892
                    __(
3893
                        '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',
3894
                        'event_espresso'
3895
                    ),
3896
                    implode('", "', $this->_logic_query_param_keys),
3897
                    $query_param,
3898
                    get_class($this),
3899
                    '<br />',
3900
                    "\t"
3901
                    . ' $passed_in_query_info = <pre>'
3902
                    . print_r($passed_in_query_info, true)
3903
                    . '</pre>'
3904
                    . "\n\t"
3905
                    . ' $query_param_type = '
3906
                    . $query_param_type
3907
                    . "\n\t"
3908
                    . ' $original_query_param = '
3909
                    . $original_query_param
3910
                )
3911
            );
3912
        }
3913
        //check if it's a custom selection
3914
        if (array_key_exists($query_param, $this->_custom_selections)) {
3915
            return;
3916
        }
3917
        //check if has a model name at the beginning
3918
        //and
3919
        //check if it's a field on a related model
3920
        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3921
            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3922
                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3923
                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3924
                if ($query_param === '') {
3925
                    //nothing left to $query_param
3926
                    //we should actually end in a field name, not a model like this!
3927
                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3928
                        "event_espresso"),
3929
                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3930
                }
3931
                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3932
                $related_model_obj->_extract_related_model_info_from_query_param(
3933
                    $query_param,
3934
                    $passed_in_query_info, $query_param_type, $original_query_param
3935
                );
3936
                return;
3937
            }
3938
            if ($query_param === $valid_related_model_name) {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $query_param (string) and $valid_related_model_name (integer) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
3939
                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3940
                return;
3941
            }
3942
        }
3943
        //ok so $query_param didn't start with a model name
3944
        //and we previously confirmed it wasn't a logic query param or field on the current model
3945
        //it's wack, that's what it is
3946
        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",
3947
            "event_espresso"),
3948
            $query_param, get_class($this), $query_param_type, $original_query_param));
3949
    }
3950
3951
3952
3953
    /**
3954
     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3955
     * and store it on $passed_in_query_info
3956
     *
3957
     * @param string                      $model_name
3958
     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3959
     * @param string                      $original_query_param used to extract the relation chain between the queried
3960
     *                                                          model and $model_name. Eg, if we are querying Event,
3961
     *                                                          and are adding a join to 'Payment' with the original
3962
     *                                                          query param key
3963
     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3964
     *                                                          to extract 'Registration.Transaction.Payment', in case
3965
     *                                                          Payment wants to add default query params so that it
3966
     *                                                          will know what models to prepend onto its default query
3967
     *                                                          params or in case it wants to rename tables (in case
3968
     *                                                          there are multiple joins to the same table)
3969
     * @return void
3970
     * @throws EE_Error
3971
     */
3972
    private function _add_join_to_model(
3973
        $model_name,
3974
        EE_Model_Query_Info_Carrier $passed_in_query_info,
3975
        $original_query_param
3976
    ) {
3977
        $relation_obj = $this->related_settings_for($model_name);
3978
        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3979
        //check if the relation is HABTM, because then we're essentially doing two joins
3980
        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3981
        if ($relation_obj instanceof EE_HABTM_Relation) {
3982
            $join_model_obj = $relation_obj->get_join_model();
3983
            //replace the model specified with the join model for this relation chain, whi
3984
            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3985
                $join_model_obj->get_this_model_name(), $model_relation_chain);
3986
            $new_query_info = new EE_Model_Query_Info_Carrier(
3987
                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3988
                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3989
            $passed_in_query_info->merge($new_query_info);
3990
        }
3991
        //now just join to the other table pointed to by the relation object, and add its data types
3992
        $new_query_info = new EE_Model_Query_Info_Carrier(
3993
            array($model_relation_chain => $model_name),
3994
            $relation_obj->get_join_statement($model_relation_chain));
3995
        $passed_in_query_info->merge($new_query_info);
3996
    }
3997
3998
3999
4000
    /**
4001
     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4002
     *
4003
     * @param array $where_params like EEM_Base::get_all
4004
     * @return string of SQL
4005
     * @throws EE_Error
4006
     */
4007
    private function _construct_where_clause($where_params)
4008
    {
4009
        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4010
        if ($SQL) {
4011
            return " WHERE " . $SQL;
4012
        }
4013
        return '';
4014
    }
4015
4016
4017
4018
    /**
4019
     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4020
     * and should be passed HAVING parameters, not WHERE parameters
4021
     *
4022
     * @param array $having_params
4023
     * @return string
4024
     * @throws EE_Error
4025
     */
4026
    private function _construct_having_clause($having_params)
4027
    {
4028
        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4029
        if ($SQL) {
4030
            return " HAVING " . $SQL;
4031
        }
4032
        return '';
4033
    }
4034
4035
4036
4037
    /**
4038
     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
4039
     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
4040
     * EEM_Attendee.
4041
     *
4042
     * @param string $field_name
4043
     * @param string $model_name
4044
     * @return EE_Model_Field_Base
4045
     * @throws EE_Error
4046
     */
4047
    protected function _get_field_on_model($field_name, $model_name)
4048
    {
4049
        $model_class = 'EEM_' . $model_name;
4050
        $model_filepath = $model_class . ".model.php";
4051
        if (is_readable($model_filepath)) {
4052
            require_once($model_filepath);
4053
            $model_instance = call_user_func($model_name . "::instance");
4054
            /* @var $model_instance EEM_Base */
4055
            return $model_instance->field_settings_for($field_name);
4056
        }
4057
        throw new EE_Error(
4058
            sprintf(
4059
                __(
4060
                    'No model named %s exists, with classname %s and filepath %s',
4061
                    'event_espresso'
4062
                ), $model_name, $model_class, $model_filepath
4063
            )
4064
        );
4065
    }
4066
4067
4068
4069
    /**
4070
     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4071
     * Event_Meta.meta_value = 'foo'))"
4072
     *
4073
     * @param array  $where_params see EEM_Base::get_all for documentation
4074
     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4075
     * @throws EE_Error
4076
     * @return string of SQL
4077
     */
4078
    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4079
    {
4080
        $where_clauses = array();
4081
        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4082
            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4083
            if (in_array($query_param, $this->_logic_query_param_keys)) {
4084
                switch ($query_param) {
4085
                    case 'not':
4086
                    case 'NOT':
4087
                        $where_clauses[] = "! ("
4088
                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4089
                                $glue)
4090
                                           . ")";
4091
                        break;
4092
                    case 'and':
4093
                    case 'AND':
4094
                        $where_clauses[] = " ("
4095
                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4096
                                ' AND ')
4097
                                           . ")";
4098
                        break;
4099
                    case 'or':
4100
                    case 'OR':
4101
                        $where_clauses[] = " ("
4102
                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4103
                                ' OR ')
4104
                                           . ")";
4105
                        break;
4106
                }
4107
            } else {
4108
                $field_obj = $this->_deduce_field_from_query_param($query_param);
4109
                //if it's not a normal field, maybe it's a custom selection?
4110
                if (! $field_obj) {
4111
                    if (isset($this->_custom_selections[$query_param][1])) {
4112
                        $field_obj = $this->_custom_selections[$query_param][1];
4113
                    } else {
4114
                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4115
                            "event_espresso"), $query_param));
4116
                    }
4117
                }
4118
                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4119
                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4120
            }
4121
        }
4122
        return $where_clauses ? implode($glue, $where_clauses) : '';
4123
    }
4124
4125
4126
4127
    /**
4128
     * Takes the input parameter and extract the table name (alias) and column name
4129
     *
4130
     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4131
     * @throws EE_Error
4132
     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4133
     */
4134
    private function _deduce_column_name_from_query_param($query_param)
4135
    {
4136
        $field = $this->_deduce_field_from_query_param($query_param);
4137
        if ($field) {
4138
            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4139
                $query_param);
4140
            return $table_alias_prefix . $field->get_qualified_column();
4141
        }
4142
        if (array_key_exists($query_param, $this->_custom_selections)) {
4143
            //maybe it's custom selection item?
4144
            //if so, just use it as the "column name"
4145
            return $query_param;
4146
        }
4147
        throw new EE_Error(
4148
            sprintf(
4149
                __(
4150
                    "%s is not a valid field on this model, nor a custom selection (%s)",
4151
                    "event_espresso"
4152
                ), $query_param, implode(",", $this->_custom_selections)
4153
            )
4154
        );
4155
    }
4156
4157
4158
4159
    /**
4160
     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4161
     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4162
     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4163
     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4164
     *
4165
     * @param string $condition_query_param_key
4166
     * @return string
4167
     */
4168 View Code Duplication
    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4169
    {
4170
        $pos_of_star = strpos($condition_query_param_key, '*');
4171
        if ($pos_of_star === false) {
4172
            return $condition_query_param_key;
4173
        }
4174
        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4175
        return $condition_query_param_sans_star;
4176
    }
4177
4178
4179
4180
    /**
4181
     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4182
     *
4183
     * @param                            mixed      array | string    $op_and_value
4184
     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4185
     * @throws EE_Error
4186
     * @return string
4187
     */
4188
    private function _construct_op_and_value($op_and_value, $field_obj)
4189
    {
4190
        if (is_array($op_and_value)) {
4191
            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4192
            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...
4193
                $php_array_like_string = array();
4194
                foreach ($op_and_value as $key => $value) {
4195
                    $php_array_like_string[] = "$key=>$value";
4196
                }
4197
                throw new EE_Error(
4198
                    sprintf(
4199
                        __(
4200
                            "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))",
4201
                            "event_espresso"
4202
                        ),
4203
                        implode(",", $php_array_like_string)
4204
                    )
4205
                );
4206
            }
4207
            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4208
        } else {
4209
            $operator = '=';
4210
            $value = $op_and_value;
4211
        }
4212
        //check to see if the value is actually another field
4213
        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4214
            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4215
        }
4216 View Code Duplication
        if (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4217
            //in this case, the value should be an array, or at least a comma-separated list
4218
            //it will need to handle a little differently
4219
            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4220
            //note: $cleaned_value has already been run through $wpdb->prepare()
4221
            return $operator . SP . $cleaned_value;
4222
        }
4223
        if (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4224
            //the value should be an array with count of two.
4225
            if (count($value) !== 2) {
4226
                throw new EE_Error(
4227
                    sprintf(
4228
                        __(
4229
                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4230
                            'event_espresso'
4231
                        ),
4232
                        "BETWEEN"
4233
                    )
4234
                );
4235
            }
4236
            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4237
            return $operator . SP . $cleaned_value;
4238
        }
4239 View Code Duplication
        if (in_array($operator, $this->_null_style_operators)) {
4240
            if ($value !== null) {
4241
                throw new EE_Error(
4242
                    sprintf(
4243
                        __(
4244
                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4245
                            "event_espresso"
4246
                        ),
4247
                        $value,
4248
                        $operator
4249
                    )
4250
                );
4251
            }
4252
            return $operator;
4253
        }
4254
        if ($operator === 'LIKE' && ! is_array($value)) {
4255
            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4256
            //remove other junk. So just treat it as a string.
4257
            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4258
        }
4259 View Code Duplication
        if (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4260
            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4261
        }
4262 View Code Duplication
        if (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4263
            throw new EE_Error(
4264
                sprintf(
4265
                    __(
4266
                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4267
                        'event_espresso'
4268
                    ),
4269
                    $operator,
4270
                    $operator
4271
                )
4272
            );
4273
        }
4274 View Code Duplication
        if (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4275
            throw new EE_Error(
4276
                sprintf(
4277
                    __(
4278
                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4279
                        'event_espresso'
4280
                    ),
4281
                    $operator,
4282
                    $operator
4283
                )
4284
            );
4285
        }
4286
        throw new EE_Error(
4287
            sprintf(
4288
                __(
4289
                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4290
                    "event_espresso"
4291
                ),
4292
                http_build_query($op_and_value)
4293
            )
4294
        );
4295
    }
4296
4297
4298
4299
    /**
4300
     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4301
     *
4302
     * @param array                      $values
4303
     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4304
     *                                              '%s'
4305
     * @return string
4306
     * @throws EE_Error
4307
     */
4308
    public function _construct_between_value($values, $field_obj)
4309
    {
4310
        $cleaned_values = array();
4311
        foreach ($values as $value) {
4312
            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4313
        }
4314
        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4315
    }
4316
4317
4318
4319
    /**
4320
     * Takes an array or a comma-separated list of $values and cleans them
4321
     * according to $data_type using $wpdb->prepare, and then makes the list a
4322
     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4323
     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4324
     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4325
     *
4326
     * @param mixed                      $values    array or comma-separated string
4327
     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4328
     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4329
     * @throws EE_Error
4330
     */
4331
    public function _construct_in_value($values, $field_obj)
4332
    {
4333
        //check if the value is a CSV list
4334
        if (is_string($values)) {
4335
            //in which case, turn it into an array
4336
            $values = explode(",", $values);
4337
        }
4338
        $cleaned_values = array();
4339
        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...
4340
            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4341
        }
4342
        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4343
        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4344
        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4345
        if (empty($cleaned_values)) {
4346
            $all_fields = $this->field_settings();
4347
            $a_field = array_shift($all_fields);
4348
            $main_table = $this->_get_main_table();
4349
            $cleaned_values[] = "SELECT "
4350
                                . $a_field->get_table_column()
4351
                                . " FROM "
4352
                                . $main_table->get_table_name()
4353
                                . " WHERE FALSE";
4354
        }
4355
        return "(" . implode(",", $cleaned_values) . ")";
4356
    }
4357
4358
4359
4360
    /**
4361
     * @param mixed                      $value
4362
     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4363
     * @throws EE_Error
4364
     * @return false|null|string
4365
     */
4366
    private function _wpdb_prepare_using_field($value, $field_obj)
4367
    {
4368
        /** @type WPDB $wpdb */
4369
        global $wpdb;
4370
        if ($field_obj instanceof EE_Model_Field_Base) {
4371
            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4372
                $this->_prepare_value_for_use_in_db($value, $field_obj));
4373
        } //$field_obj should really just be a data type
4374 View Code Duplication
        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4375
            throw new EE_Error(
4376
                sprintf(
4377
                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4378
                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4379
                )
4380
            );
4381
        }
4382
        return $wpdb->prepare($field_obj, $value);
4383
    }
4384
4385
4386
4387
    /**
4388
     * Takes the input parameter and finds the model field that it indicates.
4389
     *
4390
     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4391
     * @throws EE_Error
4392
     * @return EE_Model_Field_Base
4393
     */
4394
    protected function _deduce_field_from_query_param($query_param_name)
4395
    {
4396
        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4397
        //which will help us find the database table and column
4398
        $query_param_parts = explode(".", $query_param_name);
4399
        if (empty($query_param_parts)) {
4400
            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4401
                'event_espresso'), $query_param_name));
4402
        }
4403
        $number_of_parts = count($query_param_parts);
4404
        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4405
        if ($number_of_parts === 1) {
4406
            $field_name = $last_query_param_part;
4407
            $model_obj = $this;
4408
        } else {// $number_of_parts >= 2
4409
            //the last part is the column name, and there are only 2parts. therefore...
4410
            $field_name = $last_query_param_part;
4411
            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4412
        }
4413
        try {
4414
            return $model_obj->field_settings_for($field_name);
4415
        } catch (EE_Error $e) {
4416
            return null;
4417
        }
4418
    }
4419
4420
4421
4422
    /**
4423
     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4424
     * alias and column which corresponds to it
4425
     *
4426
     * @param string $field_name
4427
     * @throws EE_Error
4428
     * @return string
4429
     */
4430
    public function _get_qualified_column_for_field($field_name)
4431
    {
4432
        $all_fields = $this->field_settings();
4433
        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4434
        if ($field) {
4435
            return $field->get_qualified_column();
4436
        }
4437
        throw new EE_Error(
4438
            sprintf(
4439
                __(
4440
                    "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.",
4441
                    'event_espresso'
4442
                ), $field_name, get_class($this)
4443
            )
4444
        );
4445
    }
4446
4447
4448
4449
    /**
4450
     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4451
     * Example usage:
4452
     * EEM_Ticket::instance()->get_all_wpdb_results(
4453
     *      array(),
4454
     *      ARRAY_A,
4455
     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4456
     *  );
4457
     * is equivalent to
4458
     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4459
     * and
4460
     *  EEM_Event::instance()->get_all_wpdb_results(
4461
     *      array(
4462
     *          array(
4463
     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4464
     *          ),
4465
     *          ARRAY_A,
4466
     *          implode(
4467
     *              ', ',
4468
     *              array_merge(
4469
     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4470
     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4471
     *              )
4472
     *          )
4473
     *      )
4474
     *  );
4475
     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4476
     *
4477
     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4478
     *                                            and the one whose fields you are selecting for example: when querying
4479
     *                                            tickets model and selecting fields from the tickets model you would
4480
     *                                            leave this parameter empty, because no models are needed to join
4481
     *                                            between the queried model and the selected one. Likewise when
4482
     *                                            querying the datetime model and selecting fields from the tickets
4483
     *                                            model, it would also be left empty, because there is a direct
4484
     *                                            relation from datetimes to tickets, so no model is needed to join
4485
     *                                            them together. However, when querying from the event model and
4486
     *                                            selecting fields from the ticket model, you should provide the string
4487
     *                                            'Datetime', indicating that the event model must first join to the
4488
     *                                            datetime model in order to find its relation to ticket model.
4489
     *                                            Also, when querying from the venue model and selecting fields from
4490
     *                                            the ticket model, you should provide the string 'Event.Datetime',
4491
     *                                            indicating you need to join the venue model to the event model,
4492
     *                                            to the datetime model, in order to find its relation to the ticket model.
4493
     *                                            This string is used to deduce the prefix that gets added onto the
4494
     *                                            models' tables qualified columns
4495
     * @param bool   $return_string               if true, will return a string with qualified column names separated
4496
     *                                            by ', ' if false, will simply return a numerically indexed array of
4497
     *                                            qualified column names
4498
     * @return array|string
4499
     */
4500
    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4501
    {
4502
        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4503
        $qualified_columns = array();
4504
        foreach ($this->field_settings() as $field_name => $field) {
4505
            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4506
        }
4507
        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4508
    }
4509
4510
4511
4512
    /**
4513
     * constructs the select use on special limit joins
4514
     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4515
     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4516
     * (as that is typically where the limits would be set).
4517
     *
4518
     * @param  string       $table_alias The table the select is being built for
4519
     * @param  mixed|string $limit       The limit for this select
4520
     * @return string                The final select join element for the query.
4521
     */
4522
    public function _construct_limit_join_select($table_alias, $limit)
4523
    {
4524
        $SQL = '';
4525
        foreach ($this->_tables as $table_obj) {
4526
            if ($table_obj instanceof EE_Primary_Table) {
4527
                $SQL .= $table_alias === $table_obj->get_table_alias()
4528
                    ? $table_obj->get_select_join_limit($limit)
4529
                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4530
            } elseif ($table_obj instanceof EE_Secondary_Table) {
4531
                $SQL .= $table_alias === $table_obj->get_table_alias()
4532
                    ? $table_obj->get_select_join_limit_join($limit)
4533
                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4534
            }
4535
        }
4536
        return $SQL;
4537
    }
4538
4539
4540
4541
    /**
4542
     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4543
     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4544
     *
4545
     * @return string SQL
4546
     * @throws EE_Error
4547
     */
4548
    public function _construct_internal_join()
4549
    {
4550
        $SQL = $this->_get_main_table()->get_table_sql();
4551
        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4552
        return $SQL;
4553
    }
4554
4555
4556
4557
    /**
4558
     * Constructs the SQL for joining all the tables on this model.
4559
     * Normally $alias should be the primary table's alias, but in cases where
4560
     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4561
     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4562
     * alias, this will construct SQL like:
4563
     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4564
     * With $alias being a secondary table's alias, this will construct SQL like:
4565
     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4566
     *
4567
     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4568
     * @return string
4569
     */
4570
    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4571
    {
4572
        $SQL = '';
4573
        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4574
        foreach ($this->_tables as $table_obj) {
4575
            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4576
                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4577
                    //so we're joining to this table, meaning the table is already in
4578
                    //the FROM statement, BUT the primary table isn't. So we want
4579
                    //to add the inverse join sql
4580
                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4581
                } else {
4582
                    //just add a regular JOIN to this table from the primary table
4583
                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4584
                }
4585
            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4586
        }
4587
        return $SQL;
4588
    }
4589
4590
4591
4592
    /**
4593
     * Gets an array for storing all the data types on the next-to-be-executed-query.
4594
     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4595
     * their data type (eg, '%s', '%d', etc)
4596
     *
4597
     * @return array
4598
     */
4599
    public function _get_data_types()
4600
    {
4601
        $data_types = array();
4602
        foreach ($this->field_settings() as $field_obj) {
4603
            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4604
            /** @var $field_obj EE_Model_Field_Base */
4605
            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4606
        }
4607
        return $data_types;
4608
    }
4609
4610
4611
4612
    /**
4613
     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4614
     *
4615
     * @param string $model_name
4616
     * @throws EE_Error
4617
     * @return EEM_Base
4618
     */
4619
    public function get_related_model_obj($model_name)
4620
    {
4621
        $model_classname = "EEM_" . $model_name;
4622
        if (! class_exists($model_classname)) {
4623
            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",
4624
                'event_espresso'), $model_name, $model_classname));
4625
        }
4626
        return call_user_func($model_classname . "::instance");
4627
    }
4628
4629
4630
4631
    /**
4632
     * Returns the array of EE_ModelRelations for this model.
4633
     *
4634
     * @return EE_Model_Relation_Base[]
4635
     */
4636
    public function relation_settings()
4637
    {
4638
        return $this->_model_relations;
4639
    }
4640
4641
4642
4643
    /**
4644
     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4645
     * because without THOSE models, this model probably doesn't have much purpose.
4646
     * (Eg, without an event, datetimes have little purpose.)
4647
     *
4648
     * @return EE_Belongs_To_Relation[]
4649
     */
4650
    public function belongs_to_relations()
4651
    {
4652
        $belongs_to_relations = array();
4653
        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4654
            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4655
                $belongs_to_relations[$model_name] = $relation_obj;
4656
            }
4657
        }
4658
        return $belongs_to_relations;
4659
    }
4660
4661
4662
4663
    /**
4664
     * Returns the specified EE_Model_Relation, or throws an exception
4665
     *
4666
     * @param string $relation_name name of relation, key in $this->_relatedModels
4667
     * @throws EE_Error
4668
     * @return EE_Model_Relation_Base
4669
     */
4670
    public function related_settings_for($relation_name)
4671
    {
4672
        $relatedModels = $this->relation_settings();
4673 View Code Duplication
        if (! array_key_exists($relation_name, $relatedModels)) {
4674
            throw new EE_Error(
4675
                sprintf(
4676
                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4677
                        'event_espresso'),
4678
                    $relation_name,
4679
                    $this->_get_class_name(),
4680
                    implode(', ', array_keys($relatedModels))
4681
                )
4682
            );
4683
        }
4684
        return $relatedModels[$relation_name];
4685
    }
4686
4687
4688
4689
    /**
4690
     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4691
     * fields
4692
     *
4693
     * @param string $fieldName
4694
     * @throws EE_Error
4695
     * @return EE_Model_Field_Base
4696
     */
4697 View Code Duplication
    public function field_settings_for($fieldName)
4698
    {
4699
        $fieldSettings = $this->field_settings(true);
4700
        if (! array_key_exists($fieldName, $fieldSettings)) {
4701
            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4702
                get_class($this)));
4703
        }
4704
        return $fieldSettings[$fieldName];
4705
    }
4706
4707
4708
4709
    /**
4710
     * Checks if this field exists on this model
4711
     *
4712
     * @param string $fieldName a key in the model's _field_settings array
4713
     * @return boolean
4714
     */
4715
    public function has_field($fieldName)
4716
    {
4717
        $fieldSettings = $this->field_settings(true);
4718
        if (isset($fieldSettings[$fieldName])) {
4719
            return true;
4720
        }
4721
        return false;
4722
    }
4723
4724
4725
4726
    /**
4727
     * Returns whether or not this model has a relation to the specified model
4728
     *
4729
     * @param string $relation_name possibly one of the keys in the relation_settings array
4730
     * @return boolean
4731
     */
4732
    public function has_relation($relation_name)
4733
    {
4734
        $relations = $this->relation_settings();
4735
        if (isset($relations[$relation_name])) {
4736
            return true;
4737
        }
4738
        return false;
4739
    }
4740
4741
4742
4743
    /**
4744
     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4745
     * Eg, on EE_Answer that would be ANS_ID field object
4746
     *
4747
     * @param $field_obj
4748
     * @return boolean
4749
     */
4750
    public function is_primary_key_field($field_obj)
4751
    {
4752
        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4753
    }
4754
4755
4756
4757
    /**
4758
     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4759
     * Eg, on EE_Answer that would be ANS_ID field object
4760
     *
4761
     * @return EE_Model_Field_Base
4762
     * @throws EE_Error
4763
     */
4764
    public function get_primary_key_field()
4765
    {
4766
        if ($this->_primary_key_field === null) {
4767
            foreach ($this->field_settings(true) as $field_obj) {
4768
                if ($this->is_primary_key_field($field_obj)) {
4769
                    $this->_primary_key_field = $field_obj;
4770
                    break;
4771
                }
4772
            }
4773
            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4774
                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4775
                    get_class($this)));
4776
            }
4777
        }
4778
        return $this->_primary_key_field;
4779
    }
4780
4781
4782
4783
    /**
4784
     * Returns whether or not not there is a primary key on this model.
4785
     * Internally does some caching.
4786
     *
4787
     * @return boolean
4788
     */
4789
    public function has_primary_key_field()
4790
    {
4791
        if ($this->_has_primary_key_field === null) {
4792
            try {
4793
                $this->get_primary_key_field();
4794
                $this->_has_primary_key_field = true;
4795
            } catch (EE_Error $e) {
4796
                $this->_has_primary_key_field = false;
4797
            }
4798
        }
4799
        return $this->_has_primary_key_field;
4800
    }
4801
4802
4803
4804
    /**
4805
     * Finds the first field of type $field_class_name.
4806
     *
4807
     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4808
     *                                 EE_Foreign_Key_Field, etc
4809
     * @return EE_Model_Field_Base or null if none is found
4810
     */
4811
    public function get_a_field_of_type($field_class_name)
4812
    {
4813
        foreach ($this->field_settings() as $field) {
4814
            if ($field instanceof $field_class_name) {
4815
                return $field;
4816
            }
4817
        }
4818
        return null;
4819
    }
4820
4821
4822
4823
    /**
4824
     * Gets a foreign key field pointing to model.
4825
     *
4826
     * @param string $model_name eg Event, Registration, not EEM_Event
4827
     * @return EE_Foreign_Key_Field_Base
4828
     * @throws EE_Error
4829
     */
4830
    public function get_foreign_key_to($model_name)
4831
    {
4832
        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4833
            foreach ($this->field_settings() as $field) {
4834
                if (
4835
                    $field instanceof EE_Foreign_Key_Field_Base
4836
                    && in_array($model_name, $field->get_model_names_pointed_to())
4837
                ) {
4838
                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4839
                    break;
4840
                }
4841
            }
4842 View Code Duplication
            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4843
                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4844
                    'event_espresso'), $model_name, get_class($this)));
4845
            }
4846
        }
4847
        return $this->_cache_foreign_key_to_fields[$model_name];
4848
    }
4849
4850
4851
4852
    /**
4853
     * Gets the table name (including $wpdb->prefix) for the table alias
4854
     *
4855
     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4856
     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4857
     *                            Either one works
4858
     * @return string
4859
     */
4860
    public function get_table_for_alias($table_alias)
4861
    {
4862
        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4863
        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4864
    }
4865
4866
4867
4868
    /**
4869
     * Returns a flat array of all field son this model, instead of organizing them
4870
     * by table_alias as they are in the constructor.
4871
     *
4872
     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4873
     * @return EE_Model_Field_Base[] where the keys are the field's name
4874
     */
4875
    public function field_settings($include_db_only_fields = false)
4876
    {
4877
        if ($include_db_only_fields) {
4878
            if ($this->_cached_fields === null) {
4879
                $this->_cached_fields = array();
4880
                foreach ($this->_fields as $fields_corresponding_to_table) {
4881
                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4882
                        $this->_cached_fields[$field_name] = $field_obj;
4883
                    }
4884
                }
4885
            }
4886
            return $this->_cached_fields;
4887
        }
4888
        if ($this->_cached_fields_non_db_only === null) {
4889
            $this->_cached_fields_non_db_only = array();
4890
            foreach ($this->_fields as $fields_corresponding_to_table) {
4891
                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4892
                    /** @var $field_obj EE_Model_Field_Base */
4893
                    if (! $field_obj->is_db_only_field()) {
4894
                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4895
                    }
4896
                }
4897
            }
4898
        }
4899
        return $this->_cached_fields_non_db_only;
4900
    }
4901
4902
4903
4904
    /**
4905
     *        cycle though array of attendees and create objects out of each item
4906
     *
4907
     * @access        private
4908
     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4909
     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4910
     *                           numerically indexed)
4911
     * @throws EE_Error
4912
     */
4913
    protected function _create_objects($rows = array())
4914
    {
4915
        $array_of_objects = array();
4916
        if (empty($rows)) {
4917
            return array();
4918
        }
4919
        $count_if_model_has_no_primary_key = 0;
4920
        $has_primary_key = $this->has_primary_key_field();
4921
        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4922
        foreach ((array)$rows as $row) {
4923
            if (empty($row)) {
4924
                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4925
                return array();
4926
            }
4927
            //check if we've already set this object in the results array,
4928
            //in which case there's no need to process it further (again)
4929
            if ($has_primary_key) {
4930
                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4931
                    $row,
4932
                    $primary_key_field->get_qualified_column(),
4933
                    $primary_key_field->get_table_column()
4934
                );
4935
                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4936
                    continue;
4937
                }
4938
            }
4939
            $classInstance = $this->instantiate_class_from_array_or_object($row);
4940 View Code Duplication
            if (! $classInstance) {
4941
                throw new EE_Error(
4942
                    sprintf(
4943
                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4944
                        $this->get_this_model_name(),
4945
                        http_build_query($row)
4946
                    )
4947
                );
4948
            }
4949
            //set the timezone on the instantiated objects
4950
            $classInstance->set_timezone($this->_timezone);
4951
            //make sure if there is any timezone setting present that we set the timezone for the object
4952
            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4953
            $array_of_objects[$key] = $classInstance;
4954
            //also, for all the relations of type BelongsTo, see if we can cache
4955
            //those related models
4956
            //(we could do this for other relations too, but if there are conditions
4957
            //that filtered out some fo the results, then we'd be caching an incomplete set
4958
            //so it requires a little more thought than just caching them immediately...)
4959
            foreach ($this->_model_relations as $modelName => $relation_obj) {
4960
                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4961
                    //check if this model's INFO is present. If so, cache it on the model
4962
                    $other_model = $relation_obj->get_other_model();
4963
                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4964
                    //if we managed to make a model object from the results, cache it on the main model object
4965
                    if ($other_model_obj_maybe) {
4966
                        //set timezone on these other model objects if they are present
4967
                        $other_model_obj_maybe->set_timezone($this->_timezone);
4968
                        $classInstance->cache($modelName, $other_model_obj_maybe);
4969
                    }
4970
                }
4971
            }
4972
        }
4973
        return $array_of_objects;
4974
    }
4975
4976
4977
4978
    /**
4979
     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4980
     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4981
     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4982
     * object (as set in the model_field!).
4983
     *
4984
     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4985
     */
4986
    public function create_default_object()
4987
    {
4988
        $this_model_fields_and_values = array();
4989
        //setup the row using default values;
4990
        foreach ($this->field_settings() as $field_name => $field_obj) {
4991
            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4992
        }
4993
        $className = $this->_get_class_name();
4994
        $classInstance = EE_Registry::instance()
4995
                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4996
        return $classInstance;
4997
    }
4998
4999
5000
5001
    /**
5002
     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5003
     *                             or an stdClass where each property is the name of a column,
5004
     * @return EE_Base_Class
5005
     * @throws EE_Error
5006
     */
5007
    public function instantiate_class_from_array_or_object($cols_n_values)
5008
    {
5009
        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5010
            $cols_n_values = get_object_vars($cols_n_values);
5011
        }
5012
        $primary_key = null;
5013
        //make sure the array only has keys that are fields/columns on this model
5014
        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5015
        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5016
            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5017
        }
5018
        $className = $this->_get_class_name();
5019
        //check we actually found results that we can use to build our model object
5020
        //if not, return null
5021
        if ($this->has_primary_key_field()) {
5022
            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5023
                return null;
5024
            }
5025
        } else if ($this->unique_indexes()) {
5026
            $first_column = reset($this_model_fields_n_values);
5027
            if (empty($first_column)) {
5028
                return null;
5029
            }
5030
        }
5031
        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5032
        if ($primary_key) {
5033
            $classInstance = $this->get_from_entity_map($primary_key);
5034
            if (! $classInstance) {
5035
                $classInstance = EE_Registry::instance()
5036
                                            ->load_class($className,
5037
                                                array($this_model_fields_n_values, $this->_timezone), true, false);
5038
                // add this new object to the entity map
5039
                $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...
5040
            }
5041
        } else {
5042
            $classInstance = EE_Registry::instance()
5043
                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5044
                                            true, false);
5045
        }
5046
        //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.
5047
        $this->set_timezone($classInstance->get_timezone());
5048
        return $classInstance;
5049
    }
5050
5051
5052
5053
    /**
5054
     * Gets the model object from the  entity map if it exists
5055
     *
5056
     * @param int|string $id the ID of the model object
5057
     * @return EE_Base_Class
5058
     */
5059
    public function get_from_entity_map($id)
5060
    {
5061
        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5062
            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5063
    }
5064
5065
5066
5067
    /**
5068
     * add_to_entity_map
5069
     * Adds the object to the model's entity mappings
5070
     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5071
     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5072
     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5073
     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5074
     *        then this method should be called immediately after the update query
5075
     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5076
     * so on multisite, the entity map is specific to the query being done for a specific site.
5077
     *
5078
     * @param    EE_Base_Class $object
5079
     * @throws EE_Error
5080
     * @return \EE_Base_Class
5081
     */
5082
    public function add_to_entity_map(EE_Base_Class $object)
5083
    {
5084
        $className = $this->_get_class_name();
5085 View Code Duplication
        if (! $object instanceof $className) {
5086
            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5087
                is_object($object) ? get_class($object) : $object, $className));
5088
        }
5089
        /** @var $object EE_Base_Class */
5090
        if (! $object->ID()) {
5091
            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5092
                "event_espresso"), get_class($this)));
5093
        }
5094
        // double check it's not already there
5095
        $classInstance = $this->get_from_entity_map($object->ID());
5096
        if ($classInstance) {
5097
            return $classInstance;
5098
        }
5099
        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5100
        return $object;
5101
    }
5102
5103
5104
5105
    /**
5106
     * if a valid identifier is provided, then that entity is unset from the entity map,
5107
     * if no identifier is provided, then the entire entity map is emptied
5108
     *
5109
     * @param int|string $id the ID of the model object
5110
     * @return boolean
5111
     */
5112
    public function clear_entity_map($id = null)
5113
    {
5114
        if (empty($id)) {
5115
            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5116
            return true;
5117
        }
5118 View Code Duplication
        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5119
            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5120
            return true;
5121
        }
5122
        return false;
5123
    }
5124
5125
5126
5127
    /**
5128
     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5129
     * Given an array where keys are column (or column alias) names and values,
5130
     * returns an array of their corresponding field names and database values
5131
     *
5132
     * @param array $cols_n_values
5133
     * @return array
5134
     */
5135
    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5136
    {
5137
        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5138
    }
5139
5140
5141
5142
    /**
5143
     * _deduce_fields_n_values_from_cols_n_values
5144
     * Given an array where keys are column (or column alias) names and values,
5145
     * returns an array of their corresponding field names and database values
5146
     *
5147
     * @param string $cols_n_values
5148
     * @return array
5149
     */
5150
    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5151
    {
5152
        $this_model_fields_n_values = array();
5153
        foreach ($this->get_tables() as $table_alias => $table_obj) {
5154
            $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...
5155
                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5156
            //there is a primary key on this table and its not set. Use defaults for all its columns
5157
            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5158
                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5159
                    if (! $field_obj->is_db_only_field()) {
5160
                        //prepare field as if its coming from db
5161
                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5162
                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5163
                    }
5164
                }
5165
            } else {
5166
                //the table's rows existed. Use their values
5167
                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5168
                    if (! $field_obj->is_db_only_field()) {
5169
                        $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...
5170
                            $cols_n_values, $field_obj->get_qualified_column(),
5171
                            $field_obj->get_table_column()
5172
                        );
5173
                    }
5174
                }
5175
            }
5176
        }
5177
        return $this_model_fields_n_values;
5178
    }
5179
5180
5181
5182
    /**
5183
     * @param $cols_n_values
5184
     * @param $qualified_column
5185
     * @param $regular_column
5186
     * @return null
5187
     */
5188
    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5189
    {
5190
        $value = null;
5191
        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5192
        //does the field on the model relate to this column retrieved from the db?
5193
        //or is it a db-only field? (not relating to the model)
5194
        if (isset($cols_n_values[$qualified_column])) {
5195
            $value = $cols_n_values[$qualified_column];
5196
        } elseif (isset($cols_n_values[$regular_column])) {
5197
            $value = $cols_n_values[$regular_column];
5198
        }
5199
        return $value;
5200
    }
5201
5202
5203
5204
    /**
5205
     * refresh_entity_map_from_db
5206
     * Makes sure the model object in the entity map at $id assumes the values
5207
     * of the database (opposite of EE_base_Class::save())
5208
     *
5209
     * @param int|string $id
5210
     * @return EE_Base_Class
5211
     * @throws EE_Error
5212
     */
5213
    public function refresh_entity_map_from_db($id)
5214
    {
5215
        $obj_in_map = $this->get_from_entity_map($id);
5216
        if ($obj_in_map) {
5217
            $wpdb_results = $this->_get_all_wpdb_results(
5218
                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5219
            );
5220
            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...
5221
                $one_row = reset($wpdb_results);
5222
                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5223
                    $obj_in_map->set_from_db($field_name, $db_value);
5224
                }
5225
                //clear the cache of related model objects
5226
                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5227
                    $obj_in_map->clear_cache($relation_name, null, true);
5228
                }
5229
            }
5230
            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5231
            return $obj_in_map;
5232
        }
5233
        return $this->get_one_by_ID($id);
5234
    }
5235
5236
5237
5238
    /**
5239
     * refresh_entity_map_with
5240
     * Leaves the entry in the entity map alone, but updates it to match the provided
5241
     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5242
     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5243
     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5244
     *
5245
     * @param int|string    $id
5246
     * @param EE_Base_Class $replacing_model_obj
5247
     * @return \EE_Base_Class
5248
     * @throws EE_Error
5249
     */
5250
    public function refresh_entity_map_with($id, $replacing_model_obj)
5251
    {
5252
        $obj_in_map = $this->get_from_entity_map($id);
5253
        if ($obj_in_map) {
5254
            if ($replacing_model_obj instanceof EE_Base_Class) {
5255
                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5256
                    $obj_in_map->set($field_name, $value);
5257
                }
5258
                //make the model object in the entity map's cache match the $replacing_model_obj
5259
                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5260
                    $obj_in_map->clear_cache($relation_name, null, true);
5261
                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5262
                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5263
                    }
5264
                }
5265
            }
5266
            return $obj_in_map;
5267
        }
5268
        $this->add_to_entity_map($replacing_model_obj);
5269
        return $replacing_model_obj;
5270
    }
5271
5272
5273
5274
    /**
5275
     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5276
     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5277
     * require_once($this->_getClassName().".class.php");
5278
     *
5279
     * @return string
5280
     */
5281
    private function _get_class_name()
5282
    {
5283
        return "EE_" . $this->get_this_model_name();
5284
    }
5285
5286
5287
5288
    /**
5289
     * Get the name of the items this model represents, for the quantity specified. Eg,
5290
     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5291
     * it would be 'Events'.
5292
     *
5293
     * @param int $quantity
5294
     * @return string
5295
     */
5296
    public function item_name($quantity = 1)
5297
    {
5298
        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5299
    }
5300
5301
5302
5303
    /**
5304
     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5305
     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5306
     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5307
     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5308
     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5309
     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5310
     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5311
     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5312
     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5313
     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5314
     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5315
     *        return $previousReturnValue.$returnString;
5316
     * }
5317
     * require('EEM_Answer.model.php');
5318
     * $answer=EEM_Answer::instance();
5319
     * echo $answer->my_callback('monkeys',100);
5320
     * //will output "you called my_callback! and passed args:monkeys,100"
5321
     *
5322
     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5323
     * @param array  $args       array of original arguments passed to the function
5324
     * @throws EE_Error
5325
     * @return mixed whatever the plugin which calls add_filter decides
5326
     */
5327 View Code Duplication
    public function __call($methodName, $args)
5328
    {
5329
        $className = get_class($this);
5330
        $tagName = "FHEE__{$className}__{$methodName}";
5331
        if (! has_filter($tagName)) {
5332
            throw new EE_Error(
5333
                sprintf(
5334
                    __('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 );',
5335
                        'event_espresso'),
5336
                    $methodName,
5337
                    $className,
5338
                    $tagName,
5339
                    '<br />'
5340
                )
5341
            );
5342
        }
5343
        return apply_filters($tagName, null, $this, $args);
5344
    }
5345
5346
5347
5348
    /**
5349
     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5350
     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5351
     *
5352
     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5353
     *                                                       the EE_Base_Class object that corresponds to this Model,
5354
     *                                                       the object's class name
5355
     *                                                       or object's ID
5356
     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5357
     *                                                       exists in the database. If it does not, we add it
5358
     * @throws EE_Error
5359
     * @return EE_Base_Class
5360
     */
5361
    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5362
    {
5363
        $className = $this->_get_class_name();
5364
        if ($base_class_obj_or_id instanceof $className) {
5365
            $model_object = $base_class_obj_or_id;
5366
        } else {
5367
            $primary_key_field = $this->get_primary_key_field();
5368
            if (
5369
                $primary_key_field instanceof EE_Primary_Key_Int_Field
5370
                && (
5371
                    is_int($base_class_obj_or_id)
5372
                    || is_string($base_class_obj_or_id)
5373
                )
5374
            ) {
5375
                // assume it's an ID.
5376
                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5377
                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5378
            } else if (
5379
                $primary_key_field instanceof EE_Primary_Key_String_Field
5380
                && is_string($base_class_obj_or_id)
5381
            ) {
5382
                // assume its a string representation of the object
5383
                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5384
            } else {
5385
                throw new EE_Error(
5386
                    sprintf(
5387
                        __(
5388
                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5389
                            'event_espresso'
5390
                        ),
5391
                        $base_class_obj_or_id,
5392
                        $this->_get_class_name(),
5393
                        print_r($base_class_obj_or_id, true)
5394
                    )
5395
                );
5396
            }
5397
        }
5398
        if ($ensure_is_in_db && $model_object->ID() !== null) {
5399
            $model_object->save();
5400
        }
5401
        return $model_object;
5402
    }
5403
5404
5405
5406
    /**
5407
     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5408
     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5409
     * returns it ID.
5410
     *
5411
     * @param EE_Base_Class|int|string $base_class_obj_or_id
5412
     * @return int|string depending on the type of this model object's ID
5413
     * @throws EE_Error
5414
     */
5415
    public function ensure_is_ID($base_class_obj_or_id)
5416
    {
5417
        $className = $this->_get_class_name();
5418
        if ($base_class_obj_or_id instanceof $className) {
5419
            /** @var $base_class_obj_or_id EE_Base_Class */
5420
            $id = $base_class_obj_or_id->ID();
5421
        } elseif (is_int($base_class_obj_or_id)) {
5422
            //assume it's an ID
5423
            $id = $base_class_obj_or_id;
5424
        } elseif (is_string($base_class_obj_or_id)) {
5425
            //assume its a string representation of the object
5426
            $id = $base_class_obj_or_id;
5427
        } else {
5428
            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5429
                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5430
                print_r($base_class_obj_or_id, true)));
5431
        }
5432
        return $id;
5433
    }
5434
5435
5436
5437
    /**
5438
     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5439
     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5440
     * been sanitized and converted into the appropriate domain.
5441
     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5442
     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5443
     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5444
     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5445
     * $EVT = EEM_Event::instance(); $old_setting =
5446
     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5447
     * $EVT->assume_values_already_prepared_by_model_object(true);
5448
     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5449
     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5450
     *
5451
     * @param int $values_already_prepared like one of the constants on EEM_Base
5452
     * @return void
5453
     */
5454
    public function assume_values_already_prepared_by_model_object(
5455
        $values_already_prepared = self::not_prepared_by_model_object
5456
    ) {
5457
        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5458
    }
5459
5460
5461
5462
    /**
5463
     * Read comments for assume_values_already_prepared_by_model_object()
5464
     *
5465
     * @return int
5466
     */
5467
    public function get_assumption_concerning_values_already_prepared_by_model_object()
5468
    {
5469
        return $this->_values_already_prepared_by_model_object;
5470
    }
5471
5472
5473
5474
    /**
5475
     * Gets all the indexes on this model
5476
     *
5477
     * @return EE_Index[]
5478
     */
5479
    public function indexes()
5480
    {
5481
        return $this->_indexes;
5482
    }
5483
5484
5485
5486
    /**
5487
     * Gets all the Unique Indexes on this model
5488
     *
5489
     * @return EE_Unique_Index[]
5490
     */
5491
    public function unique_indexes()
5492
    {
5493
        $unique_indexes = array();
5494
        foreach ($this->_indexes as $name => $index) {
5495
            if ($index instanceof EE_Unique_Index) {
5496
                $unique_indexes [$name] = $index;
5497
            }
5498
        }
5499
        return $unique_indexes;
5500
    }
5501
5502
5503
5504
    /**
5505
     * Gets all the fields which, when combined, make the primary key.
5506
     * This is usually just an array with 1 element (the primary key), but in cases
5507
     * where there is no primary key, it's a combination of fields as defined
5508
     * on a primary index
5509
     *
5510
     * @return EE_Model_Field_Base[] indexed by the field's name
5511
     * @throws EE_Error
5512
     */
5513
    public function get_combined_primary_key_fields()
5514
    {
5515
        foreach ($this->indexes() as $index) {
5516
            if ($index instanceof EE_Primary_Key_Index) {
5517
                return $index->fields();
5518
            }
5519
        }
5520
        return array($this->primary_key_name() => $this->get_primary_key_field());
5521
    }
5522
5523
5524
5525
    /**
5526
     * Used to build a primary key string (when the model has no primary key),
5527
     * which can be used a unique string to identify this model object.
5528
     *
5529
     * @param array $cols_n_values keys are field names, values are their values
5530
     * @return string
5531
     * @throws EE_Error
5532
     */
5533
    public function get_index_primary_key_string($cols_n_values)
5534
    {
5535
        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5536
            $this->get_combined_primary_key_fields());
5537
        return http_build_query($cols_n_values_for_primary_key_index);
5538
    }
5539
5540
5541
5542
    /**
5543
     * Gets the field values from the primary key string
5544
     *
5545
     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5546
     * @param string $index_primary_key_string
5547
     * @return null|array
5548
     * @throws EE_Error
5549
     */
5550
    public function parse_index_primary_key_string($index_primary_key_string)
5551
    {
5552
        $key_fields = $this->get_combined_primary_key_fields();
5553
        //check all of them are in the $id
5554
        $key_vals_in_combined_pk = array();
5555
        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5556
        foreach ($key_fields as $key_field_name => $field_obj) {
5557
            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5558
                return null;
5559
            }
5560
        }
5561
        return $key_vals_in_combined_pk;
5562
    }
5563
5564
5565
5566
    /**
5567
     * verifies that an array of key-value pairs for model fields has a key
5568
     * for each field comprising the primary key index
5569
     *
5570
     * @param array $key_vals
5571
     * @return boolean
5572
     * @throws EE_Error
5573
     */
5574
    public function has_all_combined_primary_key_fields($key_vals)
5575
    {
5576
        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5577
        foreach ($keys_it_should_have as $key) {
5578
            if (! isset($key_vals[$key])) {
5579
                return false;
5580
            }
5581
        }
5582
        return true;
5583
    }
5584
5585
5586
5587
    /**
5588
     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5589
     * We consider something to be a copy if all the attributes match (except the ID, of course).
5590
     *
5591
     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5592
     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5593
     * @throws EE_Error
5594
     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5595
     *                                                              indexed)
5596
     */
5597
    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5598
    {
5599 View Code Duplication
        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5600
            $attributes_array = $model_object_or_attributes_array->model_field_array();
5601
        } elseif (is_array($model_object_or_attributes_array)) {
5602
            $attributes_array = $model_object_or_attributes_array;
5603
        } else {
5604
            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",
5605
                "event_espresso"), $model_object_or_attributes_array));
5606
        }
5607
        //even copies obviously won't have the same ID, so remove the primary key
5608
        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5609
        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5610
            unset($attributes_array[$this->primary_key_name()]);
5611
        }
5612
        if (isset($query_params[0])) {
5613
            $query_params[0] = array_merge($attributes_array, $query_params);
5614
        } else {
5615
            $query_params[0] = $attributes_array;
5616
        }
5617
        return $this->get_all($query_params);
5618
    }
5619
5620
5621
5622
    /**
5623
     * Gets the first copy we find. See get_all_copies for more details
5624
     *
5625
     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5626
     * @param array $query_params
5627
     * @return EE_Base_Class
5628
     * @throws EE_Error
5629
     */
5630 View Code Duplication
    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5631
    {
5632
        if (! is_array($query_params)) {
5633
            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5634
                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5635
                    gettype($query_params)), '4.6.0');
5636
            $query_params = array();
5637
        }
5638
        $query_params['limit'] = 1;
5639
        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5640
        if (is_array($copies)) {
5641
            return array_shift($copies);
5642
        }
5643
        return null;
5644
    }
5645
5646
5647
5648
    /**
5649
     * Updates the item with the specified id. Ignores default query parameters because
5650
     * we have specified the ID, and its assumed we KNOW what we're doing
5651
     *
5652
     * @param array      $fields_n_values keys are field names, values are their new values
5653
     * @param int|string $id              the value of the primary key to update
5654
     * @return int number of rows updated
5655
     * @throws EE_Error
5656
     */
5657
    public function update_by_ID($fields_n_values, $id)
5658
    {
5659
        $query_params = array(
5660
            0                          => array($this->get_primary_key_field()->get_name() => $id),
5661
            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5662
        );
5663
        return $this->update($fields_n_values, $query_params);
5664
    }
5665
5666
5667
5668
    /**
5669
     * Changes an operator which was supplied to the models into one usable in SQL
5670
     *
5671
     * @param string $operator_supplied
5672
     * @return string an operator which can be used in SQL
5673
     * @throws EE_Error
5674
     */
5675
    private function _prepare_operator_for_sql($operator_supplied)
5676
    {
5677
        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5678
            : null;
5679
        if ($sql_operator) {
5680
            return $sql_operator;
5681
        }
5682
        throw new EE_Error(
5683
            sprintf(
5684
                __(
5685
                    "The operator '%s' is not in the list of valid operators: %s",
5686
                    "event_espresso"
5687
                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5688
            )
5689
        );
5690
    }
5691
5692
5693
5694
    /**
5695
     * Gets an array where keys are the primary keys and values are their 'names'
5696
     * (as determined by the model object's name() function, which is often overridden)
5697
     *
5698
     * @param array $query_params like get_all's
5699
     * @return string[]
5700
     * @throws EE_Error
5701
     */
5702
    public function get_all_names($query_params = array())
5703
    {
5704
        $objs = $this->get_all($query_params);
5705
        $names = array();
5706
        foreach ($objs as $obj) {
5707
            $names[$obj->ID()] = $obj->name();
5708
        }
5709
        return $names;
5710
    }
5711
5712
5713
5714
    /**
5715
     * Gets an array of primary keys from the model objects. If you acquired the model objects
5716
     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5717
     * this is duplicated effort and reduces efficiency) you would be better to use
5718
     * array_keys() on $model_objects.
5719
     *
5720
     * @param \EE_Base_Class[] $model_objects
5721
     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5722
     *                                               in the returned array
5723
     * @return array
5724
     * @throws EE_Error
5725
     */
5726
    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5727
    {
5728
        if (! $this->has_primary_key_field()) {
5729
            if (WP_DEBUG) {
5730
                EE_Error::add_error(
5731
                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5732
                    __FILE__,
5733
                    __FUNCTION__,
5734
                    __LINE__
5735
                );
5736
            }
5737
        }
5738
        $IDs = array();
5739
        foreach ($model_objects as $model_object) {
5740
            $id = $model_object->ID();
5741
            if (! $id) {
5742
                if ($filter_out_empty_ids) {
5743
                    continue;
5744
                }
5745
                if (WP_DEBUG) {
5746
                    EE_Error::add_error(
5747
                        __(
5748
                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5749
                            'event_espresso'
5750
                        ),
5751
                        __FILE__,
5752
                        __FUNCTION__,
5753
                        __LINE__
5754
                    );
5755
                }
5756
            }
5757
            $IDs[] = $id;
5758
        }
5759
        return $IDs;
5760
    }
5761
5762
5763
5764
    /**
5765
     * Returns the string used in capabilities relating to this model. If there
5766
     * are no capabilities that relate to this model returns false
5767
     *
5768
     * @return string|false
5769
     */
5770
    public function cap_slug()
5771
    {
5772
        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5773
    }
5774
5775
5776
5777
    /**
5778
     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5779
     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5780
     * only returns the cap restrictions array in that context (ie, the array
5781
     * at that key)
5782
     *
5783
     * @param string $context
5784
     * @return EE_Default_Where_Conditions[] indexed by associated capability
5785
     * @throws EE_Error
5786
     */
5787
    public function cap_restrictions($context = EEM_Base::caps_read)
5788
    {
5789
        EEM_Base::verify_is_valid_cap_context($context);
5790
        //check if we ought to run the restriction generator first
5791
        if (
5792
            isset($this->_cap_restriction_generators[$context])
5793
            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5794
            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5795
        ) {
5796
            $this->_cap_restrictions[$context] = array_merge(
5797
                $this->_cap_restrictions[$context],
5798
                $this->_cap_restriction_generators[$context]->generate_restrictions()
5799
            );
5800
        }
5801
        //and make sure we've finalized the construction of each restriction
5802
        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5803
            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5804
                $where_conditions_obj->_finalize_construct($this);
5805
            }
5806
        }
5807
        return $this->_cap_restrictions[$context];
5808
    }
5809
5810
5811
5812
    /**
5813
     * Indicating whether or not this model thinks its a wp core model
5814
     *
5815
     * @return boolean
5816
     */
5817
    public function is_wp_core_model()
5818
    {
5819
        return $this->_wp_core_model;
5820
    }
5821
5822
5823
5824
    /**
5825
     * Gets all the caps that are missing which impose a restriction on
5826
     * queries made in this context
5827
     *
5828
     * @param string $context one of EEM_Base::caps_ constants
5829
     * @return EE_Default_Where_Conditions[] indexed by capability name
5830
     * @throws EE_Error
5831
     */
5832
    public function caps_missing($context = EEM_Base::caps_read)
5833
    {
5834
        $missing_caps = array();
5835
        $cap_restrictions = $this->cap_restrictions($context);
5836
        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5837
            if (! EE_Capabilities::instance()
5838
                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5839
            ) {
5840
                $missing_caps[$cap] = $restriction_if_no_cap;
5841
            }
5842
        }
5843
        return $missing_caps;
5844
    }
5845
5846
5847
5848
    /**
5849
     * Gets the mapping from capability contexts to action strings used in capability names
5850
     *
5851
     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5852
     * one of 'read', 'edit', or 'delete'
5853
     */
5854
    public function cap_contexts_to_cap_action_map()
5855
    {
5856
        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5857
            $this);
5858
    }
5859
5860
5861
5862
    /**
5863
     * Gets the action string for the specified capability context
5864
     *
5865
     * @param string $context
5866
     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5867
     * @throws EE_Error
5868
     */
5869
    public function cap_action_for_context($context)
5870
    {
5871
        $mapping = $this->cap_contexts_to_cap_action_map();
5872
        if (isset($mapping[$context])) {
5873
            return $mapping[$context];
5874
        }
5875
        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5876
            return $action;
5877
        }
5878
        throw new EE_Error(
5879
            sprintf(
5880
                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5881
                $context,
5882
                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5883
            )
5884
        );
5885
    }
5886
5887
5888
5889
    /**
5890
     * Returns all the capability contexts which are valid when querying models
5891
     *
5892
     * @return array
5893
     */
5894
    public static function valid_cap_contexts()
5895
    {
5896
        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5897
            self::caps_read,
5898
            self::caps_read_admin,
5899
            self::caps_edit,
5900
            self::caps_delete,
5901
        ));
5902
    }
5903
5904
5905
5906
    /**
5907
     * Returns all valid options for 'default_where_conditions'
5908
     *
5909
     * @return array
5910
     */
5911
    public static function valid_default_where_conditions()
5912
    {
5913
        return array(
5914
            EEM_Base::default_where_conditions_all,
5915
            EEM_Base::default_where_conditions_this_only,
5916
            EEM_Base::default_where_conditions_others_only,
5917
            EEM_Base::default_where_conditions_minimum_all,
5918
            EEM_Base::default_where_conditions_minimum_others,
5919
            EEM_Base::default_where_conditions_none
5920
        );
5921
    }
5922
5923
    // public static function default_where_conditions_full
5924
    /**
5925
     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5926
     *
5927
     * @param string $context
5928
     * @return bool
5929
     * @throws EE_Error
5930
     */
5931
    static public function verify_is_valid_cap_context($context)
5932
    {
5933
        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5934
        if (in_array($context, $valid_cap_contexts)) {
5935
            return true;
5936
        }
5937
        throw new EE_Error(
5938
            sprintf(
5939
                __(
5940
                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5941
                    'event_espresso'
5942
                ),
5943
                $context,
5944
                'EEM_Base',
5945
                implode(',', $valid_cap_contexts)
5946
            )
5947
        );
5948
    }
5949
5950
5951
5952
    /**
5953
     * Clears all the models field caches. This is only useful when a sub-class
5954
     * might have added a field or something and these caches might be invalidated
5955
     */
5956
    protected function _invalidate_field_caches()
5957
    {
5958
        $this->_cache_foreign_key_to_fields = array();
5959
        $this->_cached_fields = null;
5960
        $this->_cached_fields_non_db_only = null;
5961
    }
5962
5963
5964
5965
    /**
5966
     * Gets the list of all the where query param keys that relate to logic instead of field names
5967
     * (eg "and", "or", "not").
5968
     *
5969
     * @return array
5970
     */
5971
    public function logic_query_param_keys()
5972
    {
5973
        return $this->_logic_query_param_keys;
5974
    }
5975
5976
5977
5978
    /**
5979
     * Determines whether or not the where query param array key is for a logic query param.
5980
     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
5981
     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5982
     *
5983
     * @param $query_param_key
5984
     * @return bool
5985
     */
5986
    public function is_logic_query_param_key($query_param_key)
5987
    {
5988
        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5989
            if ($query_param_key === $logic_query_param_key
5990
                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5991
            ) {
5992
                return true;
5993
            }
5994
        }
5995
        return false;
5996
    }
5997
5998
5999
6000
}
6001