Completed
Branch master (24c3eb)
by
unknown
34:49 queued 28:57
created
core/db_classes/EE_Base_Class.class.php 2 patches
Indentation   +3359 added lines, -3359 removed lines patch added patch discarded remove patch
@@ -15,3374 +15,3374 @@
 block discarded – undo
15 15
  */
16 16
 abstract class EE_Base_Class
17 17
 {
18
-    /**
19
-     * @var EEM_Base|null
20
-     */
21
-    protected $_model = null;
22
-
23
-    /**
24
-     * This is an array of the original properties and values provided during construction
25
-     * of this model object. (keys are model field names, values are their values).
26
-     * This list is important to remember so that when we are merging data from the db, we know
27
-     * which values to override and which to not override.
28
-     */
29
-    protected ?array $_props_n_values_provided_in_constructor = null;
30
-
31
-    /**
32
-     * Timezone
33
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
34
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
35
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
36
-     * access to it.
37
-     */
38
-    protected string $_timezone = '';
39
-
40
-    /**
41
-     * date format
42
-     * pattern or format for displaying dates
43
-     */
44
-    protected string $_dt_frmt = '';
45
-
46
-    /**
47
-     * time format
48
-     * pattern or format for displaying time
49
-     */
50
-    protected string $_tm_frmt = '';
51
-
52
-    /**
53
-     * This property is for holding a cached array of object properties indexed by property name as the key.
54
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
55
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
56
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
57
-     */
58
-    protected array $_cached_properties = [];
59
-
60
-    /**
61
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
62
-     * single
63
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
64
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
65
-     * all others have an array)
66
-     */
67
-    protected array $_model_relations = [];
68
-
69
-    /**
70
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
71
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
72
-     */
73
-    protected array $_fields = [];
74
-
75
-    /**
76
-     * indicating whether or not this model object is intended to ever be saved
77
-     * For example, we might create model objects intended to only be used for the duration
78
-     * of this request and to be thrown away, and if they were accidentally saved
79
-     * it would be a bug.
80
-     */
81
-    protected bool $_allow_persist = true;
82
-
83
-    /**
84
-     * indicating whether or not this model object's properties have changed since construction
85
-     */
86
-    protected bool $_has_changes = false;
87
-
88
-    /**
89
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
90
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
91
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
92
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
93
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
94
-     * array as:
95
-     * array(
96
-     *  'Registration_Count' => 24
97
-     * );
98
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
99
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
100
-     * info)
101
-     */
102
-    protected array $custom_selection_results = [];
103
-
104
-
105
-    /**
106
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
107
-     * play nice
108
-     *
109
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
110
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
111
-     *                                                         TXN_amount, QST_name, etc) and values are their values
112
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
113
-     *                                                         corresponding db model or not.
114
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
115
-     *                                                         be in when instantiating a EE_Base_Class object.
116
-     * @param array   $date_formats                            An array of date formats to set on construct where first
117
-     *                                                         value is the date_format and second value is the time
118
-     *                                                         format.
119
-     * @throws InvalidArgumentException
120
-     * @throws InvalidInterfaceException
121
-     * @throws InvalidDataTypeException
122
-     * @throws EE_Error
123
-     * @throws ReflectionException
124
-     */
125
-    protected function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
126
-    {
127
-        $className = get_class($this);
128
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
129
-        $model        = $this->get_model();
130
-        $model_fields = $model->field_settings();
131
-        // ensure $fieldValues is an array
132
-        $fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
133
-        // verify client code has not passed any invalid field names
134
-        foreach ($fieldValues as $field_name => $field_value) {
135
-            if (! isset($model_fields[ $field_name ])) {
136
-                throw new EE_Error(
137
-                    sprintf(
138
-                        esc_html__(
139
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
140
-                            'event_espresso'
141
-                        ),
142
-                        $field_name,
143
-                        get_class($this),
144
-                        implode(', ', array_keys($model_fields))
145
-                    )
146
-                );
147
-            }
148
-        }
149
-
150
-        $date_format     = null;
151
-        $time_format     = null;
152
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
153
-        if (! empty($date_formats) && is_array($date_formats)) {
154
-            [$date_format, $time_format] = $date_formats;
155
-        }
156
-        $this->set_date_format($date_format);
157
-        $this->set_time_format($time_format);
158
-        // if db model is instantiating
159
-        foreach ($model_fields as $fieldName => $field) {
160
-            if ($bydb) {
161
-                // client code has indicated these field values are from the database
162
-                $this->set_from_db(
163
-                    $fieldName,
164
-                    $fieldValues[ $fieldName ] ?? null
165
-                );
166
-            } else {
167
-                // we're constructing a brand new instance of the model object.
168
-                // Generally, this means we'll need to do more field validation
169
-                $this->set(
170
-                    $fieldName,
171
-                    $fieldValues[ $fieldName ] ?? null,
172
-                    true
173
-                );
174
-            }
175
-        }
176
-        // remember what values were passed to this constructor
177
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
178
-        // remember in entity mapper
179
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
180
-            $model->add_to_entity_map($this);
181
-        }
182
-        // setup all the relations
183
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
184
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
185
-                $this->_model_relations[ $relation_name ] = null;
186
-            } else {
187
-                $this->_model_relations[ $relation_name ] = [];
188
-            }
189
-        }
190
-        /**
191
-         * Action done at the end of each model object construction
192
-         *
193
-         * @param EE_Base_Class $this the model object just created
194
-         */
195
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
196
-    }
197
-
198
-
199
-    /**
200
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
201
-     *
202
-     * @return boolean
203
-     */
204
-    public function allow_persist()
205
-    {
206
-        return $this->_allow_persist;
207
-    }
208
-
209
-
210
-    /**
211
-     * Sets whether or not this model object should be allowed to be saved to the DB.
212
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
213
-     * you got new information that somehow made you change your mind.
214
-     *
215
-     * @param boolean $allow_persist
216
-     * @return boolean
217
-     */
218
-    public function set_allow_persist($allow_persist)
219
-    {
220
-        return $this->_allow_persist = $allow_persist;
221
-    }
222
-
223
-
224
-    /**
225
-     * Gets the field's original value when this object was constructed during this request.
226
-     * This can be helpful when determining if a model object has changed or not
227
-     *
228
-     * @param string $field_name
229
-     * @return mixed|null
230
-     * @throws ReflectionException
231
-     * @throws InvalidArgumentException
232
-     * @throws InvalidInterfaceException
233
-     * @throws InvalidDataTypeException
234
-     * @throws EE_Error
235
-     */
236
-    public function get_original($field_name)
237
-    {
238
-        if (
239
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
240
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
241
-        ) {
242
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
243
-        }
244
-        return null;
245
-    }
246
-
247
-
248
-    /**
249
-     * @param EE_Base_Class $obj
250
-     * @return string
251
-     */
252
-    public function get_class($obj)
253
-    {
254
-        return get_class($obj);
255
-    }
256
-
257
-
258
-    /**
259
-     * Overrides parent because parent expects old models.
260
-     * This also doesn't do any validation, and won't work for serialized arrays
261
-     *
262
-     * @param string $field_name
263
-     * @param mixed  $field_value
264
-     * @param bool   $use_default
265
-     * @throws InvalidArgumentException
266
-     * @throws InvalidInterfaceException
267
-     * @throws InvalidDataTypeException
268
-     * @throws EE_Error
269
-     * @throws ReflectionException
270
-     * @throws Exception
271
-     */
272
-    public function set(string $field_name, $field_value, bool $use_default = false)
273
-    {
274
-        // if not using default and nothing has changed, and object has already been setup (has ID),
275
-        // then don't do anything
276
-        if (
277
-            ! $use_default
278
-            && $this->_fields[ $field_name ] === $field_value
279
-            && $this->ID()
280
-        ) {
281
-            return;
282
-        }
283
-        $model              = $this->get_model();
284
-        $this->_has_changes = true;
285
-        $field_obj          = $model->field_settings_for($field_name);
286
-        if (! $field_obj instanceof EE_Model_Field_Base) {
287
-            throw new EE_Error(
288
-                sprintf(
289
-                    esc_html__(
290
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
291
-                        'event_espresso'
292
-                    ),
293
-                    $field_name
294
-                )
295
-            );
296
-        }
297
-        // if ( method_exists( $field_obj, 'set_timezone' )) {
298
-        if ($field_obj instanceof EE_Datetime_Field) {
299
-            $field_obj->set_timezone($this->_timezone);
300
-            $field_obj->set_date_format($this->_dt_frmt);
301
-            $field_obj->set_time_format($this->_tm_frmt);
302
-        }
303
-
304
-        // should the value be null?
305
-        $value = $field_value === null && ($use_default || ! $field_obj->is_nullable())
306
-            ? $field_obj->get_default_value()
307
-            : $field_value;
308
-
309
-        $this->_fields[ $field_name ] = $field_obj->prepare_for_set($value);
310
-
311
-        // if we're not in the constructor...
312
-        // now check if what we set was a primary key
313
-        if (
314
-            // note: props_n_values_provided_in_constructor is only set at the END of the constructor
315
-            $this->_props_n_values_provided_in_constructor
316
-            && $field_value
317
-            && $field_name === $model->primary_key_name()
318
-        ) {
319
-            // if so, we want all this object's fields to be filled either with
320
-            // what we've explicitly set on this model
321
-            // or what we have in the db
322
-            // echo "setting primary key!";
323
-            $fields_on_model = self::_get_model(get_class($this))->field_settings();
324
-            $obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
325
-            foreach ($fields_on_model as $field_obj) {
326
-                if (
327
-                    ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
328
-                    && $field_obj->get_name() !== $field_name
329
-                ) {
330
-                    $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
331
-                }
332
-            }
333
-            // oh this model object has an ID? well make sure its in the entity mapper
334
-            $model->add_to_entity_map($this);
335
-        }
336
-        // let's unset any cache for this field_name from the $_cached_properties property.
337
-        $this->_clear_cached_property($field_name);
338
-    }
339
-
340
-
341
-    /**
342
-     * Overrides parent because parent expects old models.
343
-     * This also doesn't do any validation, and won't work for serialized arrays
344
-     *
345
-     * @param string $field_name
346
-     * @param mixed  $field_value_from_db
347
-     * @throws ReflectionException
348
-     * @throws InvalidArgumentException
349
-     * @throws InvalidInterfaceException
350
-     * @throws InvalidDataTypeException
351
-     * @throws EE_Error
352
-     */
353
-    public function set_from_db(string $field_name, $field_value_from_db)
354
-    {
355
-        $field_obj = $this->get_model()->field_settings_for($field_name);
356
-        if ($field_obj instanceof EE_Model_Field_Base) {
357
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
358
-            // eg, a CPT model object could have an entry in the posts table, but no
359
-            // entry in the meta table. Meaning that all its columns in the meta table
360
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
361
-            if ($field_value_from_db === null) {
362
-                if ($field_obj->is_nullable()) {
363
-                    // if the field allows nulls, then let it be null
364
-                    $field_value = null;
365
-                } else {
366
-                    $field_value = $field_obj->get_default_value();
367
-                }
368
-            } else {
369
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
370
-            }
371
-            $this->_fields[ $field_name ] = $field_value;
372
-            $this->_clear_cached_property($field_name);
373
-        }
374
-    }
375
-
376
-
377
-    /**
378
-     * Set custom select values for model.
379
-     *
380
-     * @param array $custom_select_values
381
-     */
382
-    public function setCustomSelectsValues(array $custom_select_values)
383
-    {
384
-        $this->custom_selection_results = $custom_select_values;
385
-    }
386
-
387
-
388
-    /**
389
-     * Returns the custom select value for the provided alias if its set.
390
-     * If not set, returns null.
391
-     *
392
-     * @param string $alias
393
-     * @return string|int|float|null
394
-     */
395
-    public function getCustomSelect($alias)
396
-    {
397
-        return $this->custom_selection_results[ $alias ] ?? null;
398
-    }
399
-
400
-
401
-    /**
402
-     * This sets the field value on the db column if it exists for the given $column_name or
403
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
404
-     *
405
-     * @param string $field_name  Must be the exact column name.
406
-     * @param mixed  $field_value The value to set.
407
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
-     * @throws InvalidArgumentException
409
-     * @throws InvalidInterfaceException
410
-     * @throws InvalidDataTypeException
411
-     * @throws EE_Error
412
-     * @throws ReflectionException
413
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
414
-     */
415
-    public function set_field_or_extra_meta($field_name, $field_value)
416
-    {
417
-        if ($this->get_model()->has_field($field_name)) {
418
-            $this->set($field_name, $field_value);
419
-            return true;
420
-        }
421
-        // ensure this object is saved first so that extra meta can be properly related.
422
-        $this->save();
423
-        return $this->update_extra_meta($field_name, $field_value);
424
-    }
425
-
426
-
427
-    /**
428
-     * This retrieves the value of the db column set on this class or if that's not present
429
-     * it will attempt to retrieve from extra_meta if found.
430
-     * Example Usage:
431
-     * Via EE_Message child class:
432
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
433
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
434
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
435
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
436
-     * value for those extra fields dynamically via the EE_message object.
437
-     *
438
-     * @param string $field_name expecting the fully qualified field name.
439
-     * @return mixed|null  value for the field if found.  null if not found.
440
-     * @throws ReflectionException
441
-     * @throws InvalidArgumentException
442
-     * @throws InvalidInterfaceException
443
-     * @throws InvalidDataTypeException
444
-     * @throws EE_Error
445
-     */
446
-    public function get_field_or_extra_meta($field_name)
447
-    {
448
-        if ($this->get_model()->has_field($field_name)) {
449
-            $column_value = $this->get($field_name);
450
-        } else {
451
-            // This isn't a column in the main table, let's see if it is in the extra meta.
452
-            $column_value = $this->get_extra_meta($field_name, true, null);
453
-        }
454
-        return $column_value;
455
-    }
456
-
457
-
458
-    /**
459
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
460
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
461
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
462
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
463
-     *
464
-     * @access public
465
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
466
-     * @return void
467
-     * @throws InvalidArgumentException
468
-     * @throws InvalidInterfaceException
469
-     * @throws InvalidDataTypeException
470
-     * @throws EE_Error
471
-     * @throws ReflectionException
472
-     * @throws Exception
473
-     */
474
-    public function set_timezone($timezone = '')
475
-    {
476
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
477
-        // make sure we clear all cached properties because they won't be relevant now
478
-        $this->_clear_cached_properties();
479
-        // make sure we update field settings and the date for all EE_Datetime_Fields
480
-        $model_fields = $this->get_model()->field_settings(false);
481
-        foreach ($model_fields as $field_name => $field_obj) {
482
-            if ($field_obj instanceof EE_Datetime_Field) {
483
-                $field_obj->set_timezone($this->_timezone);
484
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
485
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
486
-                }
487
-            }
488
-        }
489
-    }
490
-
491
-
492
-    /**
493
-     * This just returns whatever is set for the current timezone.
494
-     *
495
-     * @access public
496
-     * @return string timezone string
497
-     */
498
-    public function get_timezone()
499
-    {
500
-        return $this->_timezone;
501
-    }
502
-
503
-
504
-    /**
505
-     * This sets the internal date format to what is sent in to be used as the new default for the class
506
-     * internally instead of wp set date format options
507
-     *
508
-     * @param string|null $format should be a format recognizable by PHP date() functions.
509
-     * @since 4.6
510
-     */
511
-    public function set_date_format(?string $format)
512
-    {
513
-        $this->_dt_frmt = new DateFormat($format);
514
-        // clear cached_properties because they won't be relevant now.
515
-        $this->_clear_cached_properties();
516
-    }
517
-
518
-
519
-    /**
520
-     * This sets the internal time format string to what is sent in to be used as the new default for the
521
-     * class internally instead of wp set time format options.
522
-     *
523
-     * @param string|null $format should be a format recognizable by PHP date() functions.
524
-     * @since 4.6
525
-     */
526
-    public function set_time_format(?string $format)
527
-    {
528
-        $this->_tm_frmt = new TimeFormat($format);
529
-        // clear cached_properties because they won't be relevant now.
530
-        $this->_clear_cached_properties();
531
-    }
532
-
533
-
534
-    /**
535
-     * This returns the current internal set format for the date and time formats.
536
-     *
537
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
538
-     *                             where the first value is the date format and the second value is the time format.
539
-     * @return string|array
540
-     */
541
-    public function get_format($full = true)
542
-    {
543
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
544
-    }
545
-
546
-
547
-    /**
548
-     * cache
549
-     * stores the passed model object on the current model object.
550
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
551
-     *
552
-     * @param string        $relation_name   one of the keys in the _model_relations array on the model. Eg
553
-     *                                       'Registration' associated with this model object
554
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
555
-     *                                       that could be a payment or a registration)
556
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
557
-     *                                       items which will be stored in an array on this object
558
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
559
-     *                                       related thing, no array)
560
-     * @throws InvalidArgumentException
561
-     * @throws InvalidInterfaceException
562
-     * @throws InvalidDataTypeException
563
-     * @throws EE_Error
564
-     * @throws ReflectionException
565
-     */
566
-    public function cache($relation_name = '', $object_to_cache = null, $cache_id = null)
567
-    {
568
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
569
-        if (! $object_to_cache instanceof EE_Base_Class) {
570
-            return false;
571
-        }
572
-        // also get "how" the object is related, or throw an error
573
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
574
-            throw new EE_Error(
575
-                sprintf(
576
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
577
-                    $relation_name,
578
-                    get_class($this)
579
-                )
580
-            );
581
-        }
582
-        // how many things are related ?
583
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
584
-            // if it's a "belongs to" relationship, then there's only one related model object
585
-            // eg, if this is a registration, there's only 1 attendee for it
586
-            // so for these model objects just set it to be cached
587
-            $this->_model_relations[ $relation_name ] = $object_to_cache;
588
-            $return                                   = true;
589
-        } else {
590
-            // otherwise, this is the "many" side of a one to many relationship,
591
-            // so we'll add the object to the array of related objects for that type.
592
-            // eg: if this is an event, there are many registrations for that event,
593
-            // so we cache the registrations in an array
594
-            if (! is_array($this->_model_relations[ $relation_name ])) {
595
-                // if for some reason, the cached item is a model object,
596
-                // then stick that in the array, otherwise start with an empty array
597
-                $this->_model_relations[ $relation_name ] =
598
-                    $this->_model_relations[ $relation_name ] instanceof EE_Base_Class
599
-                        ? [$this->_model_relations[ $relation_name ]]
600
-                        : [];
601
-            }
602
-            // first check for a cache_id which is normally empty
603
-            if (! empty($cache_id)) {
604
-                // if the cache_id exists, then it means we are purposely trying to cache this
605
-                // with a known key that can then be used to retrieve the object later on
606
-                $this->_model_relations[ $relation_name ][ $cache_id ] = $object_to_cache;
607
-                $return                                                = $cache_id;
608
-            } elseif ($object_to_cache->ID()) {
609
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
610
-                $this->_model_relations[ $relation_name ][ $object_to_cache->ID() ] = $object_to_cache;
611
-                $return                                                             = $object_to_cache->ID();
612
-            } else {
613
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
614
-                $this->_model_relations[ $relation_name ][] = $object_to_cache;
615
-                // move the internal pointer to the end of the array
616
-                end($this->_model_relations[ $relation_name ]);
617
-                // and grab the key so that we can return it
618
-                $return = key($this->_model_relations[ $relation_name ]);
619
-            }
620
-        }
621
-        return $return;
622
-    }
623
-
624
-
625
-    /**
626
-     * For adding an item to the cached_properties property.
627
-     *
628
-     * @access protected
629
-     * @param string      $fieldname the property item the corresponding value is for.
630
-     * @param mixed       $value     The value we are caching.
631
-     * @param string|null $cache_type
632
-     * @return void
633
-     * @throws ReflectionException
634
-     * @throws InvalidArgumentException
635
-     * @throws InvalidInterfaceException
636
-     * @throws InvalidDataTypeException
637
-     * @throws EE_Error
638
-     */
639
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
640
-    {
641
-        // first make sure this property exists
642
-        $this->get_model()->field_settings_for($fieldname);
643
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
644
-
645
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
646
-    }
647
-
648
-
649
-    /**
650
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
651
-     * This also SETS the cache if we return the actual property!
652
-     *
653
-     * @param string $fieldname        the name of the property we're trying to retrieve
654
-     * @param bool   $pretty
655
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
656
-     *                                 (in cases where the same property may be used for different outputs
657
-     *                                 - i.e. datetime, money etc.)
658
-     *                                 It can also accept certain pre-defined "schema" strings
659
-     *                                 to define how to output the property.
660
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
661
-     * @return mixed                   whatever the value for the property is we're retrieving
662
-     * @throws ReflectionException
663
-     * @throws InvalidArgumentException
664
-     * @throws InvalidInterfaceException
665
-     * @throws InvalidDataTypeException
666
-     * @throws EE_Error
667
-     */
668
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
669
-    {
670
-        // verify the field exists
671
-        $model = $this->get_model();
672
-        $model->field_settings_for($fieldname);
673
-        $cache_type = $pretty ? 'pretty' : 'standard';
674
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
675
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
676
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
677
-        }
678
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
679
-        $this->_set_cached_property($fieldname, $value, $cache_type);
680
-        return $value;
681
-    }
682
-
683
-
684
-    /**
685
-     * If the cache didn't fetch the needed item, this fetches it.
686
-     *
687
-     * @param string $fieldname
688
-     * @param bool   $pretty
689
-     * @param string $extra_cache_ref
690
-     * @return mixed
691
-     * @throws InvalidArgumentException
692
-     * @throws InvalidInterfaceException
693
-     * @throws InvalidDataTypeException
694
-     * @throws EE_Error
695
-     * @throws ReflectionException
696
-     */
697
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
698
-    {
699
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
700
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
701
-        if ($field_obj instanceof EE_Datetime_Field) {
702
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
703
-        }
704
-        if (! isset($this->_fields[ $fieldname ])) {
705
-            $this->_fields[ $fieldname ] = null;
706
-        }
707
-        return $pretty
708
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
709
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
710
-    }
711
-
712
-
713
-    /**
714
-     * set timezone, formats, and output for EE_Datetime_Field objects
715
-     *
716
-     * @param EE_Datetime_Field $datetime_field
717
-     * @param bool              $pretty
718
-     * @param null              $date_or_time
719
-     * @return void
720
-     * @throws InvalidArgumentException
721
-     * @throws InvalidInterfaceException
722
-     * @throws InvalidDataTypeException
723
-     */
724
-    protected function _prepare_datetime_field(
725
-        EE_Datetime_Field $datetime_field,
726
-        $pretty = false,
727
-        $date_or_time = null
728
-    ) {
729
-        $datetime_field->set_timezone($this->_timezone);
730
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
731
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
732
-        // set the output returned
733
-        switch ($date_or_time) {
734
-            case 'D':
735
-                $datetime_field->set_date_time_output('date');
736
-                break;
737
-            case 'T':
738
-                $datetime_field->set_date_time_output('time');
739
-                break;
740
-            default:
741
-                $datetime_field->set_date_time_output();
742
-        }
743
-    }
744
-
745
-
746
-    /**
747
-     * This just takes care of clearing out the cached_properties
748
-     *
749
-     * @return void
750
-     */
751
-    protected function _clear_cached_properties()
752
-    {
753
-        $this->_cached_properties = [];
754
-    }
755
-
756
-
757
-    /**
758
-     * This just clears out ONE property if it exists in the cache
759
-     *
760
-     * @param string $property_name the property to remove if it exists (from the _cached_properties array)
761
-     * @return void
762
-     */
763
-    protected function _clear_cached_property($property_name)
764
-    {
765
-        if (isset($this->_cached_properties[ $property_name ])) {
766
-            unset($this->_cached_properties[ $property_name ]);
767
-        }
768
-    }
769
-
770
-
771
-    /**
772
-     * Ensures that this related thing is a model object.
773
-     *
774
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
775
-     * @param string $model_name   name of the related thing, eg 'Attendee',
776
-     * @return EE_Base_Class
777
-     * @throws ReflectionException
778
-     * @throws InvalidArgumentException
779
-     * @throws InvalidInterfaceException
780
-     * @throws InvalidDataTypeException
781
-     * @throws EE_Error
782
-     */
783
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
784
-    {
785
-        $other_model_instance = self::_get_model_instance_with_name(
786
-            self::_get_model_classname($model_name),
787
-            $this->_timezone
788
-        );
789
-        return $other_model_instance->ensure_is_obj($object_or_id);
790
-    }
791
-
792
-
793
-    /**
794
-     * Forgets the cached model of the given relation Name. So the next time we request it,
795
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
796
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
797
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
798
-     *
799
-     * @param string $relation_name                        one of the keys in the _model_relations array on the model.
800
-     *                                                     Eg 'Registration'
801
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
802
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
803
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
804
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
805
-     *                                                     this is HasMany or HABTM.
806
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
807
-     *                                                     relation from all
808
-     * @throws InvalidArgumentException
809
-     * @throws InvalidInterfaceException
810
-     * @throws InvalidDataTypeException
811
-     * @throws EE_Error
812
-     * @throws ReflectionException
813
-     */
814
-    public function clear_cache($relation_name, $object_to_remove_or_index_into_array = null, $clear_all = false)
815
-    {
816
-        $relationship_to_model = $this->get_model()->related_settings_for($relation_name);
817
-        $index_in_cache        = '';
818
-        if (! $relationship_to_model) {
819
-            throw new EE_Error(
820
-                sprintf(
821
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
822
-                    $relation_name,
823
-                    get_class($this)
824
-                )
825
-            );
826
-        }
827
-        if ($clear_all) {
828
-            $obj_removed                              = true;
829
-            $this->_model_relations[ $relation_name ] = null;
830
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
831
-            $obj_removed                              = $this->_model_relations[ $relation_name ];
832
-            $this->_model_relations[ $relation_name ] = null;
833
-        } else {
834
-            if (
835
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
836
-                && $object_to_remove_or_index_into_array->ID()
837
-            ) {
838
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
839
-                if (
840
-                    is_array($this->_model_relations[ $relation_name ])
841
-                    && ! isset($this->_model_relations[ $relation_name ][ $index_in_cache ])
842
-                ) {
843
-                    $index_found_at = null;
844
-                    // find this object in the array even though it has a different key
845
-                    foreach ($this->_model_relations[ $relation_name ] as $index => $obj) {
846
-                        /** @noinspection TypeUnsafeComparisonInspection */
847
-                        if (
848
-                            $obj instanceof EE_Base_Class
849
-                            && (
850
-                                $obj == $object_to_remove_or_index_into_array
851
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
852
-                            )
853
-                        ) {
854
-                            $index_found_at = $index;
855
-                            break;
856
-                        }
857
-                    }
858
-                    if ($index_found_at) {
859
-                        $index_in_cache = $index_found_at;
860
-                    } else {
861
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
862
-                        // if it wasn't in it to begin with. So we're done
863
-                        return $object_to_remove_or_index_into_array;
864
-                    }
865
-                }
866
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
867
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
868
-                foreach ($this->get_all_from_cache($relation_name) as $index => $potentially_obj_we_want) {
869
-                    /** @noinspection TypeUnsafeComparisonInspection */
870
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
871
-                        $index_in_cache = $index;
872
-                    }
873
-                }
874
-            } else {
875
-                $index_in_cache = $object_to_remove_or_index_into_array;
876
-            }
877
-            // supposedly we've found it. But it could just be that the client code
878
-            // provided a bad index/object
879
-            if (isset($this->_model_relations[ $relation_name ][ $index_in_cache ])) {
880
-                $obj_removed = $this->_model_relations[ $relation_name ][ $index_in_cache ];
881
-                unset($this->_model_relations[ $relation_name ][ $index_in_cache ]);
882
-            } else {
883
-                // that thing was never cached anyways.
884
-                $obj_removed = null;
885
-            }
886
-        }
887
-        return $obj_removed;
888
-    }
889
-
890
-
891
-    /**
892
-     * update_cache_after_object_save
893
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
894
-     * obtained after being saved to the db
895
-     *
896
-     * @param string        $relation_name      - the type of object that is cached
897
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
898
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
899
-     * @return boolean TRUE on success, FALSE on fail
900
-     * @throws ReflectionException
901
-     * @throws InvalidArgumentException
902
-     * @throws InvalidInterfaceException
903
-     * @throws InvalidDataTypeException
904
-     * @throws EE_Error
905
-     */
906
-    public function update_cache_after_object_save(
907
-        $relation_name,
908
-        EE_Base_Class $newly_saved_object,
909
-        $current_cache_id = ''
910
-    ) {
911
-        // verify that incoming object is of the correct type
912
-        $obj_class = 'EE_' . $relation_name;
913
-        if ($newly_saved_object instanceof $obj_class) {
914
-            /* @type EE_Base_Class $newly_saved_object */
915
-            // now get the type of relation
916
-            $relationship_to_model = $this->get_model()->related_settings_for($relation_name);
917
-            // if this is a 1:1 relationship
918
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
919
-                // then just replace the cached object with the newly saved object
920
-                $this->_model_relations[ $relation_name ] = $newly_saved_object;
921
-                return true;
922
-                // or if it's some kind of sordid feral polyamorous relationship...
923
-            }
924
-            if (
925
-                is_array($this->_model_relations[ $relation_name ])
926
-                && isset($this->_model_relations[ $relation_name ][ $current_cache_id ])
927
-            ) {
928
-                // then remove the current cached item
929
-                unset($this->_model_relations[ $relation_name ][ $current_cache_id ]);
930
-                // and cache the newly saved object using it's new ID
931
-                $this->_model_relations[ $relation_name ][ $newly_saved_object->ID() ] = $newly_saved_object;
932
-                return true;
933
-            }
934
-        }
935
-        return false;
936
-    }
937
-
938
-
939
-    /**
940
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
941
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
942
-     *
943
-     * @param string $relation_name
944
-     * @return EE_Base_Class
945
-     */
946
-    public function get_one_from_cache($relation_name)
947
-    {
948
-        $cached_array_or_object = $this->_model_relations[ $relation_name ] ?? null;
949
-        if (is_array($cached_array_or_object)) {
950
-            return array_shift($cached_array_or_object);
951
-        }
952
-        return $cached_array_or_object;
953
-    }
954
-
955
-
956
-    /**
957
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
958
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
959
-     *
960
-     * @param string $relation_name
961
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
962
-     * @throws InvalidArgumentException
963
-     * @throws InvalidInterfaceException
964
-     * @throws InvalidDataTypeException
965
-     * @throws EE_Error
966
-     * @throws ReflectionException
967
-     */
968
-    public function get_all_from_cache($relation_name)
969
-    {
970
-        $objects = $this->_model_relations[ $relation_name ] ?? [];
971
-        // if the result is not an array, but exists, make it an array
972
-        $objects = is_array($objects)
973
-            ? $objects
974
-            : [$objects];
975
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
976
-        // basically, if this model object was stored in the session, and these cached model objects
977
-        // already have IDs, let's make sure they're in their model's entity mapper
978
-        // otherwise we will have duplicates next time we call
979
-        // EE_Registry::instance()->load_model( $relation_name )->get_one_by_ID( $result->ID() );
980
-        $model = EE_Registry::instance()->load_model($relation_name);
981
-        foreach ($objects as $model_object) {
982
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
983
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
984
-                if ($model_object->ID()) {
985
-                    $model->add_to_entity_map($model_object);
986
-                }
987
-            } else {
988
-                throw new EE_Error(
989
-                    sprintf(
990
-                        esc_html__(
991
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
992
-                            'event_espresso'
993
-                        ),
994
-                        $relation_name,
995
-                        gettype($model_object)
996
-                    )
997
-                );
998
-            }
999
-        }
1000
-        return $objects;
1001
-    }
1002
-
1003
-
1004
-    /**
1005
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1006
-     * matching the given query conditions.
1007
-     *
1008
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1009
-     * @param int   $limit              How many objects to return.
1010
-     * @param array $query_params       Any additional conditions on the query.
1011
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1012
-     *                                  you can indicate just the columns you want returned
1013
-     * @return array|EE_Base_Class[]
1014
-     * @throws ReflectionException
1015
-     * @throws InvalidArgumentException
1016
-     * @throws InvalidInterfaceException
1017
-     * @throws InvalidDataTypeException
1018
-     * @throws EE_Error
1019
-     */
1020
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = [], $columns_to_select = null)
1021
-    {
1022
-        $model         = $this->get_model();
1023
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1024
-            ? $model->get_primary_key_field()->get_name()
1025
-            : $field_to_order_by;
1026
-        $current_value = ! empty($field)
1027
-            ? $this->get($field)
1028
-            : null;
1029
-        if (empty($field) || empty($current_value)) {
1030
-            return [];
1031
-        }
1032
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1033
-    }
1034
-
1035
-
1036
-    /**
1037
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1038
-     * matching the given query conditions.
1039
-     *
1040
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1041
-     * @param int   $limit              How many objects to return.
1042
-     * @param array $query_params       Any additional conditions on the query.
1043
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1044
-     *                                  you can indicate just the columns you want returned
1045
-     * @return array|EE_Base_Class[]
1046
-     * @throws ReflectionException
1047
-     * @throws InvalidArgumentException
1048
-     * @throws InvalidInterfaceException
1049
-     * @throws InvalidDataTypeException
1050
-     * @throws EE_Error
1051
-     */
1052
-    public function previous_x(
1053
-        $field_to_order_by = null,
1054
-        $limit = 1,
1055
-        $query_params = [],
1056
-        $columns_to_select = null
1057
-    ) {
1058
-        $model         = $this->get_model();
1059
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1060
-            ? $model->get_primary_key_field()->get_name()
1061
-            : $field_to_order_by;
1062
-        $current_value = ! empty($field) ? $this->get($field) : null;
1063
-        if (empty($field) || empty($current_value)) {
1064
-            return [];
1065
-        }
1066
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1067
-    }
1068
-
1069
-
1070
-    /**
1071
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1072
-     * matching the given query conditions.
1073
-     *
1074
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1075
-     * @param array $query_params       Any additional conditions on the query.
1076
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1077
-     *                                  you can indicate just the columns you want returned
1078
-     * @return array|EE_Base_Class
1079
-     * @throws ReflectionException
1080
-     * @throws InvalidArgumentException
1081
-     * @throws InvalidInterfaceException
1082
-     * @throws InvalidDataTypeException
1083
-     * @throws EE_Error
1084
-     */
1085
-    public function next($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1086
-    {
1087
-        $model         = $this->get_model();
1088
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1089
-            ? $model->get_primary_key_field()->get_name()
1090
-            : $field_to_order_by;
1091
-        $current_value = ! empty($field) ? $this->get($field) : null;
1092
-        if (empty($field) || empty($current_value)) {
1093
-            return [];
1094
-        }
1095
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1096
-    }
1097
-
1098
-
1099
-    /**
1100
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1101
-     * matching the given query conditions.
1102
-     *
1103
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1104
-     * @param array $query_params       Any additional conditions on the query.
1105
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1106
-     *                                  you can indicate just the column you want returned
1107
-     * @return array|EE_Base_Class
1108
-     * @throws ReflectionException
1109
-     * @throws InvalidArgumentException
1110
-     * @throws InvalidInterfaceException
1111
-     * @throws InvalidDataTypeException
1112
-     * @throws EE_Error
1113
-     */
1114
-    public function previous($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1115
-    {
1116
-        $model         = $this->get_model();
1117
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1118
-            ? $model->get_primary_key_field()->get_name()
1119
-            : $field_to_order_by;
1120
-        $current_value = ! empty($field) ? $this->get($field) : null;
1121
-        if (empty($field) || empty($current_value)) {
1122
-            return [];
1123
-        }
1124
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * verifies that the specified field is of the correct type
1130
-     *
1131
-     * @param string $field_name
1132
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1133
-     *                                (in cases where the same property may be used for different outputs
1134
-     *                                - i.e. datetime, money etc.)
1135
-     * @return mixed
1136
-     * @throws ReflectionException
1137
-     * @throws InvalidArgumentException
1138
-     * @throws InvalidInterfaceException
1139
-     * @throws InvalidDataTypeException
1140
-     * @throws EE_Error
1141
-     */
1142
-    public function get($field_name, $extra_cache_ref = null)
1143
-    {
1144
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1145
-    }
1146
-
1147
-
1148
-    /**
1149
-     * This method simply returns the RAW unprocessed value for the given property in this class
1150
-     *
1151
-     * @param string $field_name A valid fieldname
1152
-     * @return mixed              Whatever the raw value stored on the property is.
1153
-     * @throws ReflectionException
1154
-     * @throws InvalidArgumentException
1155
-     * @throws InvalidInterfaceException
1156
-     * @throws InvalidDataTypeException
1157
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1158
-     */
1159
-    public function get_raw($field_name)
1160
-    {
1161
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1162
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1163
-            ? $this->_fields[ $field_name ]->format('U')
1164
-            : $this->_fields[ $field_name ];
1165
-    }
1166
-
1167
-
1168
-    /**
1169
-     * This is used to return the internal DateTime object used for a field that is a
1170
-     * EE_Datetime_Field.
1171
-     *
1172
-     * @param string $field_name               The field name retrieving the DateTime object.
1173
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1174
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1175
-     *                                         EE_Datetime_Field and but the field value is null, then
1176
-     *                                         just null is returned (because that indicates that likely
1177
-     *                                         this field is nullable).
1178
-     * @throws InvalidArgumentException
1179
-     * @throws InvalidDataTypeException
1180
-     * @throws InvalidInterfaceException
1181
-     * @throws ReflectionException
1182
-     */
1183
-    public function get_DateTime_object($field_name)
1184
-    {
1185
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1186
-        if (! $field_settings instanceof EE_Datetime_Field) {
1187
-            EE_Error::add_error(
1188
-                sprintf(
1189
-                    esc_html__(
1190
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1191
-                        'event_espresso'
1192
-                    ),
1193
-                    $field_name
1194
-                ),
1195
-                __FILE__,
1196
-                __FUNCTION__,
1197
-                __LINE__
1198
-            );
1199
-            return false;
1200
-        }
1201
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1202
-            ? clone $this->_fields[ $field_name ]
1203
-            : null;
1204
-    }
1205
-
1206
-
1207
-    /**
1208
-     * To be used in template to immediately echo out the value, and format it for output.
1209
-     * Eg, should call stripslashes and whatnot before echoing
1210
-     *
1211
-     * @param string $field_name      the name of the field as it appears in the DB
1212
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1213
-     *                                (in cases where the same property may be used for different outputs
1214
-     *                                - i.e. datetime, money etc.)
1215
-     * @return void
1216
-     * @throws ReflectionException
1217
-     * @throws InvalidArgumentException
1218
-     * @throws InvalidInterfaceException
1219
-     * @throws InvalidDataTypeException
1220
-     * @throws EE_Error
1221
-     */
1222
-    public function e($field_name, $extra_cache_ref = null)
1223
-    {
1224
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1225
-    }
1226
-
1227
-
1228
-    /**
1229
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1230
-     * can be easily used as the value of form input.
1231
-     *
1232
-     * @param string $field_name
1233
-     * @return void
1234
-     * @throws ReflectionException
1235
-     * @throws InvalidArgumentException
1236
-     * @throws InvalidInterfaceException
1237
-     * @throws InvalidDataTypeException
1238
-     * @throws EE_Error
1239
-     */
1240
-    public function f($field_name)
1241
-    {
1242
-        $this->e($field_name, 'form_input');
1243
-    }
1244
-
1245
-
1246
-    /**
1247
-     * Same as `f()` but just returns the value instead of echoing it
1248
-     *
1249
-     * @param string $field_name
1250
-     * @return string
1251
-     * @throws ReflectionException
1252
-     * @throws InvalidArgumentException
1253
-     * @throws InvalidInterfaceException
1254
-     * @throws InvalidDataTypeException
1255
-     * @throws EE_Error
1256
-     */
1257
-    public function get_f($field_name)
1258
-    {
1259
-        return (string) $this->get_pretty($field_name, 'form_input');
1260
-    }
1261
-
1262
-
1263
-    /**
1264
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1265
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1266
-     * to see what options are available.
1267
-     *
1268
-     * @param string $field_name
1269
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1270
-     *                                (in cases where the same property may be used for different outputs
1271
-     *                                - i.e. datetime, money etc.)
1272
-     * @return mixed
1273
-     * @throws ReflectionException
1274
-     * @throws InvalidArgumentException
1275
-     * @throws InvalidInterfaceException
1276
-     * @throws InvalidDataTypeException
1277
-     * @throws EE_Error
1278
-     */
1279
-    public function get_pretty($field_name, $extra_cache_ref = null)
1280
-    {
1281
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1282
-    }
1283
-
1284
-
1285
-    /**
1286
-     * This simply returns the datetime for the given field name
1287
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1288
-     * (and the equivalent e_date, e_time, e_datetime).
1289
-     *
1290
-     * @access   protected
1291
-     * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1292
-     * @param string|null $date_format  valid datetime format used for date
1293
-     *                                  (if '' then we just use the default on the field,
1294
-     *                                  if NULL we use the last-used format)
1295
-     * @param string|null $time_format  Same as above except this is for time format
1296
-     * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1297
-     * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1298
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1299
-     *                                  if field is not a valid dtt field, or void if echoing
1300
-     * @throws EE_Error
1301
-     * @throws ReflectionException
1302
-     */
1303
-    protected function _get_datetime(
1304
-        string $field_name,
1305
-        ?string $date_format = '',
1306
-        ?string $time_format = '',
1307
-        ?string $date_or_time = '',
1308
-        ?bool $echo = false
1309
-    ) {
1310
-        // clear cached property
1311
-        $this->_clear_cached_property($field_name);
1312
-        // reset format properties because they are used in get()
1313
-        $this->_dt_frmt = $date_format ?: $this->_dt_frmt;
1314
-        $this->_tm_frmt = $time_format ?: $this->_tm_frmt;
1315
-        if ($echo) {
1316
-            $this->e($field_name, $date_or_time);
1317
-            return '';
1318
-        }
1319
-        return $this->get($field_name, $date_or_time);
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1325
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1326
-     * other echoes the pretty value for dtt)
1327
-     *
1328
-     * @param string $field_name name of model object datetime field holding the value
1329
-     * @param string $format     format for the date returned (if NULL we use default in dt_frmt property)
1330
-     * @return string            datetime value formatted
1331
-     * @throws ReflectionException
1332
-     * @throws InvalidArgumentException
1333
-     * @throws InvalidInterfaceException
1334
-     * @throws InvalidDataTypeException
1335
-     * @throws EE_Error
1336
-     */
1337
-    public function get_date($field_name, $format = '')
1338
-    {
1339
-        return $this->_get_datetime($field_name, $format, null, 'D');
1340
-    }
1341
-
1342
-
1343
-    /**
1344
-     * @param        $field_name
1345
-     * @param string $format
1346
-     * @throws ReflectionException
1347
-     * @throws InvalidArgumentException
1348
-     * @throws InvalidInterfaceException
1349
-     * @throws InvalidDataTypeException
1350
-     * @throws EE_Error
1351
-     */
1352
-    public function e_date($field_name, $format = '')
1353
-    {
1354
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1355
-    }
1356
-
1357
-
1358
-    /**
1359
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1360
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1361
-     * other echoes the pretty value for dtt)
1362
-     *
1363
-     * @param string $field_name name of model object datetime field holding the value
1364
-     * @param string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1365
-     * @return string             datetime value formatted
1366
-     * @throws ReflectionException
1367
-     * @throws InvalidArgumentException
1368
-     * @throws InvalidInterfaceException
1369
-     * @throws InvalidDataTypeException
1370
-     * @throws EE_Error
1371
-     */
1372
-    public function get_time($field_name, $format = '')
1373
-    {
1374
-        return $this->_get_datetime($field_name, null, $format, 'T');
1375
-    }
1376
-
1377
-
1378
-    /**
1379
-     * @param        $field_name
1380
-     * @param string $format
1381
-     * @throws ReflectionException
1382
-     * @throws InvalidArgumentException
1383
-     * @throws InvalidInterfaceException
1384
-     * @throws InvalidDataTypeException
1385
-     * @throws EE_Error
1386
-     */
1387
-    public function e_time($field_name, $format = '')
1388
-    {
1389
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1390
-    }
1391
-
1392
-
1393
-    /**
1394
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1395
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1396
-     * other echoes the pretty value for dtt)
1397
-     *
1398
-     * @param string $field_name  name of model object datetime field holding the value
1399
-     * @param string $date_format format for the date returned (if NULL we use default in dt_frmt property)
1400
-     * @param string $time_format format for the time returned (if NULL we use default in tm_frmt property)
1401
-     * @return string             datetime value formatted
1402
-     * @throws ReflectionException
1403
-     * @throws InvalidArgumentException
1404
-     * @throws InvalidInterfaceException
1405
-     * @throws InvalidDataTypeException
1406
-     * @throws EE_Error
1407
-     */
1408
-    public function get_datetime($field_name, $date_format = '', $time_format = '')
1409
-    {
1410
-        return $this->_get_datetime($field_name, $date_format, $time_format);
1411
-    }
1412
-
1413
-
1414
-    /**
1415
-     * @param string $field_name
1416
-     * @param string $date_format
1417
-     * @param string $time_format
1418
-     * @throws ReflectionException
1419
-     * @throws InvalidArgumentException
1420
-     * @throws InvalidInterfaceException
1421
-     * @throws InvalidDataTypeException
1422
-     * @throws EE_Error
1423
-     */
1424
-    public function e_datetime($field_name, $date_format = '', $time_format = '')
1425
-    {
1426
-        $this->_get_datetime($field_name, $date_format, $time_format, null, true);
1427
-    }
1428
-
1429
-
1430
-    /**
1431
-     * Get the i8ln value for a date using the WordPress @param string $field_name The EE_Datetime_Field reference for
1432
-     *                           the date being retrieved.
1433
-     *
1434
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1435
-     *                           on the object will be used.
1436
-     * @return string Date and time string in set locale or false if no field exists for the given
1437
-     * @throws ReflectionException
1438
-     * @throws InvalidArgumentException
1439
-     * @throws InvalidInterfaceException
1440
-     * @throws InvalidDataTypeException
1441
-     * @throws EE_Error
1442
-     *                           field name.
1443
-     * @see date_i18n function.
1444
-     */
1445
-    public function get_i18n_datetime(string $field_name, string $format = ''): string
1446
-    {
1447
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1448
-        return date_i18n(
1449
-            $format,
1450
-            EEH_DTT_Helper::get_timestamp_with_offset(
1451
-                $this->get_raw($field_name),
1452
-                $this->_timezone
1453
-            )
1454
-        );
1455
-    }
1456
-
1457
-
1458
-    /**
1459
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1460
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1461
-     * thrown.
1462
-     *
1463
-     * @param string $field_name The field name being checked
1464
-     * @return EE_Datetime_Field
1465
-     * @throws InvalidArgumentException
1466
-     * @throws InvalidInterfaceException
1467
-     * @throws InvalidDataTypeException
1468
-     * @throws EE_Error
1469
-     * @throws ReflectionException
1470
-     */
1471
-    protected function _get_dtt_field_settings($field_name)
1472
-    {
1473
-        $field = $this->get_model()->field_settings_for($field_name);
1474
-        // check if field is dtt
1475
-        if ($field instanceof EE_Datetime_Field) {
1476
-            return $field;
1477
-        }
1478
-        throw new EE_Error(
1479
-            sprintf(
1480
-                esc_html__(
1481
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1482
-                    'event_espresso'
1483
-                ),
1484
-                $field_name,
1485
-                self::_get_model_classname(get_class($this))
1486
-            )
1487
-        );
1488
-    }
1489
-
1490
-
1491
-
1492
-
1493
-    /**
1494
-     * NOTE ABOUT BELOW:
1495
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1496
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1497
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1498
-     * method and make sure you send the entire datetime value for setting.
1499
-     */
1500
-    /**
1501
-     * sets the time on a datetime property
1502
-     *
1503
-     * @access protected
1504
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1505
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1506
-     * @throws ReflectionException
1507
-     * @throws InvalidArgumentException
1508
-     * @throws InvalidInterfaceException
1509
-     * @throws InvalidDataTypeException
1510
-     * @throws EE_Error
1511
-     */
1512
-    protected function _set_time_for($time, $fieldname)
1513
-    {
1514
-        $this->_set_date_time('T', $time, $fieldname);
1515
-    }
1516
-
1517
-
1518
-    /**
1519
-     * sets the date on a datetime property
1520
-     *
1521
-     * @access protected
1522
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1523
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1524
-     * @throws ReflectionException
1525
-     * @throws InvalidArgumentException
1526
-     * @throws InvalidInterfaceException
1527
-     * @throws InvalidDataTypeException
1528
-     * @throws EE_Error
1529
-     */
1530
-    protected function _set_date_for($date, $fieldname)
1531
-    {
1532
-        $this->_set_date_time('D', $date, $fieldname);
1533
-    }
1534
-
1535
-
1536
-    /**
1537
-     * This takes care of setting a date or time independently on a given model object property. This method also
1538
-     * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1539
-     *
1540
-     * @access protected
1541
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1542
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1543
-     * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1544
-     *                                        EE_Datetime_Field property)
1545
-     * @throws ReflectionException
1546
-     * @throws InvalidArgumentException
1547
-     * @throws InvalidInterfaceException
1548
-     * @throws InvalidDataTypeException
1549
-     * @throws EE_Error
1550
-     */
1551
-    protected function _set_date_time(string $what, $datetime_value, string $field_name)
1552
-    {
1553
-        $field = $this->_get_dtt_field_settings($field_name);
1554
-        $field->set_timezone($this->_timezone);
1555
-        $field->set_date_format($this->_dt_frmt);
1556
-        $field->set_time_format($this->_tm_frmt);
1557
-        switch ($what) {
1558
-            case 'T':
1559
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1560
-                    $datetime_value,
1561
-                    $this->_fields[ $field_name ]
1562
-                );
1563
-                $this->_has_changes           = true;
1564
-                break;
1565
-            case 'D':
1566
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1567
-                    $datetime_value,
1568
-                    $this->_fields[ $field_name ]
1569
-                );
1570
-                $this->_has_changes           = true;
1571
-                break;
1572
-            case 'B':
1573
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1574
-                $this->_has_changes           = true;
1575
-                break;
1576
-        }
1577
-        $this->_clear_cached_property($field_name);
1578
-    }
1579
-
1580
-
1581
-    /**
1582
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1583
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1584
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1585
-     * that could lead to some unexpected results!
1586
-     *
1587
-     * @access public
1588
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1589
-     *                                         value being returned.
1590
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1591
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1592
-     * @param string $prepend                  You can include something to prepend on the timestamp
1593
-     * @param string $append                   You can include something to append on the timestamp
1594
-     * @return string timestamp
1595
-     * @throws ReflectionException
1596
-     * @throws InvalidArgumentException
1597
-     * @throws InvalidInterfaceException
1598
-     * @throws InvalidDataTypeException
1599
-     * @throws EE_Error
1600
-     */
1601
-    public function display_in_my_timezone(
1602
-        $field_name,
1603
-        $callback = 'get_datetime',
1604
-        $args = null,
1605
-        $prepend = '',
1606
-        $append = ''
1607
-    ) {
1608
-        $timezone = EEH_DTT_Helper::get_timezone();
1609
-        if ($timezone === $this->_timezone) {
1610
-            return '';
1611
-        }
1612
-        $original_timezone = $this->_timezone;
1613
-        $this->set_timezone($timezone);
1614
-        $fn   = (array) $field_name;
1615
-        $args = array_merge($fn, (array) $args);
1616
-        if (! method_exists($this, $callback)) {
1617
-            throw new EE_Error(
1618
-                sprintf(
1619
-                    esc_html__(
1620
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1621
-                        'event_espresso'
1622
-                    ),
1623
-                    $callback
1624
-                )
1625
-            );
1626
-        }
1627
-        $args   = (array) $args;
1628
-        $return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
1629
-        $this->set_timezone($original_timezone);
1630
-        return $return;
1631
-    }
1632
-
1633
-
1634
-    /**
1635
-     * Deletes this model object.
1636
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1637
-     * override
1638
-     * `EE_Base_Class::_delete` NOT this class.
1639
-     *
1640
-     * @return boolean | int
1641
-     * @throws ReflectionException
1642
-     * @throws InvalidArgumentException
1643
-     * @throws InvalidInterfaceException
1644
-     * @throws InvalidDataTypeException
1645
-     * @throws EE_Error
1646
-     */
1647
-    public function delete()
1648
-    {
1649
-        /**
1650
-         * Called just before the `EE_Base_Class::_delete` method call.
1651
-         * Note:
1652
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1653
-         * should be aware that `_delete` may not always result in a permanent delete.
1654
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1655
-         * soft deletes (trash) the object and does not permanently delete it.
1656
-         *
1657
-         * @param EE_Base_Class $model_object about to be 'deleted'
1658
-         */
1659
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1660
-        $result = $this->_delete();
1661
-        /**
1662
-         * Called just after the `EE_Base_Class::_delete` method call.
1663
-         * Note:
1664
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1665
-         * should be aware that `_delete` may not always result in a permanent delete.
1666
-         * For example `EE_Soft_Base_Class::_delete`
1667
-         * soft deletes (trash) the object and does not permanently delete it.
1668
-         *
1669
-         * @param EE_Base_Class $model_object that was just 'deleted'
1670
-         * @param boolean       $result
1671
-         */
1672
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1673
-        return $result;
1674
-    }
1675
-
1676
-
1677
-    /**
1678
-     * Calls the specific delete method for the instantiated class.
1679
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1680
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1681
-     * `EE_Base_Class::delete`
1682
-     *
1683
-     * @return bool|int
1684
-     * @throws ReflectionException
1685
-     * @throws InvalidArgumentException
1686
-     * @throws InvalidInterfaceException
1687
-     * @throws InvalidDataTypeException
1688
-     * @throws EE_Error
1689
-     */
1690
-    protected function _delete()
1691
-    {
1692
-        return $this->delete_permanently();
1693
-    }
1694
-
1695
-
1696
-    /**
1697
-     * Deletes this model object permanently from db
1698
-     * (but keep in mind related models may block the delete and return an error)
1699
-     *
1700
-     * @return bool | int
1701
-     * @throws ReflectionException
1702
-     * @throws InvalidArgumentException
1703
-     * @throws InvalidInterfaceException
1704
-     * @throws InvalidDataTypeException
1705
-     * @throws EE_Error
1706
-     */
1707
-    public function delete_permanently()
1708
-    {
1709
-        /**
1710
-         * Called just before HARD deleting a model object
1711
-         *
1712
-         * @param EE_Base_Class $model_object about to be 'deleted'
1713
-         */
1714
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1715
-        $model  = $this->get_model();
1716
-        $result = $model->delete_permanently_by_ID($this->ID());
1717
-        $this->refresh_cache_of_related_objects();
1718
-        /**
1719
-         * Called just after HARD deleting a model object
1720
-         *
1721
-         * @param EE_Base_Class $model_object that was just 'deleted'
1722
-         * @param boolean       $result
1723
-         */
1724
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1725
-        return $result;
1726
-    }
1727
-
1728
-
1729
-    /**
1730
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1731
-     * related model objects
1732
-     *
1733
-     * @throws ReflectionException
1734
-     * @throws InvalidArgumentException
1735
-     * @throws InvalidInterfaceException
1736
-     * @throws InvalidDataTypeException
1737
-     * @throws EE_Error
1738
-     */
1739
-    public function refresh_cache_of_related_objects()
1740
-    {
1741
-        $model = $this->get_model();
1742
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1743
-            if (! empty($this->_model_relations[ $relation_name ])) {
1744
-                $related_objects = $this->_model_relations[ $relation_name ];
1745
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1746
-                    // this relation only stores a single model object, not an array
1747
-                    // but let's make it consistent
1748
-                    $related_objects = [$related_objects];
1749
-                }
1750
-                foreach ($related_objects as $related_object) {
1751
-                    // only refresh their cache if they're in memory
1752
-                    if ($related_object instanceof EE_Base_Class) {
1753
-                        $related_object->clear_cache(
1754
-                            $model->get_this_model_name(),
1755
-                            $this
1756
-                        );
1757
-                    }
1758
-                }
1759
-            }
1760
-        }
1761
-    }
1762
-
1763
-
1764
-    /**
1765
-     *        Saves this object to the database. An array may be supplied to set some values on this
1766
-     * object just before saving.
1767
-     *
1768
-     * @access public
1769
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1770
-     *                                 if provided during the save() method (often client code will change the fields'
1771
-     *                                 values before calling save)
1772
-     * @return bool|int|string         1 on a successful update
1773
-     *                                 the ID of the new entry on insert
1774
-     *                                 0 on failure or if the model object isn't allowed to persist
1775
-     *                                 (as determined by EE_Base_Class::allow_persist())
1776
-     * @throws InvalidInterfaceException
1777
-     * @throws InvalidDataTypeException
1778
-     * @throws EE_Error
1779
-     * @throws InvalidArgumentException
1780
-     * @throws ReflectionException
1781
-     */
1782
-    public function save($set_cols_n_values = [])
1783
-    {
1784
-        $model = $this->get_model();
1785
-        /**
1786
-         * Filters the fields we're about to save on the model object
1787
-         *
1788
-         * @param array         $set_cols_n_values
1789
-         * @param EE_Base_Class $model_object
1790
-         */
1791
-        $set_cols_n_values = (array) apply_filters(
1792
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1793
-            $set_cols_n_values,
1794
-            $this
1795
-        );
1796
-        // set attributes as provided in $set_cols_n_values
1797
-        foreach ($set_cols_n_values as $column => $value) {
1798
-            $this->set($column, $value);
1799
-        }
1800
-        // no changes ? then don't do anything
1801
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1802
-            return 0;
1803
-        }
1804
-        /**
1805
-         * Saving a model object.
1806
-         * Before we perform a save, this action is fired.
1807
-         *
1808
-         * @param EE_Base_Class $model_object the model object about to be saved.
1809
-         */
1810
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1811
-        if (! $this->allow_persist()) {
1812
-            return 0;
1813
-        }
1814
-        // now get current attribute values
1815
-        $save_cols_n_values = $this->_fields;
1816
-        // if the object already has an ID, update it. Otherwise, insert it
1817
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1818
-        // They have been
1819
-        $old_assumption_concerning_value_preparation = $model
1820
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1821
-        $model->assume_values_already_prepared_by_model_object(true);
1822
-        // does this model have an autoincrement PK?
1823
-        if ($model->has_primary_key_field()) {
1824
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1825
-                // ok check if it's set, if so: update; if not, insert
1826
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1827
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1828
-                } else {
1829
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1830
-                    $results = $model->insert($save_cols_n_values);
1831
-                    if ($results) {
1832
-                        // if successful, set the primary key
1833
-                        // but don't use the normal SET method, because it will check if
1834
-                        // an item with the same ID exists in the mapper & db, then
1835
-                        // will find it in the db (because we just added it) and THAT object
1836
-                        // will get added to the mapper before we can add this one!
1837
-                        // but if we just avoid using the SET method, all that headache can be avoided
1838
-                        $pk_field_name                   = $model->primary_key_name();
1839
-                        $this->_fields[ $pk_field_name ] = $results;
1840
-                        $this->_clear_cached_property($pk_field_name);
1841
-                        $model->add_to_entity_map($this);
1842
-                        $this->_update_cached_related_model_objs_fks();
1843
-                    }
1844
-                }
1845
-            } else {// PK is NOT auto-increment
1846
-                // so check if one like it already exists in the db
1847
-                if ($model->exists_by_ID($this->ID())) {
1848
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1849
-                        throw new EE_Error(
1850
-                            sprintf(
1851
-                                esc_html__(
1852
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1853
-                                    'event_espresso'
1854
-                                ),
1855
-                                get_class($this),
1856
-                                get_class($model) . '::instance()->add_to_entity_map()',
1857
-                                get_class($model) . '::instance()->get_one_by_ID()',
1858
-                                '<br />'
1859
-                            )
1860
-                        );
1861
-                    }
1862
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1863
-                } else {
1864
-                    $results = $model->insert($save_cols_n_values);
1865
-                    $this->_update_cached_related_model_objs_fks();
1866
-                }
1867
-            }
1868
-        } else {// there is NO primary key
1869
-            $already_in_db = false;
1870
-            foreach ($model->unique_indexes() as $index) {
1871
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1872
-                if ($model->exists([$uniqueness_where_params])) {
1873
-                    $already_in_db = true;
1874
-                }
1875
-            }
1876
-            if ($already_in_db) {
1877
-                $combined_pk_fields_n_values = array_intersect_key(
1878
-                    $save_cols_n_values,
1879
-                    $model->get_combined_primary_key_fields()
1880
-                );
1881
-                $results                     = $model->update(
1882
-                    $save_cols_n_values,
1883
-                    $combined_pk_fields_n_values
1884
-                );
1885
-            } else {
1886
-                $results = $model->insert($save_cols_n_values);
1887
-            }
1888
-        }
1889
-        // restore the old assumption about values being prepared by the model object
1890
-        $model->assume_values_already_prepared_by_model_object(
1891
-            $old_assumption_concerning_value_preparation
1892
-        );
1893
-        /**
1894
-         * After saving the model object this action is called
1895
-         *
1896
-         * @param EE_Base_Class $model_object which was just saved
1897
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1898
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1899
-         */
1900
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1901
-        $this->_has_changes = false;
1902
-        return $results;
1903
-    }
1904
-
1905
-
1906
-    /**
1907
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1908
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1909
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1910
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1911
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1912
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1913
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1914
-     *
1915
-     * @return void
1916
-     * @throws ReflectionException
1917
-     * @throws InvalidArgumentException
1918
-     * @throws InvalidInterfaceException
1919
-     * @throws InvalidDataTypeException
1920
-     * @throws EE_Error
1921
-     */
1922
-    protected function _update_cached_related_model_objs_fks()
1923
-    {
1924
-        $model = $this->get_model();
1925
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1926
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1927
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1928
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1929
-                        $model->get_this_model_name()
1930
-                    );
1931
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1932
-                    if ($related_model_obj_in_cache->ID()) {
1933
-                        $related_model_obj_in_cache->save();
1934
-                    }
1935
-                }
1936
-            }
1937
-        }
1938
-    }
1939
-
1940
-
1941
-    /**
1942
-     * Saves this model object and its NEW cached relations to the database.
1943
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1944
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1945
-     * because otherwise, there's a potential for infinite looping of saving
1946
-     * Saves the cached related model objects, and ensures the relation between them
1947
-     * and this object and properly setup
1948
-     *
1949
-     * @return int ID of new model object on save; 0 on failure+
1950
-     * @throws ReflectionException
1951
-     * @throws InvalidArgumentException
1952
-     * @throws InvalidInterfaceException
1953
-     * @throws InvalidDataTypeException
1954
-     * @throws EE_Error
1955
-     */
1956
-    public function save_new_cached_related_model_objs()
1957
-    {
1958
-        // make sure this has been saved
1959
-        if (! $this->ID()) {
1960
-            $id = $this->save();
1961
-        } else {
1962
-            $id = $this->ID();
1963
-        }
1964
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1965
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relationObj) {
1966
-            if ($this->_model_relations[ $relation_name ]) {
1967
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1968
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1969
-                /* @var $related_model_obj EE_Base_Class */
1970
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1971
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
1972
-                    // but ONLY if it DOES NOT exist in the DB
1973
-                    $related_model_obj = $this->_model_relations[ $relation_name ];
1974
-                    // if( ! $related_model_obj->ID()){
1975
-                    $this->_add_relation_to($related_model_obj, $relation_name);
1976
-                    $related_model_obj->save_new_cached_related_model_objs();
1977
-                    // }
1978
-                } else {
1979
-                    foreach ($this->_model_relations[ $relation_name ] as $related_model_obj) {
1980
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
1981
-                        // but ONLY if it DOES NOT exist in the DB
1982
-                        // if( ! $related_model_obj->ID()){
1983
-                        $this->_add_relation_to($related_model_obj, $relation_name);
1984
-                        $related_model_obj->save_new_cached_related_model_objs();
1985
-                        // }
1986
-                    }
1987
-                }
1988
-            }
1989
-        }
1990
-        return $id;
1991
-    }
1992
-
1993
-
1994
-    /**
1995
-     * for getting a model while instantiated.
1996
-     *
1997
-     * @return EEM_Base | EEM_CPT_Base
1998
-     * @throws ReflectionException
1999
-     * @throws InvalidArgumentException
2000
-     * @throws InvalidInterfaceException
2001
-     * @throws InvalidDataTypeException
2002
-     * @throws EE_Error
2003
-     */
2004
-    public function get_model()
2005
-    {
2006
-        if (! $this->_model) {
2007
-            $modelName    = self::_get_model_classname(get_class($this));
2008
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2009
-        } else {
2010
-            $this->_model->set_timezone($this->_timezone);
2011
-        }
2012
-        return $this->_model;
2013
-    }
2014
-
2015
-
2016
-    /**
2017
-     * @param $props_n_values
2018
-     * @param $classname
2019
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2020
-     * @throws ReflectionException
2021
-     * @throws InvalidArgumentException
2022
-     * @throws InvalidInterfaceException
2023
-     * @throws InvalidDataTypeException
2024
-     * @throws EE_Error
2025
-     */
2026
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2027
-    {
2028
-        // TODO: will not work for Term_Relationships because they have no PK!
2029
-        $primary_id_ref = self::_get_primary_key_name($classname);
2030
-        if (
2031
-            array_key_exists($primary_id_ref, $props_n_values)
2032
-            && ! empty($props_n_values[ $primary_id_ref ])
2033
-        ) {
2034
-            $id = $props_n_values[ $primary_id_ref ];
2035
-            return self::_get_model($classname)->get_from_entity_map($id);
2036
-        }
2037
-        return false;
2038
-    }
2039
-
2040
-
2041
-    /**
2042
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2043
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2044
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2045
-     * we return false.
2046
-     *
2047
-     * @param array  $props_n_values    incoming array of properties and their values
2048
-     * @param string $classname         the classname of the child class
2049
-     * @param null   $timezone
2050
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the
2051
-     *                                  date_format and the second value is the time format
2052
-     * @return mixed (EE_Base_Class|bool)
2053
-     * @throws InvalidArgumentException
2054
-     * @throws InvalidInterfaceException
2055
-     * @throws InvalidDataTypeException
2056
-     * @throws EE_Error
2057
-     * @throws ReflectionException
2058
-     */
2059
-    protected static function _check_for_object($props_n_values, $classname, $timezone = '', $date_formats = [])
2060
-    {
2061
-        $existing = null;
2062
-        $model    = self::_get_model($classname, $timezone);
2063
-        if ($model->has_primary_key_field()) {
2064
-            $primary_id_ref = self::_get_primary_key_name($classname);
2065
-            if (
2066
-                array_key_exists($primary_id_ref, $props_n_values)
2067
-                && ! empty($props_n_values[ $primary_id_ref ])
2068
-            ) {
2069
-                $existing = $model->get_one_by_ID(
2070
-                    $props_n_values[ $primary_id_ref ]
2071
-                );
2072
-            }
2073
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2074
-            // no primary key on this model, but there's still a matching item in the DB
2075
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2076
-                self::_get_model($classname, $timezone)
2077
-                    ->get_index_primary_key_string($props_n_values)
2078
-            );
2079
-        }
2080
-        if ($existing) {
2081
-            // set date formats if present before setting values
2082
-            if (! empty($date_formats) && is_array($date_formats)) {
2083
-                $existing->set_date_format($date_formats[0]);
2084
-                $existing->set_time_format($date_formats[1]);
2085
-            } else {
2086
-                // set default formats for date and time
2087
-                $existing->set_date_format(get_option('date_format'));
2088
-                $existing->set_time_format(get_option('time_format'));
2089
-            }
2090
-            foreach ($props_n_values as $property => $field_value) {
2091
-                $existing->set($property, $field_value);
2092
-            }
2093
-            return $existing;
2094
-        }
2095
-        return false;
2096
-    }
2097
-
2098
-
2099
-    /**
2100
-     * Gets the EEM_*_Model for this class
2101
-     *
2102
-     * @access public now, as this is more convenient
2103
-     * @param      $classname
2104
-     * @param null $timezone
2105
-     * @return EEM_Base
2106
-     * @throws InvalidArgumentException
2107
-     * @throws InvalidInterfaceException
2108
-     * @throws InvalidDataTypeException
2109
-     * @throws EE_Error
2110
-     * @throws ReflectionException
2111
-     */
2112
-    protected static function _get_model($classname, $timezone = '')
2113
-    {
2114
-        // find model for this class
2115
-        if (! $classname) {
2116
-            throw new EE_Error(
2117
-                sprintf(
2118
-                    esc_html__(
2119
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2120
-                        'event_espresso'
2121
-                    ),
2122
-                    $classname
2123
-                )
2124
-            );
2125
-        }
2126
-        $modelName = self::_get_model_classname($classname);
2127
-        return self::_get_model_instance_with_name($modelName, $timezone);
2128
-    }
2129
-
2130
-
2131
-    /**
2132
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2133
-     *
2134
-     * @param string $model_classname
2135
-     * @param null   $timezone
2136
-     * @return EEM_Base
2137
-     * @throws ReflectionException
2138
-     * @throws InvalidArgumentException
2139
-     * @throws InvalidInterfaceException
2140
-     * @throws InvalidDataTypeException
2141
-     * @throws EE_Error
2142
-     */
2143
-    protected static function _get_model_instance_with_name($model_classname, $timezone = '')
2144
-    {
2145
-        $model_classname = str_replace('EEM_', '', $model_classname);
2146
-        $model           = EE_Registry::instance()->load_model($model_classname);
2147
-        $model->set_timezone($timezone);
2148
-        return $model;
2149
-    }
2150
-
2151
-
2152
-    /**
2153
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2154
-     * Also works if a model class's classname is provided (eg EE_Registration).
2155
-     *
2156
-     * @param string|null $model_name
2157
-     * @return string like EEM_Attendee
2158
-     */
2159
-    private static function _get_model_classname($model_name = '')
2160
-    {
2161
-        return strpos((string) $model_name, 'EE_') === 0
2162
-            ? str_replace('EE_', 'EEM_', $model_name)
2163
-            : 'EEM_' . $model_name;
2164
-    }
2165
-
2166
-
2167
-    /**
2168
-     * returns the name of the primary key attribute
2169
-     *
2170
-     * @param null $classname
2171
-     * @return string
2172
-     * @throws InvalidArgumentException
2173
-     * @throws InvalidInterfaceException
2174
-     * @throws InvalidDataTypeException
2175
-     * @throws EE_Error
2176
-     * @throws ReflectionException
2177
-     */
2178
-    protected static function _get_primary_key_name($classname = null)
2179
-    {
2180
-        if (! $classname) {
2181
-            throw new EE_Error(
2182
-                sprintf(
2183
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2184
-                    $classname
2185
-                )
2186
-            );
2187
-        }
2188
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2189
-    }
2190
-
2191
-
2192
-    /**
2193
-     * Gets the value of the primary key.
2194
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2195
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2196
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2197
-     *
2198
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2199
-     * @throws ReflectionException
2200
-     * @throws InvalidArgumentException
2201
-     * @throws InvalidInterfaceException
2202
-     * @throws InvalidDataTypeException
2203
-     * @throws EE_Error
2204
-     */
2205
-    public function ID()
2206
-    {
2207
-        $model = $this->get_model();
2208
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2209
-        if ($model->has_primary_key_field()) {
2210
-            return $this->_fields[ $model->primary_key_name() ];
2211
-        }
2212
-        return $model->get_index_primary_key_string($this->_fields);
2213
-    }
2214
-
2215
-
2216
-    /**
2217
-     * @param EE_Base_Class|int|string $otherModelObjectOrID
2218
-     * @param string                   $relation_name
2219
-     * @return bool
2220
-     * @throws EE_Error
2221
-     * @throws ReflectionException
2222
-     * @since   5.0.0.p
2223
-     */
2224
-    public function hasRelation($otherModelObjectOrID, string $relation_name): bool
2225
-    {
2226
-        $other_model = self::_get_model_instance_with_name(
2227
-            self::_get_model_classname($relation_name),
2228
-            $this->_timezone
2229
-        );
2230
-        $primary_key = $other_model->primary_key_name();
2231
-        /** @var EE_Base_Class $otherModelObject */
2232
-        $otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relation_name);
2233
-        return $this->count_related($relation_name, [[$primary_key => $otherModelObject->ID()]]) > 0;
2234
-    }
2235
-
2236
-
2237
-    /**
2238
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2239
-     * model is related to a group of events, the $relation_name should be 'Event', and should be a key in the EE
2240
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2241
-     *
2242
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2243
-     * @param string $relation_name                    eg 'Events','Question',etc.
2244
-     *                                                 an attendee to a group, you also want to specify which role they
2245
-     *                                                 will have in that group. So you would use this parameter to
2246
-     *                                                 specify array('role-column-name'=>'role-id')
2247
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2248
-     *                                                 allow you to further constrict the relation to being added.
2249
-     *                                                 However, keep in mind that the columns (keys) given must match a
2250
-     *                                                 column on the JOIN table and currently only the HABTM models
2251
-     *                                                 accept these additional conditions.  Also remember that if an
2252
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2253
-     *                                                 NEW row is created in the join table.
2254
-     * @param null   $cache_id
2255
-     * @return EE_Base_Class the object the relation was added to
2256
-     * @throws ReflectionException
2257
-     * @throws InvalidArgumentException
2258
-     * @throws InvalidInterfaceException
2259
-     * @throws InvalidDataTypeException
2260
-     * @throws EE_Error
2261
-     */
2262
-    public function _add_relation_to(
2263
-        $otherObjectModelObjectOrID,
2264
-        $relation_name,
2265
-        $extra_join_model_fields_n_values = [],
2266
-        $cache_id = null
2267
-    ) {
2268
-        $model = $this->get_model();
2269
-        // if this thing exists in the DB, save the relation to the DB
2270
-        if ($this->ID()) {
2271
-            $otherObject = $model->add_relationship_to(
2272
-                $this,
2273
-                $otherObjectModelObjectOrID,
2274
-                $relation_name,
2275
-                $extra_join_model_fields_n_values
2276
-            );
2277
-            // clear cache so future get_many_related and get_first_related() return new results.
2278
-            $this->clear_cache($relation_name, $otherObject, true);
2279
-            if ($otherObject instanceof EE_Base_Class) {
2280
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2281
-            }
2282
-        } else {
2283
-            // this thing doesn't exist in the DB,  so just cache it
2284
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2285
-                throw new EE_Error(
2286
-                    sprintf(
2287
-                        esc_html__(
2288
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2289
-                            'event_espresso'
2290
-                        ),
2291
-                        $otherObjectModelObjectOrID,
2292
-                        get_class($this)
2293
-                    )
2294
-                );
2295
-            }
2296
-            $otherObject = $otherObjectModelObjectOrID;
2297
-            $this->cache($relation_name, $otherObjectModelObjectOrID, $cache_id);
2298
-        }
2299
-        if ($otherObject instanceof EE_Base_Class) {
2300
-            // fix the reciprocal relation too
2301
-            if ($otherObject->ID()) {
2302
-                // its saved so assumed relations exist in the DB, so we can just
2303
-                // clear the cache so future queries use the updated info in the DB
2304
-                $otherObject->clear_cache(
2305
-                    $model->get_this_model_name(),
2306
-                    null,
2307
-                    true
2308
-                );
2309
-            } else {
2310
-                // it's not saved, so it caches relations like this
2311
-                $otherObject->cache($model->get_this_model_name(), $this);
2312
-            }
2313
-        }
2314
-        return $otherObject;
2315
-    }
2316
-
2317
-
2318
-    /**
2319
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2320
-     * model is related to a group of events, the $relation_name should be 'Events', and should be a key in the EE
2321
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2322
-     * from the cache
2323
-     *
2324
-     * @param mixed  $otherObjectModelObjectOrID
2325
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2326
-     *                to the DB yet
2327
-     * @param string $relation_name
2328
-     * @param array  $where_query
2329
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2330
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2331
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2332
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2333
-     *                deleted.
2334
-     * @return EE_Base_Class the relation was removed from
2335
-     * @throws ReflectionException
2336
-     * @throws InvalidArgumentException
2337
-     * @throws InvalidInterfaceException
2338
-     * @throws InvalidDataTypeException
2339
-     * @throws EE_Error
2340
-     */
2341
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relation_name, $where_query = [])
2342
-    {
2343
-        if ($this->ID()) {
2344
-            // if this exists in the DB, save the relation change to the DB too
2345
-            $otherObject = $this->get_model()->remove_relationship_to(
2346
-                $this,
2347
-                $otherObjectModelObjectOrID,
2348
-                $relation_name,
2349
-                $where_query
2350
-            );
2351
-            $this->clear_cache(
2352
-                $relation_name,
2353
-                $otherObject
2354
-            );
2355
-        } else {
2356
-            // this doesn't exist in the DB, just remove it from the cache
2357
-            $otherObject = $this->clear_cache(
2358
-                $relation_name,
2359
-                $otherObjectModelObjectOrID
2360
-            );
2361
-        }
2362
-        if ($otherObject instanceof EE_Base_Class) {
2363
-            $otherObject->clear_cache(
2364
-                $this->get_model()->get_this_model_name(),
2365
-                $this
2366
-            );
2367
-        }
2368
-        return $otherObject;
2369
-    }
2370
-
2371
-
2372
-    /**
2373
-     * Removes ALL the related things for the $relation_name.
2374
-     *
2375
-     * @param string $relation_name
2376
-     * @param array  $where_query_params @see
2377
-     *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2378
-     * @return EE_Base_Class
2379
-     * @throws ReflectionException
2380
-     * @throws InvalidArgumentException
2381
-     * @throws InvalidInterfaceException
2382
-     * @throws InvalidDataTypeException
2383
-     * @throws EE_Error
2384
-     */
2385
-    public function _remove_relations($relation_name, $where_query_params = [])
2386
-    {
2387
-        if ($this->ID()) {
2388
-            // if this exists in the DB, save the relation change to the DB too
2389
-            $otherObjects = $this->get_model()->remove_relations(
2390
-                $this,
2391
-                $relation_name,
2392
-                $where_query_params
2393
-            );
2394
-            $this->clear_cache(
2395
-                $relation_name,
2396
-                null,
2397
-                true
2398
-            );
2399
-        } else {
2400
-            // this doesn't exist in the DB, just remove it from the cache
2401
-            $otherObjects = $this->clear_cache(
2402
-                $relation_name,
2403
-                null,
2404
-                true
2405
-            );
2406
-        }
2407
-        if (is_array($otherObjects)) {
2408
-            foreach ($otherObjects as $otherObject) {
2409
-                $otherObject->clear_cache(
2410
-                    $this->get_model()->get_this_model_name(),
2411
-                    $this
2412
-                );
2413
-            }
2414
-        }
2415
-        return $otherObjects;
2416
-    }
2417
-
2418
-
2419
-    /**
2420
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2421
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2422
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2423
-     * because we want to get even deleted items etc.
2424
-     *
2425
-     * @param string      $relation_name key in the model's _model_relations array
2426
-     * @param array|null  $query_params  @see
2427
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2428
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2429
-     *                              keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2430
-     *                              results if you want IDs
2431
-     * @throws ReflectionException
2432
-     * @throws InvalidArgumentException
2433
-     * @throws InvalidInterfaceException
2434
-     * @throws InvalidDataTypeException
2435
-     * @throws EE_Error
2436
-     */
2437
-    public function get_many_related($relation_name, $query_params = [])
2438
-    {
2439
-        if ($this->ID()) {
2440
-            // this exists in the DB, so get the related things from either the cache or the DB
2441
-            // if there are query parameters, forget about caching the related model objects.
2442
-            if ($query_params) {
2443
-                $related_model_objects = $this->get_model()->get_all_related(
2444
-                    $this,
2445
-                    $relation_name,
2446
-                    $query_params
2447
-                );
2448
-            } else {
2449
-                // did we already cache the result of this query?
2450
-                $cached_results = $this->get_all_from_cache($relation_name);
2451
-                if (! $cached_results) {
2452
-                    $related_model_objects = $this->get_model()->get_all_related(
2453
-                        $this,
2454
-                        $relation_name,
2455
-                        $query_params
2456
-                    );
2457
-                    // if no query parameters were passed, then we got all the related model objects
2458
-                    // for that relation. We can cache them then.
2459
-                    foreach ($related_model_objects as $related_model_object) {
2460
-                        $this->cache($relation_name, $related_model_object);
2461
-                    }
2462
-                } else {
2463
-                    $related_model_objects = $cached_results;
2464
-                }
2465
-            }
2466
-        } else {
2467
-            // this doesn't exist in the DB, so just get the related things from the cache
2468
-            $related_model_objects = $this->get_all_from_cache($relation_name);
2469
-        }
2470
-        return $related_model_objects;
2471
-    }
2472
-
2473
-
2474
-    /**
2475
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2476
-     * unless otherwise specified in the $query_params
2477
-     *
2478
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2479
-     * @param array  $query_params   @see
2480
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2481
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2482
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2483
-     *                               that by the setting $distinct to TRUE;
2484
-     * @return int
2485
-     * @throws ReflectionException
2486
-     * @throws InvalidArgumentException
2487
-     * @throws InvalidInterfaceException
2488
-     * @throws InvalidDataTypeException
2489
-     * @throws EE_Error
2490
-     */
2491
-    public function count_related($relation_name, $query_params = [], $field_to_count = null, $distinct = false)
2492
-    {
2493
-        return $this->get_model()->count_related(
2494
-            $this,
2495
-            $relation_name,
2496
-            $query_params,
2497
-            $field_to_count,
2498
-            $distinct
2499
-        );
2500
-    }
2501
-
2502
-
2503
-    /**
2504
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2505
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2506
-     *
2507
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2508
-     * @param array  $query_params  @see
2509
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2510
-     * @param string $field_to_sum  name of field to count by.
2511
-     *                              By default, uses primary key
2512
-     *                              (which doesn't make much sense, so you should probably change it)
2513
-     * @return int
2514
-     * @throws ReflectionException
2515
-     * @throws InvalidArgumentException
2516
-     * @throws InvalidInterfaceException
2517
-     * @throws InvalidDataTypeException
2518
-     * @throws EE_Error
2519
-     */
2520
-    public function sum_related($relation_name, $query_params = [], $field_to_sum = null)
2521
-    {
2522
-        return $this->get_model()->sum_related(
2523
-            $this,
2524
-            $relation_name,
2525
-            $query_params,
2526
-            $field_to_sum
2527
-        );
2528
-    }
2529
-
2530
-
2531
-    /**
2532
-     * Gets the first (ie, one) related model object of the specified type.
2533
-     *
2534
-     * @param string $relation_name key in the model's _model_relations array
2535
-     * @param array  $query_params  @see
2536
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2537
-     * @return EE_Base_Class|null (not an array, a single object)
2538
-     * @throws ReflectionException
2539
-     * @throws InvalidArgumentException
2540
-     * @throws InvalidInterfaceException
2541
-     * @throws InvalidDataTypeException
2542
-     * @throws EE_Error
2543
-     */
2544
-    public function get_first_related(string $relation_name, array $query_params = []): ?EE_Base_Class
2545
-    {
2546
-        $model = $this->get_model();
2547
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2548
-            // if they've provided some query parameters, don't bother trying to cache the result
2549
-            // also make sure we're not caching the result of get_first_related
2550
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2551
-            if (
2552
-                $query_params
2553
-                || ! $model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation
2554
-            ) {
2555
-                $related_model_object = $model->get_first_related(
2556
-                    $this,
2557
-                    $relation_name,
2558
-                    $query_params
2559
-                );
2560
-            } else {
2561
-                // first, check if we've already cached the result of this query
2562
-                $cached_result = $this->get_one_from_cache($relation_name);
2563
-                if (! $cached_result) {
2564
-                    $related_model_object = $model->get_first_related(
2565
-                        $this,
2566
-                        $relation_name,
2567
-                        $query_params
2568
-                    );
2569
-                    $this->cache($relation_name, $related_model_object);
2570
-                } else {
2571
-                    $related_model_object = $cached_result;
2572
-                }
2573
-            }
2574
-        } else {
2575
-            $related_model_object = null;
2576
-            // this doesn't exist in the Db,
2577
-            // but maybe the relation is of type belongs to, and so the related thing might
2578
-            if ($model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation) {
2579
-                $related_model_object = $model->get_first_related(
2580
-                    $this,
2581
-                    $relation_name,
2582
-                    $query_params
2583
-                );
2584
-            }
2585
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2586
-            // just get what's cached on this object
2587
-            if (! $related_model_object) {
2588
-                $related_model_object = $this->get_one_from_cache($relation_name);
2589
-            }
2590
-        }
2591
-        return $related_model_object;
2592
-    }
2593
-
2594
-
2595
-    /**
2596
-     * Does a delete on all related objects of type $relation_name and removes
2597
-     * the current model object's relation to them. If they can't be deleted (because
2598
-     * of blocking related model objects) does nothing. If the related model objects are
2599
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2600
-     * If this model object doesn't exist yet in the DB, just removes its related things
2601
-     *
2602
-     * @param string $relation_name
2603
-     * @param array  $query_params @see
2604
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2605
-     * @return int how many deleted
2606
-     * @throws ReflectionException
2607
-     * @throws InvalidArgumentException
2608
-     * @throws InvalidInterfaceException
2609
-     * @throws InvalidDataTypeException
2610
-     * @throws EE_Error
2611
-     */
2612
-    public function delete_related($relation_name, $query_params = [])
2613
-    {
2614
-        if ($this->ID()) {
2615
-            $count = $this->get_model()->delete_related(
2616
-                $this,
2617
-                $relation_name,
2618
-                $query_params
2619
-            );
2620
-        } else {
2621
-            $count = count($this->get_all_from_cache($relation_name));
2622
-            $this->clear_cache($relation_name, null, true);
2623
-        }
2624
-        return $count;
2625
-    }
2626
-
2627
-
2628
-    /**
2629
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relation_name and removes
2630
-     * the current model object's relation to them. If they can't be deleted (because
2631
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2632
-     * If the related thing isn't a soft-deletable model object, this function is identical
2633
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2634
-     *
2635
-     * @param string $relation_name
2636
-     * @param array  $query_params @see
2637
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2638
-     * @return int how many deleted (including those soft deleted)
2639
-     * @throws ReflectionException
2640
-     * @throws InvalidArgumentException
2641
-     * @throws InvalidInterfaceException
2642
-     * @throws InvalidDataTypeException
2643
-     * @throws EE_Error
2644
-     */
2645
-    public function delete_related_permanently($relation_name, $query_params = [])
2646
-    {
2647
-        $count = $this->ID()
2648
-            ? $this->get_model()->delete_related_permanently(
2649
-                $this,
2650
-                $relation_name,
2651
-                $query_params
2652
-            )
2653
-            : count($this->get_all_from_cache($relation_name));
2654
-
2655
-        $this->clear_cache($relation_name, null, true);
2656
-        return $count;
2657
-    }
2658
-
2659
-
2660
-    /**
2661
-     * is_set
2662
-     * Just a simple utility function children can use for checking if property exists
2663
-     *
2664
-     * @access  public
2665
-     * @param string $field_name property to check
2666
-     * @return bool                              TRUE if existing,FALSE if not.
2667
-     */
2668
-    public function is_set($field_name)
2669
-    {
2670
-        return isset($this->_fields[ $field_name ]);
2671
-    }
2672
-
2673
-
2674
-    /**
2675
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2676
-     * EE_Error exception if they don't
2677
-     *
2678
-     * @param mixed (string|array) $properties properties to check
2679
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2680
-     * @throws EE_Error
2681
-     */
2682
-    protected function _property_exists($properties)
2683
-    {
2684
-        foreach ((array) $properties as $property_name) {
2685
-            // first make sure this property exists
2686
-            if (! $this->_fields[ $property_name ]) {
2687
-                throw new EE_Error(
2688
-                    sprintf(
2689
-                        esc_html__(
2690
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2691
-                            'event_espresso'
2692
-                        ),
2693
-                        $property_name
2694
-                    )
2695
-                );
2696
-            }
2697
-        }
2698
-        return true;
2699
-    }
2700
-
2701
-
2702
-    /**
2703
-     * This simply returns an array of model fields for this object
2704
-     *
2705
-     * @return array
2706
-     * @throws ReflectionException
2707
-     * @throws InvalidArgumentException
2708
-     * @throws InvalidInterfaceException
2709
-     * @throws InvalidDataTypeException
2710
-     * @throws EE_Error
2711
-     */
2712
-    public function model_field_array()
2713
-    {
2714
-        $fields     = $this->get_model()->field_settings(false);
2715
-        $properties = [];
2716
-        // remove prepended underscore
2717
-        foreach ($fields as $field_name => $settings) {
2718
-            $properties[ $field_name ] = $this->get($field_name);
2719
-        }
2720
-        return $properties;
2721
-    }
2722
-
2723
-
2724
-    /**
2725
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2726
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2727
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2728
-     * Instead of requiring a plugin to extend the EE_Base_Class
2729
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2730
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2731
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2732
-     * and accepts 2 arguments: the object on which the function was called,
2733
-     * and an array of the original arguments passed to the function.
2734
-     * Whatever their callback function returns will be returned by this function.
2735
-     * Example: in functions.php (or in a plugin):
2736
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2737
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2738
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2739
-     *          return $previousReturnValue.$returnString;
2740
-     *      }
2741
-     * require('EE_Answer.class.php');
2742
-     * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2743
-     *      ->my_callback('monkeys',100);
2744
-     * // will output "you called my_callback! and passed args:monkeys,100"
2745
-     *
2746
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2747
-     * @param array  $args       array of original arguments passed to the function
2748
-     * @return mixed whatever the plugin which calls add_filter decides
2749
-     * @throws EE_Error
2750
-     */
2751
-    public function __call($methodName, $args)
2752
-    {
2753
-        $className = get_class($this);
2754
-        $tagName   = "FHEE__{$className}__{$methodName}";
2755
-        if (! has_filter($tagName)) {
2756
-            throw new EE_Error(
2757
-                sprintf(
2758
-                    esc_html__(
2759
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2760
-                        'event_espresso'
2761
-                    ),
2762
-                    $methodName,
2763
-                    $className,
2764
-                    $tagName
2765
-                )
2766
-            );
2767
-        }
2768
-        return apply_filters($tagName, null, $this, $args);
2769
-    }
2770
-
2771
-
2772
-    /**
2773
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2774
-     * A $previous_value can be specified in case there are many meta rows with the same key
2775
-     *
2776
-     * @param string $meta_key
2777
-     * @param mixed  $meta_value
2778
-     * @param mixed  $previous_value
2779
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2780
-     *                  NOTE: if the values haven't changed, returns 0
2781
-     * @throws InvalidArgumentException
2782
-     * @throws InvalidInterfaceException
2783
-     * @throws InvalidDataTypeException
2784
-     * @throws EE_Error
2785
-     * @throws ReflectionException
2786
-     */
2787
-    public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2788
-    {
2789
-        $query_params = [
2790
-            [
2791
-                'EXM_key'  => $meta_key,
2792
-                'OBJ_ID'   => $this->ID(),
2793
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2794
-            ],
2795
-        ];
2796
-        if ($previous_value !== null) {
2797
-            $query_params[0]['EXM_value'] = $meta_value;
2798
-        }
2799
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2800
-        if (! $existing_rows_like_that) {
2801
-            return $this->add_extra_meta($meta_key, $meta_value);
2802
-        }
2803
-        foreach ($existing_rows_like_that as $existing_row) {
2804
-            $existing_row->save(['EXM_value' => $meta_value]);
2805
-        }
2806
-        return count($existing_rows_like_that);
2807
-    }
2808
-
2809
-
2810
-    /**
2811
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2812
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2813
-     * extra meta row was entered, false if not
2814
-     *
2815
-     * @param string $meta_key
2816
-     * @param mixed  $meta_value
2817
-     * @param bool   $unique
2818
-     * @return bool
2819
-     * @throws InvalidArgumentException
2820
-     * @throws InvalidInterfaceException
2821
-     * @throws InvalidDataTypeException
2822
-     * @throws EE_Error
2823
-     * @throws ReflectionException
2824
-     */
2825
-    public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2826
-    {
2827
-        if ($unique) {
2828
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2829
-                [
2830
-                    [
2831
-                        'EXM_key'  => $meta_key,
2832
-                        'OBJ_ID'   => $this->ID(),
2833
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2834
-                    ],
2835
-                ]
2836
-            );
2837
-            if ($existing_extra_meta) {
2838
-                return false;
2839
-            }
2840
-        }
2841
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2842
-            [
2843
-                'EXM_key'   => $meta_key,
2844
-                'EXM_value' => $meta_value,
2845
-                'OBJ_ID'    => $this->ID(),
2846
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2847
-            ]
2848
-        );
2849
-        $new_extra_meta->save();
2850
-        return true;
2851
-    }
2852
-
2853
-
2854
-    /**
2855
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2856
-     * is specified, only deletes extra meta records with that value.
2857
-     *
2858
-     * @param string $meta_key
2859
-     * @param mixed  $meta_value
2860
-     * @return int|bool number of extra meta rows deleted
2861
-     * @throws InvalidArgumentException
2862
-     * @throws InvalidInterfaceException
2863
-     * @throws InvalidDataTypeException
2864
-     * @throws EE_Error
2865
-     * @throws ReflectionException
2866
-     */
2867
-    public function delete_extra_meta(string $meta_key, $meta_value = null)
2868
-    {
2869
-        $query_params = [
2870
-            [
2871
-                'EXM_key'  => $meta_key,
2872
-                'OBJ_ID'   => $this->ID(),
2873
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2874
-            ],
2875
-        ];
2876
-        if ($meta_value !== null) {
2877
-            $query_params[0]['EXM_value'] = $meta_value;
2878
-        }
2879
-        return EEM_Extra_Meta::instance()->delete($query_params);
2880
-    }
2881
-
2882
-
2883
-    /**
2884
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2885
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2886
-     * You can specify $default is case you haven't found the extra meta
2887
-     *
2888
-     * @param string     $meta_key
2889
-     * @param bool       $single
2890
-     * @param mixed      $default if we don't find anything, what should we return?
2891
-     * @param array|null $extra_where
2892
-     * @return mixed single value if $single; array if ! $single
2893
-     * @throws ReflectionException
2894
-     * @throws EE_Error
2895
-     */
2896
-    public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2897
-    {
2898
-        $query_params = [$extra_where + ['EXM_key' => $meta_key]];
2899
-        if ($single) {
2900
-            $result = $this->get_first_related('Extra_Meta', $query_params);
2901
-            if ($result instanceof EE_Extra_Meta) {
2902
-                return $result->value();
2903
-            }
2904
-        } else {
2905
-            $results = $this->get_many_related('Extra_Meta', $query_params);
2906
-            if ($results) {
2907
-                $values = [];
2908
-                foreach ($results as $result) {
2909
-                    if ($result instanceof EE_Extra_Meta) {
2910
-                        $values[ $result->ID() ] = $result->value();
2911
-                    }
2912
-                }
2913
-                return $values;
2914
-            }
2915
-        }
2916
-        // if nothing discovered yet return default.
2917
-        return apply_filters(
2918
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2919
-            $default,
2920
-            $meta_key,
2921
-            $single,
2922
-            $this
2923
-        );
2924
-    }
2925
-
2926
-
2927
-    /**
2928
-     * Returns a simple array of all the extra meta associated with this model object.
2929
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2930
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2931
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2932
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2933
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2934
-     * finally the extra meta's value as each sub-value. (eg
2935
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2936
-     *
2937
-     * @param bool $one_of_each_key
2938
-     * @return array
2939
-     * @throws ReflectionException
2940
-     * @throws InvalidArgumentException
2941
-     * @throws InvalidInterfaceException
2942
-     * @throws InvalidDataTypeException
2943
-     * @throws EE_Error
2944
-     */
2945
-    public function all_extra_meta_array(bool $one_of_each_key = true): array
2946
-    {
2947
-        $return_array = [];
2948
-        if ($one_of_each_key) {
2949
-            $extra_meta_objs = $this->get_many_related(
2950
-                'Extra_Meta',
2951
-                ['group_by' => 'EXM_key']
2952
-            );
2953
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2954
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2955
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2956
-                }
2957
-            }
2958
-        } else {
2959
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2960
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2961
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2962
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2963
-                        $return_array[ $extra_meta_obj->key() ] = [];
2964
-                    }
2965
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2966
-                }
2967
-            }
2968
-        }
2969
-        return $return_array;
2970
-    }
2971
-
2972
-
2973
-    /**
2974
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2975
-     *
2976
-     * @return string
2977
-     * @throws ReflectionException
2978
-     * @throws InvalidArgumentException
2979
-     * @throws InvalidInterfaceException
2980
-     * @throws InvalidDataTypeException
2981
-     * @throws EE_Error
2982
-     */
2983
-    public function name()
2984
-    {
2985
-        // find a field that's not a text field
2986
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2987
-        if ($field_we_can_use) {
2988
-            return $this->get($field_we_can_use->get_name());
2989
-        }
2990
-        $first_few_properties = $this->model_field_array();
2991
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
2992
-        $name_parts           = [];
2993
-        foreach ($first_few_properties as $name => $value) {
2994
-            $name_parts[] = "$name:$value";
2995
-        }
2996
-        return implode(',', $name_parts);
2997
-    }
2998
-
2999
-
3000
-    /**
3001
-     * in_entity_map
3002
-     * Checks if this model object has been proven to already be in the entity map
3003
-     *
3004
-     * @return boolean
3005
-     * @throws ReflectionException
3006
-     * @throws InvalidArgumentException
3007
-     * @throws InvalidInterfaceException
3008
-     * @throws InvalidDataTypeException
3009
-     * @throws EE_Error
3010
-     */
3011
-    public function in_entity_map()
3012
-    {
3013
-        // well, if we looked, did we find it in the entity map?
3014
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3015
-    }
3016
-
3017
-
3018
-    /**
3019
-     * refresh_from_db
3020
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3021
-     *
3022
-     * @throws ReflectionException
3023
-     * @throws InvalidArgumentException
3024
-     * @throws InvalidInterfaceException
3025
-     * @throws InvalidDataTypeException
3026
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3027
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3028
-     */
3029
-    public function refresh_from_db()
3030
-    {
3031
-        if ($this->ID() && $this->in_entity_map()) {
3032
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3033
-        } else {
3034
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3035
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3036
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3037
-            // absolutely nothing in it for this ID
3038
-            if (WP_DEBUG) {
3039
-                throw new EE_Error(
3040
-                    sprintf(
3041
-                        esc_html__(
3042
-                            'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3043
-                            'event_espresso'
3044
-                        ),
3045
-                        $this->ID(),
3046
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3047
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3048
-                    )
3049
-                );
3050
-            }
3051
-        }
3052
-    }
3053
-
3054
-
3055
-    /**
3056
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3057
-     *
3058
-     * @param EE_Model_Field_Base[] $fields
3059
-     * @param string                $new_value_sql
3060
-     *          example: 'column_name=123',
3061
-     *          or 'column_name=column_name+1',
3062
-     *          or 'column_name= CASE
3063
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3064
-     *          THEN `column_name` + 5
3065
-     *          ELSE `column_name`
3066
-     *          END'
3067
-     *          Also updates $field on this model object with the latest value from the database.
3068
-     * @return bool
3069
-     * @throws EE_Error
3070
-     * @throws InvalidArgumentException
3071
-     * @throws InvalidDataTypeException
3072
-     * @throws InvalidInterfaceException
3073
-     * @throws ReflectionException
3074
-     * @since 4.9.80.p
3075
-     */
3076
-    protected function updateFieldsInDB($fields, $new_value_sql)
3077
-    {
3078
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3079
-        // if it wasn't even there to start off.
3080
-        if (! $this->ID()) {
3081
-            $this->save();
3082
-        }
3083
-        global $wpdb;
3084
-        if (empty($fields)) {
3085
-            throw new InvalidArgumentException(
3086
-                esc_html__(
3087
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3088
-                    'event_espresso'
3089
-                )
3090
-            );
3091
-        }
3092
-        $first_field = reset($fields);
3093
-        $table_alias = $first_field->get_table_alias();
3094
-        foreach ($fields as $field) {
3095
-            if ($table_alias !== $field->get_table_alias()) {
3096
-                throw new InvalidArgumentException(
3097
-                    sprintf(
3098
-                        esc_html__(
3099
-                        // @codingStandardsIgnoreStart
3100
-                            'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3101
-                            // @codingStandardsIgnoreEnd
3102
-                            'event_espresso'
3103
-                        ),
3104
-                        $table_alias,
3105
-                        $field->get_table_alias()
3106
-                    )
3107
-                );
3108
-            }
3109
-        }
3110
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3111
-        $table_obj      = $this->get_model()->get_table_obj_by_alias($table_alias);
3112
-        $table_pk_value = $this->ID();
3113
-        $table_name     = $table_obj->get_table_name();
3114
-        if ($table_obj instanceof EE_Secondary_Table) {
3115
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3116
-        } else {
3117
-            $table_pk_field_name = $table_obj->get_pk_column();
3118
-        }
3119
-
3120
-        $query  =
3121
-            "UPDATE `{$table_name}`
18
+	/**
19
+	 * @var EEM_Base|null
20
+	 */
21
+	protected $_model = null;
22
+
23
+	/**
24
+	 * This is an array of the original properties and values provided during construction
25
+	 * of this model object. (keys are model field names, values are their values).
26
+	 * This list is important to remember so that when we are merging data from the db, we know
27
+	 * which values to override and which to not override.
28
+	 */
29
+	protected ?array $_props_n_values_provided_in_constructor = null;
30
+
31
+	/**
32
+	 * Timezone
33
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
34
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
35
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
36
+	 * access to it.
37
+	 */
38
+	protected string $_timezone = '';
39
+
40
+	/**
41
+	 * date format
42
+	 * pattern or format for displaying dates
43
+	 */
44
+	protected string $_dt_frmt = '';
45
+
46
+	/**
47
+	 * time format
48
+	 * pattern or format for displaying time
49
+	 */
50
+	protected string $_tm_frmt = '';
51
+
52
+	/**
53
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
54
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
55
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
56
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
57
+	 */
58
+	protected array $_cached_properties = [];
59
+
60
+	/**
61
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
62
+	 * single
63
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
64
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
65
+	 * all others have an array)
66
+	 */
67
+	protected array $_model_relations = [];
68
+
69
+	/**
70
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
71
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
72
+	 */
73
+	protected array $_fields = [];
74
+
75
+	/**
76
+	 * indicating whether or not this model object is intended to ever be saved
77
+	 * For example, we might create model objects intended to only be used for the duration
78
+	 * of this request and to be thrown away, and if they were accidentally saved
79
+	 * it would be a bug.
80
+	 */
81
+	protected bool $_allow_persist = true;
82
+
83
+	/**
84
+	 * indicating whether or not this model object's properties have changed since construction
85
+	 */
86
+	protected bool $_has_changes = false;
87
+
88
+	/**
89
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
90
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
91
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
92
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
93
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
94
+	 * array as:
95
+	 * array(
96
+	 *  'Registration_Count' => 24
97
+	 * );
98
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
99
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
100
+	 * info)
101
+	 */
102
+	protected array $custom_selection_results = [];
103
+
104
+
105
+	/**
106
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
107
+	 * play nice
108
+	 *
109
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
110
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
111
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
112
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
113
+	 *                                                         corresponding db model or not.
114
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
115
+	 *                                                         be in when instantiating a EE_Base_Class object.
116
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
117
+	 *                                                         value is the date_format and second value is the time
118
+	 *                                                         format.
119
+	 * @throws InvalidArgumentException
120
+	 * @throws InvalidInterfaceException
121
+	 * @throws InvalidDataTypeException
122
+	 * @throws EE_Error
123
+	 * @throws ReflectionException
124
+	 */
125
+	protected function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
126
+	{
127
+		$className = get_class($this);
128
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
129
+		$model        = $this->get_model();
130
+		$model_fields = $model->field_settings();
131
+		// ensure $fieldValues is an array
132
+		$fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
133
+		// verify client code has not passed any invalid field names
134
+		foreach ($fieldValues as $field_name => $field_value) {
135
+			if (! isset($model_fields[ $field_name ])) {
136
+				throw new EE_Error(
137
+					sprintf(
138
+						esc_html__(
139
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
140
+							'event_espresso'
141
+						),
142
+						$field_name,
143
+						get_class($this),
144
+						implode(', ', array_keys($model_fields))
145
+					)
146
+				);
147
+			}
148
+		}
149
+
150
+		$date_format     = null;
151
+		$time_format     = null;
152
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
153
+		if (! empty($date_formats) && is_array($date_formats)) {
154
+			[$date_format, $time_format] = $date_formats;
155
+		}
156
+		$this->set_date_format($date_format);
157
+		$this->set_time_format($time_format);
158
+		// if db model is instantiating
159
+		foreach ($model_fields as $fieldName => $field) {
160
+			if ($bydb) {
161
+				// client code has indicated these field values are from the database
162
+				$this->set_from_db(
163
+					$fieldName,
164
+					$fieldValues[ $fieldName ] ?? null
165
+				);
166
+			} else {
167
+				// we're constructing a brand new instance of the model object.
168
+				// Generally, this means we'll need to do more field validation
169
+				$this->set(
170
+					$fieldName,
171
+					$fieldValues[ $fieldName ] ?? null,
172
+					true
173
+				);
174
+			}
175
+		}
176
+		// remember what values were passed to this constructor
177
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
178
+		// remember in entity mapper
179
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
180
+			$model->add_to_entity_map($this);
181
+		}
182
+		// setup all the relations
183
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
184
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
185
+				$this->_model_relations[ $relation_name ] = null;
186
+			} else {
187
+				$this->_model_relations[ $relation_name ] = [];
188
+			}
189
+		}
190
+		/**
191
+		 * Action done at the end of each model object construction
192
+		 *
193
+		 * @param EE_Base_Class $this the model object just created
194
+		 */
195
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
196
+	}
197
+
198
+
199
+	/**
200
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
201
+	 *
202
+	 * @return boolean
203
+	 */
204
+	public function allow_persist()
205
+	{
206
+		return $this->_allow_persist;
207
+	}
208
+
209
+
210
+	/**
211
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
212
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
213
+	 * you got new information that somehow made you change your mind.
214
+	 *
215
+	 * @param boolean $allow_persist
216
+	 * @return boolean
217
+	 */
218
+	public function set_allow_persist($allow_persist)
219
+	{
220
+		return $this->_allow_persist = $allow_persist;
221
+	}
222
+
223
+
224
+	/**
225
+	 * Gets the field's original value when this object was constructed during this request.
226
+	 * This can be helpful when determining if a model object has changed or not
227
+	 *
228
+	 * @param string $field_name
229
+	 * @return mixed|null
230
+	 * @throws ReflectionException
231
+	 * @throws InvalidArgumentException
232
+	 * @throws InvalidInterfaceException
233
+	 * @throws InvalidDataTypeException
234
+	 * @throws EE_Error
235
+	 */
236
+	public function get_original($field_name)
237
+	{
238
+		if (
239
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
240
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
241
+		) {
242
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
243
+		}
244
+		return null;
245
+	}
246
+
247
+
248
+	/**
249
+	 * @param EE_Base_Class $obj
250
+	 * @return string
251
+	 */
252
+	public function get_class($obj)
253
+	{
254
+		return get_class($obj);
255
+	}
256
+
257
+
258
+	/**
259
+	 * Overrides parent because parent expects old models.
260
+	 * This also doesn't do any validation, and won't work for serialized arrays
261
+	 *
262
+	 * @param string $field_name
263
+	 * @param mixed  $field_value
264
+	 * @param bool   $use_default
265
+	 * @throws InvalidArgumentException
266
+	 * @throws InvalidInterfaceException
267
+	 * @throws InvalidDataTypeException
268
+	 * @throws EE_Error
269
+	 * @throws ReflectionException
270
+	 * @throws Exception
271
+	 */
272
+	public function set(string $field_name, $field_value, bool $use_default = false)
273
+	{
274
+		// if not using default and nothing has changed, and object has already been setup (has ID),
275
+		// then don't do anything
276
+		if (
277
+			! $use_default
278
+			&& $this->_fields[ $field_name ] === $field_value
279
+			&& $this->ID()
280
+		) {
281
+			return;
282
+		}
283
+		$model              = $this->get_model();
284
+		$this->_has_changes = true;
285
+		$field_obj          = $model->field_settings_for($field_name);
286
+		if (! $field_obj instanceof EE_Model_Field_Base) {
287
+			throw new EE_Error(
288
+				sprintf(
289
+					esc_html__(
290
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
291
+						'event_espresso'
292
+					),
293
+					$field_name
294
+				)
295
+			);
296
+		}
297
+		// if ( method_exists( $field_obj, 'set_timezone' )) {
298
+		if ($field_obj instanceof EE_Datetime_Field) {
299
+			$field_obj->set_timezone($this->_timezone);
300
+			$field_obj->set_date_format($this->_dt_frmt);
301
+			$field_obj->set_time_format($this->_tm_frmt);
302
+		}
303
+
304
+		// should the value be null?
305
+		$value = $field_value === null && ($use_default || ! $field_obj->is_nullable())
306
+			? $field_obj->get_default_value()
307
+			: $field_value;
308
+
309
+		$this->_fields[ $field_name ] = $field_obj->prepare_for_set($value);
310
+
311
+		// if we're not in the constructor...
312
+		// now check if what we set was a primary key
313
+		if (
314
+			// note: props_n_values_provided_in_constructor is only set at the END of the constructor
315
+			$this->_props_n_values_provided_in_constructor
316
+			&& $field_value
317
+			&& $field_name === $model->primary_key_name()
318
+		) {
319
+			// if so, we want all this object's fields to be filled either with
320
+			// what we've explicitly set on this model
321
+			// or what we have in the db
322
+			// echo "setting primary key!";
323
+			$fields_on_model = self::_get_model(get_class($this))->field_settings();
324
+			$obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
325
+			foreach ($fields_on_model as $field_obj) {
326
+				if (
327
+					! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
328
+					&& $field_obj->get_name() !== $field_name
329
+				) {
330
+					$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
331
+				}
332
+			}
333
+			// oh this model object has an ID? well make sure its in the entity mapper
334
+			$model->add_to_entity_map($this);
335
+		}
336
+		// let's unset any cache for this field_name from the $_cached_properties property.
337
+		$this->_clear_cached_property($field_name);
338
+	}
339
+
340
+
341
+	/**
342
+	 * Overrides parent because parent expects old models.
343
+	 * This also doesn't do any validation, and won't work for serialized arrays
344
+	 *
345
+	 * @param string $field_name
346
+	 * @param mixed  $field_value_from_db
347
+	 * @throws ReflectionException
348
+	 * @throws InvalidArgumentException
349
+	 * @throws InvalidInterfaceException
350
+	 * @throws InvalidDataTypeException
351
+	 * @throws EE_Error
352
+	 */
353
+	public function set_from_db(string $field_name, $field_value_from_db)
354
+	{
355
+		$field_obj = $this->get_model()->field_settings_for($field_name);
356
+		if ($field_obj instanceof EE_Model_Field_Base) {
357
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
358
+			// eg, a CPT model object could have an entry in the posts table, but no
359
+			// entry in the meta table. Meaning that all its columns in the meta table
360
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
361
+			if ($field_value_from_db === null) {
362
+				if ($field_obj->is_nullable()) {
363
+					// if the field allows nulls, then let it be null
364
+					$field_value = null;
365
+				} else {
366
+					$field_value = $field_obj->get_default_value();
367
+				}
368
+			} else {
369
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
370
+			}
371
+			$this->_fields[ $field_name ] = $field_value;
372
+			$this->_clear_cached_property($field_name);
373
+		}
374
+	}
375
+
376
+
377
+	/**
378
+	 * Set custom select values for model.
379
+	 *
380
+	 * @param array $custom_select_values
381
+	 */
382
+	public function setCustomSelectsValues(array $custom_select_values)
383
+	{
384
+		$this->custom_selection_results = $custom_select_values;
385
+	}
386
+
387
+
388
+	/**
389
+	 * Returns the custom select value for the provided alias if its set.
390
+	 * If not set, returns null.
391
+	 *
392
+	 * @param string $alias
393
+	 * @return string|int|float|null
394
+	 */
395
+	public function getCustomSelect($alias)
396
+	{
397
+		return $this->custom_selection_results[ $alias ] ?? null;
398
+	}
399
+
400
+
401
+	/**
402
+	 * This sets the field value on the db column if it exists for the given $column_name or
403
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
404
+	 *
405
+	 * @param string $field_name  Must be the exact column name.
406
+	 * @param mixed  $field_value The value to set.
407
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
+	 * @throws InvalidArgumentException
409
+	 * @throws InvalidInterfaceException
410
+	 * @throws InvalidDataTypeException
411
+	 * @throws EE_Error
412
+	 * @throws ReflectionException
413
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
414
+	 */
415
+	public function set_field_or_extra_meta($field_name, $field_value)
416
+	{
417
+		if ($this->get_model()->has_field($field_name)) {
418
+			$this->set($field_name, $field_value);
419
+			return true;
420
+		}
421
+		// ensure this object is saved first so that extra meta can be properly related.
422
+		$this->save();
423
+		return $this->update_extra_meta($field_name, $field_value);
424
+	}
425
+
426
+
427
+	/**
428
+	 * This retrieves the value of the db column set on this class or if that's not present
429
+	 * it will attempt to retrieve from extra_meta if found.
430
+	 * Example Usage:
431
+	 * Via EE_Message child class:
432
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
433
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
434
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
435
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
436
+	 * value for those extra fields dynamically via the EE_message object.
437
+	 *
438
+	 * @param string $field_name expecting the fully qualified field name.
439
+	 * @return mixed|null  value for the field if found.  null if not found.
440
+	 * @throws ReflectionException
441
+	 * @throws InvalidArgumentException
442
+	 * @throws InvalidInterfaceException
443
+	 * @throws InvalidDataTypeException
444
+	 * @throws EE_Error
445
+	 */
446
+	public function get_field_or_extra_meta($field_name)
447
+	{
448
+		if ($this->get_model()->has_field($field_name)) {
449
+			$column_value = $this->get($field_name);
450
+		} else {
451
+			// This isn't a column in the main table, let's see if it is in the extra meta.
452
+			$column_value = $this->get_extra_meta($field_name, true, null);
453
+		}
454
+		return $column_value;
455
+	}
456
+
457
+
458
+	/**
459
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
460
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
461
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
462
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
463
+	 *
464
+	 * @access public
465
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
466
+	 * @return void
467
+	 * @throws InvalidArgumentException
468
+	 * @throws InvalidInterfaceException
469
+	 * @throws InvalidDataTypeException
470
+	 * @throws EE_Error
471
+	 * @throws ReflectionException
472
+	 * @throws Exception
473
+	 */
474
+	public function set_timezone($timezone = '')
475
+	{
476
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
477
+		// make sure we clear all cached properties because they won't be relevant now
478
+		$this->_clear_cached_properties();
479
+		// make sure we update field settings and the date for all EE_Datetime_Fields
480
+		$model_fields = $this->get_model()->field_settings(false);
481
+		foreach ($model_fields as $field_name => $field_obj) {
482
+			if ($field_obj instanceof EE_Datetime_Field) {
483
+				$field_obj->set_timezone($this->_timezone);
484
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
485
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
486
+				}
487
+			}
488
+		}
489
+	}
490
+
491
+
492
+	/**
493
+	 * This just returns whatever is set for the current timezone.
494
+	 *
495
+	 * @access public
496
+	 * @return string timezone string
497
+	 */
498
+	public function get_timezone()
499
+	{
500
+		return $this->_timezone;
501
+	}
502
+
503
+
504
+	/**
505
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
506
+	 * internally instead of wp set date format options
507
+	 *
508
+	 * @param string|null $format should be a format recognizable by PHP date() functions.
509
+	 * @since 4.6
510
+	 */
511
+	public function set_date_format(?string $format)
512
+	{
513
+		$this->_dt_frmt = new DateFormat($format);
514
+		// clear cached_properties because they won't be relevant now.
515
+		$this->_clear_cached_properties();
516
+	}
517
+
518
+
519
+	/**
520
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
521
+	 * class internally instead of wp set time format options.
522
+	 *
523
+	 * @param string|null $format should be a format recognizable by PHP date() functions.
524
+	 * @since 4.6
525
+	 */
526
+	public function set_time_format(?string $format)
527
+	{
528
+		$this->_tm_frmt = new TimeFormat($format);
529
+		// clear cached_properties because they won't be relevant now.
530
+		$this->_clear_cached_properties();
531
+	}
532
+
533
+
534
+	/**
535
+	 * This returns the current internal set format for the date and time formats.
536
+	 *
537
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
538
+	 *                             where the first value is the date format and the second value is the time format.
539
+	 * @return string|array
540
+	 */
541
+	public function get_format($full = true)
542
+	{
543
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
544
+	}
545
+
546
+
547
+	/**
548
+	 * cache
549
+	 * stores the passed model object on the current model object.
550
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
551
+	 *
552
+	 * @param string        $relation_name   one of the keys in the _model_relations array on the model. Eg
553
+	 *                                       'Registration' associated with this model object
554
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
555
+	 *                                       that could be a payment or a registration)
556
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
557
+	 *                                       items which will be stored in an array on this object
558
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
559
+	 *                                       related thing, no array)
560
+	 * @throws InvalidArgumentException
561
+	 * @throws InvalidInterfaceException
562
+	 * @throws InvalidDataTypeException
563
+	 * @throws EE_Error
564
+	 * @throws ReflectionException
565
+	 */
566
+	public function cache($relation_name = '', $object_to_cache = null, $cache_id = null)
567
+	{
568
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
569
+		if (! $object_to_cache instanceof EE_Base_Class) {
570
+			return false;
571
+		}
572
+		// also get "how" the object is related, or throw an error
573
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
574
+			throw new EE_Error(
575
+				sprintf(
576
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
577
+					$relation_name,
578
+					get_class($this)
579
+				)
580
+			);
581
+		}
582
+		// how many things are related ?
583
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
584
+			// if it's a "belongs to" relationship, then there's only one related model object
585
+			// eg, if this is a registration, there's only 1 attendee for it
586
+			// so for these model objects just set it to be cached
587
+			$this->_model_relations[ $relation_name ] = $object_to_cache;
588
+			$return                                   = true;
589
+		} else {
590
+			// otherwise, this is the "many" side of a one to many relationship,
591
+			// so we'll add the object to the array of related objects for that type.
592
+			// eg: if this is an event, there are many registrations for that event,
593
+			// so we cache the registrations in an array
594
+			if (! is_array($this->_model_relations[ $relation_name ])) {
595
+				// if for some reason, the cached item is a model object,
596
+				// then stick that in the array, otherwise start with an empty array
597
+				$this->_model_relations[ $relation_name ] =
598
+					$this->_model_relations[ $relation_name ] instanceof EE_Base_Class
599
+						? [$this->_model_relations[ $relation_name ]]
600
+						: [];
601
+			}
602
+			// first check for a cache_id which is normally empty
603
+			if (! empty($cache_id)) {
604
+				// if the cache_id exists, then it means we are purposely trying to cache this
605
+				// with a known key that can then be used to retrieve the object later on
606
+				$this->_model_relations[ $relation_name ][ $cache_id ] = $object_to_cache;
607
+				$return                                                = $cache_id;
608
+			} elseif ($object_to_cache->ID()) {
609
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
610
+				$this->_model_relations[ $relation_name ][ $object_to_cache->ID() ] = $object_to_cache;
611
+				$return                                                             = $object_to_cache->ID();
612
+			} else {
613
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
614
+				$this->_model_relations[ $relation_name ][] = $object_to_cache;
615
+				// move the internal pointer to the end of the array
616
+				end($this->_model_relations[ $relation_name ]);
617
+				// and grab the key so that we can return it
618
+				$return = key($this->_model_relations[ $relation_name ]);
619
+			}
620
+		}
621
+		return $return;
622
+	}
623
+
624
+
625
+	/**
626
+	 * For adding an item to the cached_properties property.
627
+	 *
628
+	 * @access protected
629
+	 * @param string      $fieldname the property item the corresponding value is for.
630
+	 * @param mixed       $value     The value we are caching.
631
+	 * @param string|null $cache_type
632
+	 * @return void
633
+	 * @throws ReflectionException
634
+	 * @throws InvalidArgumentException
635
+	 * @throws InvalidInterfaceException
636
+	 * @throws InvalidDataTypeException
637
+	 * @throws EE_Error
638
+	 */
639
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
640
+	{
641
+		// first make sure this property exists
642
+		$this->get_model()->field_settings_for($fieldname);
643
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
644
+
645
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
646
+	}
647
+
648
+
649
+	/**
650
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
651
+	 * This also SETS the cache if we return the actual property!
652
+	 *
653
+	 * @param string $fieldname        the name of the property we're trying to retrieve
654
+	 * @param bool   $pretty
655
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
656
+	 *                                 (in cases where the same property may be used for different outputs
657
+	 *                                 - i.e. datetime, money etc.)
658
+	 *                                 It can also accept certain pre-defined "schema" strings
659
+	 *                                 to define how to output the property.
660
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
661
+	 * @return mixed                   whatever the value for the property is we're retrieving
662
+	 * @throws ReflectionException
663
+	 * @throws InvalidArgumentException
664
+	 * @throws InvalidInterfaceException
665
+	 * @throws InvalidDataTypeException
666
+	 * @throws EE_Error
667
+	 */
668
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
669
+	{
670
+		// verify the field exists
671
+		$model = $this->get_model();
672
+		$model->field_settings_for($fieldname);
673
+		$cache_type = $pretty ? 'pretty' : 'standard';
674
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
675
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
676
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
677
+		}
678
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
679
+		$this->_set_cached_property($fieldname, $value, $cache_type);
680
+		return $value;
681
+	}
682
+
683
+
684
+	/**
685
+	 * If the cache didn't fetch the needed item, this fetches it.
686
+	 *
687
+	 * @param string $fieldname
688
+	 * @param bool   $pretty
689
+	 * @param string $extra_cache_ref
690
+	 * @return mixed
691
+	 * @throws InvalidArgumentException
692
+	 * @throws InvalidInterfaceException
693
+	 * @throws InvalidDataTypeException
694
+	 * @throws EE_Error
695
+	 * @throws ReflectionException
696
+	 */
697
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
698
+	{
699
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
700
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
701
+		if ($field_obj instanceof EE_Datetime_Field) {
702
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
703
+		}
704
+		if (! isset($this->_fields[ $fieldname ])) {
705
+			$this->_fields[ $fieldname ] = null;
706
+		}
707
+		return $pretty
708
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
709
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
710
+	}
711
+
712
+
713
+	/**
714
+	 * set timezone, formats, and output for EE_Datetime_Field objects
715
+	 *
716
+	 * @param EE_Datetime_Field $datetime_field
717
+	 * @param bool              $pretty
718
+	 * @param null              $date_or_time
719
+	 * @return void
720
+	 * @throws InvalidArgumentException
721
+	 * @throws InvalidInterfaceException
722
+	 * @throws InvalidDataTypeException
723
+	 */
724
+	protected function _prepare_datetime_field(
725
+		EE_Datetime_Field $datetime_field,
726
+		$pretty = false,
727
+		$date_or_time = null
728
+	) {
729
+		$datetime_field->set_timezone($this->_timezone);
730
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
731
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
732
+		// set the output returned
733
+		switch ($date_or_time) {
734
+			case 'D':
735
+				$datetime_field->set_date_time_output('date');
736
+				break;
737
+			case 'T':
738
+				$datetime_field->set_date_time_output('time');
739
+				break;
740
+			default:
741
+				$datetime_field->set_date_time_output();
742
+		}
743
+	}
744
+
745
+
746
+	/**
747
+	 * This just takes care of clearing out the cached_properties
748
+	 *
749
+	 * @return void
750
+	 */
751
+	protected function _clear_cached_properties()
752
+	{
753
+		$this->_cached_properties = [];
754
+	}
755
+
756
+
757
+	/**
758
+	 * This just clears out ONE property if it exists in the cache
759
+	 *
760
+	 * @param string $property_name the property to remove if it exists (from the _cached_properties array)
761
+	 * @return void
762
+	 */
763
+	protected function _clear_cached_property($property_name)
764
+	{
765
+		if (isset($this->_cached_properties[ $property_name ])) {
766
+			unset($this->_cached_properties[ $property_name ]);
767
+		}
768
+	}
769
+
770
+
771
+	/**
772
+	 * Ensures that this related thing is a model object.
773
+	 *
774
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
775
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
776
+	 * @return EE_Base_Class
777
+	 * @throws ReflectionException
778
+	 * @throws InvalidArgumentException
779
+	 * @throws InvalidInterfaceException
780
+	 * @throws InvalidDataTypeException
781
+	 * @throws EE_Error
782
+	 */
783
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
784
+	{
785
+		$other_model_instance = self::_get_model_instance_with_name(
786
+			self::_get_model_classname($model_name),
787
+			$this->_timezone
788
+		);
789
+		return $other_model_instance->ensure_is_obj($object_or_id);
790
+	}
791
+
792
+
793
+	/**
794
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
795
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
796
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
797
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
798
+	 *
799
+	 * @param string $relation_name                        one of the keys in the _model_relations array on the model.
800
+	 *                                                     Eg 'Registration'
801
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
802
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
803
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
804
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
805
+	 *                                                     this is HasMany or HABTM.
806
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
807
+	 *                                                     relation from all
808
+	 * @throws InvalidArgumentException
809
+	 * @throws InvalidInterfaceException
810
+	 * @throws InvalidDataTypeException
811
+	 * @throws EE_Error
812
+	 * @throws ReflectionException
813
+	 */
814
+	public function clear_cache($relation_name, $object_to_remove_or_index_into_array = null, $clear_all = false)
815
+	{
816
+		$relationship_to_model = $this->get_model()->related_settings_for($relation_name);
817
+		$index_in_cache        = '';
818
+		if (! $relationship_to_model) {
819
+			throw new EE_Error(
820
+				sprintf(
821
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
822
+					$relation_name,
823
+					get_class($this)
824
+				)
825
+			);
826
+		}
827
+		if ($clear_all) {
828
+			$obj_removed                              = true;
829
+			$this->_model_relations[ $relation_name ] = null;
830
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
831
+			$obj_removed                              = $this->_model_relations[ $relation_name ];
832
+			$this->_model_relations[ $relation_name ] = null;
833
+		} else {
834
+			if (
835
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
836
+				&& $object_to_remove_or_index_into_array->ID()
837
+			) {
838
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
839
+				if (
840
+					is_array($this->_model_relations[ $relation_name ])
841
+					&& ! isset($this->_model_relations[ $relation_name ][ $index_in_cache ])
842
+				) {
843
+					$index_found_at = null;
844
+					// find this object in the array even though it has a different key
845
+					foreach ($this->_model_relations[ $relation_name ] as $index => $obj) {
846
+						/** @noinspection TypeUnsafeComparisonInspection */
847
+						if (
848
+							$obj instanceof EE_Base_Class
849
+							&& (
850
+								$obj == $object_to_remove_or_index_into_array
851
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
852
+							)
853
+						) {
854
+							$index_found_at = $index;
855
+							break;
856
+						}
857
+					}
858
+					if ($index_found_at) {
859
+						$index_in_cache = $index_found_at;
860
+					} else {
861
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
862
+						// if it wasn't in it to begin with. So we're done
863
+						return $object_to_remove_or_index_into_array;
864
+					}
865
+				}
866
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
867
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
868
+				foreach ($this->get_all_from_cache($relation_name) as $index => $potentially_obj_we_want) {
869
+					/** @noinspection TypeUnsafeComparisonInspection */
870
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
871
+						$index_in_cache = $index;
872
+					}
873
+				}
874
+			} else {
875
+				$index_in_cache = $object_to_remove_or_index_into_array;
876
+			}
877
+			// supposedly we've found it. But it could just be that the client code
878
+			// provided a bad index/object
879
+			if (isset($this->_model_relations[ $relation_name ][ $index_in_cache ])) {
880
+				$obj_removed = $this->_model_relations[ $relation_name ][ $index_in_cache ];
881
+				unset($this->_model_relations[ $relation_name ][ $index_in_cache ]);
882
+			} else {
883
+				// that thing was never cached anyways.
884
+				$obj_removed = null;
885
+			}
886
+		}
887
+		return $obj_removed;
888
+	}
889
+
890
+
891
+	/**
892
+	 * update_cache_after_object_save
893
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
894
+	 * obtained after being saved to the db
895
+	 *
896
+	 * @param string        $relation_name      - the type of object that is cached
897
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
898
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
899
+	 * @return boolean TRUE on success, FALSE on fail
900
+	 * @throws ReflectionException
901
+	 * @throws InvalidArgumentException
902
+	 * @throws InvalidInterfaceException
903
+	 * @throws InvalidDataTypeException
904
+	 * @throws EE_Error
905
+	 */
906
+	public function update_cache_after_object_save(
907
+		$relation_name,
908
+		EE_Base_Class $newly_saved_object,
909
+		$current_cache_id = ''
910
+	) {
911
+		// verify that incoming object is of the correct type
912
+		$obj_class = 'EE_' . $relation_name;
913
+		if ($newly_saved_object instanceof $obj_class) {
914
+			/* @type EE_Base_Class $newly_saved_object */
915
+			// now get the type of relation
916
+			$relationship_to_model = $this->get_model()->related_settings_for($relation_name);
917
+			// if this is a 1:1 relationship
918
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
919
+				// then just replace the cached object with the newly saved object
920
+				$this->_model_relations[ $relation_name ] = $newly_saved_object;
921
+				return true;
922
+				// or if it's some kind of sordid feral polyamorous relationship...
923
+			}
924
+			if (
925
+				is_array($this->_model_relations[ $relation_name ])
926
+				&& isset($this->_model_relations[ $relation_name ][ $current_cache_id ])
927
+			) {
928
+				// then remove the current cached item
929
+				unset($this->_model_relations[ $relation_name ][ $current_cache_id ]);
930
+				// and cache the newly saved object using it's new ID
931
+				$this->_model_relations[ $relation_name ][ $newly_saved_object->ID() ] = $newly_saved_object;
932
+				return true;
933
+			}
934
+		}
935
+		return false;
936
+	}
937
+
938
+
939
+	/**
940
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
941
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
942
+	 *
943
+	 * @param string $relation_name
944
+	 * @return EE_Base_Class
945
+	 */
946
+	public function get_one_from_cache($relation_name)
947
+	{
948
+		$cached_array_or_object = $this->_model_relations[ $relation_name ] ?? null;
949
+		if (is_array($cached_array_or_object)) {
950
+			return array_shift($cached_array_or_object);
951
+		}
952
+		return $cached_array_or_object;
953
+	}
954
+
955
+
956
+	/**
957
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
958
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
959
+	 *
960
+	 * @param string $relation_name
961
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
962
+	 * @throws InvalidArgumentException
963
+	 * @throws InvalidInterfaceException
964
+	 * @throws InvalidDataTypeException
965
+	 * @throws EE_Error
966
+	 * @throws ReflectionException
967
+	 */
968
+	public function get_all_from_cache($relation_name)
969
+	{
970
+		$objects = $this->_model_relations[ $relation_name ] ?? [];
971
+		// if the result is not an array, but exists, make it an array
972
+		$objects = is_array($objects)
973
+			? $objects
974
+			: [$objects];
975
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
976
+		// basically, if this model object was stored in the session, and these cached model objects
977
+		// already have IDs, let's make sure they're in their model's entity mapper
978
+		// otherwise we will have duplicates next time we call
979
+		// EE_Registry::instance()->load_model( $relation_name )->get_one_by_ID( $result->ID() );
980
+		$model = EE_Registry::instance()->load_model($relation_name);
981
+		foreach ($objects as $model_object) {
982
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
983
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
984
+				if ($model_object->ID()) {
985
+					$model->add_to_entity_map($model_object);
986
+				}
987
+			} else {
988
+				throw new EE_Error(
989
+					sprintf(
990
+						esc_html__(
991
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
992
+							'event_espresso'
993
+						),
994
+						$relation_name,
995
+						gettype($model_object)
996
+					)
997
+				);
998
+			}
999
+		}
1000
+		return $objects;
1001
+	}
1002
+
1003
+
1004
+	/**
1005
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1006
+	 * matching the given query conditions.
1007
+	 *
1008
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1009
+	 * @param int   $limit              How many objects to return.
1010
+	 * @param array $query_params       Any additional conditions on the query.
1011
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1012
+	 *                                  you can indicate just the columns you want returned
1013
+	 * @return array|EE_Base_Class[]
1014
+	 * @throws ReflectionException
1015
+	 * @throws InvalidArgumentException
1016
+	 * @throws InvalidInterfaceException
1017
+	 * @throws InvalidDataTypeException
1018
+	 * @throws EE_Error
1019
+	 */
1020
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = [], $columns_to_select = null)
1021
+	{
1022
+		$model         = $this->get_model();
1023
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1024
+			? $model->get_primary_key_field()->get_name()
1025
+			: $field_to_order_by;
1026
+		$current_value = ! empty($field)
1027
+			? $this->get($field)
1028
+			: null;
1029
+		if (empty($field) || empty($current_value)) {
1030
+			return [];
1031
+		}
1032
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1033
+	}
1034
+
1035
+
1036
+	/**
1037
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1038
+	 * matching the given query conditions.
1039
+	 *
1040
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1041
+	 * @param int   $limit              How many objects to return.
1042
+	 * @param array $query_params       Any additional conditions on the query.
1043
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1044
+	 *                                  you can indicate just the columns you want returned
1045
+	 * @return array|EE_Base_Class[]
1046
+	 * @throws ReflectionException
1047
+	 * @throws InvalidArgumentException
1048
+	 * @throws InvalidInterfaceException
1049
+	 * @throws InvalidDataTypeException
1050
+	 * @throws EE_Error
1051
+	 */
1052
+	public function previous_x(
1053
+		$field_to_order_by = null,
1054
+		$limit = 1,
1055
+		$query_params = [],
1056
+		$columns_to_select = null
1057
+	) {
1058
+		$model         = $this->get_model();
1059
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1060
+			? $model->get_primary_key_field()->get_name()
1061
+			: $field_to_order_by;
1062
+		$current_value = ! empty($field) ? $this->get($field) : null;
1063
+		if (empty($field) || empty($current_value)) {
1064
+			return [];
1065
+		}
1066
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1067
+	}
1068
+
1069
+
1070
+	/**
1071
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1072
+	 * matching the given query conditions.
1073
+	 *
1074
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1075
+	 * @param array $query_params       Any additional conditions on the query.
1076
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1077
+	 *                                  you can indicate just the columns you want returned
1078
+	 * @return array|EE_Base_Class
1079
+	 * @throws ReflectionException
1080
+	 * @throws InvalidArgumentException
1081
+	 * @throws InvalidInterfaceException
1082
+	 * @throws InvalidDataTypeException
1083
+	 * @throws EE_Error
1084
+	 */
1085
+	public function next($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1086
+	{
1087
+		$model         = $this->get_model();
1088
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1089
+			? $model->get_primary_key_field()->get_name()
1090
+			: $field_to_order_by;
1091
+		$current_value = ! empty($field) ? $this->get($field) : null;
1092
+		if (empty($field) || empty($current_value)) {
1093
+			return [];
1094
+		}
1095
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1096
+	}
1097
+
1098
+
1099
+	/**
1100
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1101
+	 * matching the given query conditions.
1102
+	 *
1103
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1104
+	 * @param array $query_params       Any additional conditions on the query.
1105
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1106
+	 *                                  you can indicate just the column you want returned
1107
+	 * @return array|EE_Base_Class
1108
+	 * @throws ReflectionException
1109
+	 * @throws InvalidArgumentException
1110
+	 * @throws InvalidInterfaceException
1111
+	 * @throws InvalidDataTypeException
1112
+	 * @throws EE_Error
1113
+	 */
1114
+	public function previous($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1115
+	{
1116
+		$model         = $this->get_model();
1117
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1118
+			? $model->get_primary_key_field()->get_name()
1119
+			: $field_to_order_by;
1120
+		$current_value = ! empty($field) ? $this->get($field) : null;
1121
+		if (empty($field) || empty($current_value)) {
1122
+			return [];
1123
+		}
1124
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * verifies that the specified field is of the correct type
1130
+	 *
1131
+	 * @param string $field_name
1132
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1133
+	 *                                (in cases where the same property may be used for different outputs
1134
+	 *                                - i.e. datetime, money etc.)
1135
+	 * @return mixed
1136
+	 * @throws ReflectionException
1137
+	 * @throws InvalidArgumentException
1138
+	 * @throws InvalidInterfaceException
1139
+	 * @throws InvalidDataTypeException
1140
+	 * @throws EE_Error
1141
+	 */
1142
+	public function get($field_name, $extra_cache_ref = null)
1143
+	{
1144
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1145
+	}
1146
+
1147
+
1148
+	/**
1149
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1150
+	 *
1151
+	 * @param string $field_name A valid fieldname
1152
+	 * @return mixed              Whatever the raw value stored on the property is.
1153
+	 * @throws ReflectionException
1154
+	 * @throws InvalidArgumentException
1155
+	 * @throws InvalidInterfaceException
1156
+	 * @throws InvalidDataTypeException
1157
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1158
+	 */
1159
+	public function get_raw($field_name)
1160
+	{
1161
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1162
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1163
+			? $this->_fields[ $field_name ]->format('U')
1164
+			: $this->_fields[ $field_name ];
1165
+	}
1166
+
1167
+
1168
+	/**
1169
+	 * This is used to return the internal DateTime object used for a field that is a
1170
+	 * EE_Datetime_Field.
1171
+	 *
1172
+	 * @param string $field_name               The field name retrieving the DateTime object.
1173
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1174
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1175
+	 *                                         EE_Datetime_Field and but the field value is null, then
1176
+	 *                                         just null is returned (because that indicates that likely
1177
+	 *                                         this field is nullable).
1178
+	 * @throws InvalidArgumentException
1179
+	 * @throws InvalidDataTypeException
1180
+	 * @throws InvalidInterfaceException
1181
+	 * @throws ReflectionException
1182
+	 */
1183
+	public function get_DateTime_object($field_name)
1184
+	{
1185
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1186
+		if (! $field_settings instanceof EE_Datetime_Field) {
1187
+			EE_Error::add_error(
1188
+				sprintf(
1189
+					esc_html__(
1190
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1191
+						'event_espresso'
1192
+					),
1193
+					$field_name
1194
+				),
1195
+				__FILE__,
1196
+				__FUNCTION__,
1197
+				__LINE__
1198
+			);
1199
+			return false;
1200
+		}
1201
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1202
+			? clone $this->_fields[ $field_name ]
1203
+			: null;
1204
+	}
1205
+
1206
+
1207
+	/**
1208
+	 * To be used in template to immediately echo out the value, and format it for output.
1209
+	 * Eg, should call stripslashes and whatnot before echoing
1210
+	 *
1211
+	 * @param string $field_name      the name of the field as it appears in the DB
1212
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1213
+	 *                                (in cases where the same property may be used for different outputs
1214
+	 *                                - i.e. datetime, money etc.)
1215
+	 * @return void
1216
+	 * @throws ReflectionException
1217
+	 * @throws InvalidArgumentException
1218
+	 * @throws InvalidInterfaceException
1219
+	 * @throws InvalidDataTypeException
1220
+	 * @throws EE_Error
1221
+	 */
1222
+	public function e($field_name, $extra_cache_ref = null)
1223
+	{
1224
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1225
+	}
1226
+
1227
+
1228
+	/**
1229
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1230
+	 * can be easily used as the value of form input.
1231
+	 *
1232
+	 * @param string $field_name
1233
+	 * @return void
1234
+	 * @throws ReflectionException
1235
+	 * @throws InvalidArgumentException
1236
+	 * @throws InvalidInterfaceException
1237
+	 * @throws InvalidDataTypeException
1238
+	 * @throws EE_Error
1239
+	 */
1240
+	public function f($field_name)
1241
+	{
1242
+		$this->e($field_name, 'form_input');
1243
+	}
1244
+
1245
+
1246
+	/**
1247
+	 * Same as `f()` but just returns the value instead of echoing it
1248
+	 *
1249
+	 * @param string $field_name
1250
+	 * @return string
1251
+	 * @throws ReflectionException
1252
+	 * @throws InvalidArgumentException
1253
+	 * @throws InvalidInterfaceException
1254
+	 * @throws InvalidDataTypeException
1255
+	 * @throws EE_Error
1256
+	 */
1257
+	public function get_f($field_name)
1258
+	{
1259
+		return (string) $this->get_pretty($field_name, 'form_input');
1260
+	}
1261
+
1262
+
1263
+	/**
1264
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1265
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1266
+	 * to see what options are available.
1267
+	 *
1268
+	 * @param string $field_name
1269
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1270
+	 *                                (in cases where the same property may be used for different outputs
1271
+	 *                                - i.e. datetime, money etc.)
1272
+	 * @return mixed
1273
+	 * @throws ReflectionException
1274
+	 * @throws InvalidArgumentException
1275
+	 * @throws InvalidInterfaceException
1276
+	 * @throws InvalidDataTypeException
1277
+	 * @throws EE_Error
1278
+	 */
1279
+	public function get_pretty($field_name, $extra_cache_ref = null)
1280
+	{
1281
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1282
+	}
1283
+
1284
+
1285
+	/**
1286
+	 * This simply returns the datetime for the given field name
1287
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1288
+	 * (and the equivalent e_date, e_time, e_datetime).
1289
+	 *
1290
+	 * @access   protected
1291
+	 * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1292
+	 * @param string|null $date_format  valid datetime format used for date
1293
+	 *                                  (if '' then we just use the default on the field,
1294
+	 *                                  if NULL we use the last-used format)
1295
+	 * @param string|null $time_format  Same as above except this is for time format
1296
+	 * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1297
+	 * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1298
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1299
+	 *                                  if field is not a valid dtt field, or void if echoing
1300
+	 * @throws EE_Error
1301
+	 * @throws ReflectionException
1302
+	 */
1303
+	protected function _get_datetime(
1304
+		string $field_name,
1305
+		?string $date_format = '',
1306
+		?string $time_format = '',
1307
+		?string $date_or_time = '',
1308
+		?bool $echo = false
1309
+	) {
1310
+		// clear cached property
1311
+		$this->_clear_cached_property($field_name);
1312
+		// reset format properties because they are used in get()
1313
+		$this->_dt_frmt = $date_format ?: $this->_dt_frmt;
1314
+		$this->_tm_frmt = $time_format ?: $this->_tm_frmt;
1315
+		if ($echo) {
1316
+			$this->e($field_name, $date_or_time);
1317
+			return '';
1318
+		}
1319
+		return $this->get($field_name, $date_or_time);
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1325
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1326
+	 * other echoes the pretty value for dtt)
1327
+	 *
1328
+	 * @param string $field_name name of model object datetime field holding the value
1329
+	 * @param string $format     format for the date returned (if NULL we use default in dt_frmt property)
1330
+	 * @return string            datetime value formatted
1331
+	 * @throws ReflectionException
1332
+	 * @throws InvalidArgumentException
1333
+	 * @throws InvalidInterfaceException
1334
+	 * @throws InvalidDataTypeException
1335
+	 * @throws EE_Error
1336
+	 */
1337
+	public function get_date($field_name, $format = '')
1338
+	{
1339
+		return $this->_get_datetime($field_name, $format, null, 'D');
1340
+	}
1341
+
1342
+
1343
+	/**
1344
+	 * @param        $field_name
1345
+	 * @param string $format
1346
+	 * @throws ReflectionException
1347
+	 * @throws InvalidArgumentException
1348
+	 * @throws InvalidInterfaceException
1349
+	 * @throws InvalidDataTypeException
1350
+	 * @throws EE_Error
1351
+	 */
1352
+	public function e_date($field_name, $format = '')
1353
+	{
1354
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1355
+	}
1356
+
1357
+
1358
+	/**
1359
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1360
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1361
+	 * other echoes the pretty value for dtt)
1362
+	 *
1363
+	 * @param string $field_name name of model object datetime field holding the value
1364
+	 * @param string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1365
+	 * @return string             datetime value formatted
1366
+	 * @throws ReflectionException
1367
+	 * @throws InvalidArgumentException
1368
+	 * @throws InvalidInterfaceException
1369
+	 * @throws InvalidDataTypeException
1370
+	 * @throws EE_Error
1371
+	 */
1372
+	public function get_time($field_name, $format = '')
1373
+	{
1374
+		return $this->_get_datetime($field_name, null, $format, 'T');
1375
+	}
1376
+
1377
+
1378
+	/**
1379
+	 * @param        $field_name
1380
+	 * @param string $format
1381
+	 * @throws ReflectionException
1382
+	 * @throws InvalidArgumentException
1383
+	 * @throws InvalidInterfaceException
1384
+	 * @throws InvalidDataTypeException
1385
+	 * @throws EE_Error
1386
+	 */
1387
+	public function e_time($field_name, $format = '')
1388
+	{
1389
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1390
+	}
1391
+
1392
+
1393
+	/**
1394
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1395
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1396
+	 * other echoes the pretty value for dtt)
1397
+	 *
1398
+	 * @param string $field_name  name of model object datetime field holding the value
1399
+	 * @param string $date_format format for the date returned (if NULL we use default in dt_frmt property)
1400
+	 * @param string $time_format format for the time returned (if NULL we use default in tm_frmt property)
1401
+	 * @return string             datetime value formatted
1402
+	 * @throws ReflectionException
1403
+	 * @throws InvalidArgumentException
1404
+	 * @throws InvalidInterfaceException
1405
+	 * @throws InvalidDataTypeException
1406
+	 * @throws EE_Error
1407
+	 */
1408
+	public function get_datetime($field_name, $date_format = '', $time_format = '')
1409
+	{
1410
+		return $this->_get_datetime($field_name, $date_format, $time_format);
1411
+	}
1412
+
1413
+
1414
+	/**
1415
+	 * @param string $field_name
1416
+	 * @param string $date_format
1417
+	 * @param string $time_format
1418
+	 * @throws ReflectionException
1419
+	 * @throws InvalidArgumentException
1420
+	 * @throws InvalidInterfaceException
1421
+	 * @throws InvalidDataTypeException
1422
+	 * @throws EE_Error
1423
+	 */
1424
+	public function e_datetime($field_name, $date_format = '', $time_format = '')
1425
+	{
1426
+		$this->_get_datetime($field_name, $date_format, $time_format, null, true);
1427
+	}
1428
+
1429
+
1430
+	/**
1431
+	 * Get the i8ln value for a date using the WordPress @param string $field_name The EE_Datetime_Field reference for
1432
+	 *                           the date being retrieved.
1433
+	 *
1434
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1435
+	 *                           on the object will be used.
1436
+	 * @return string Date and time string in set locale or false if no field exists for the given
1437
+	 * @throws ReflectionException
1438
+	 * @throws InvalidArgumentException
1439
+	 * @throws InvalidInterfaceException
1440
+	 * @throws InvalidDataTypeException
1441
+	 * @throws EE_Error
1442
+	 *                           field name.
1443
+	 * @see date_i18n function.
1444
+	 */
1445
+	public function get_i18n_datetime(string $field_name, string $format = ''): string
1446
+	{
1447
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1448
+		return date_i18n(
1449
+			$format,
1450
+			EEH_DTT_Helper::get_timestamp_with_offset(
1451
+				$this->get_raw($field_name),
1452
+				$this->_timezone
1453
+			)
1454
+		);
1455
+	}
1456
+
1457
+
1458
+	/**
1459
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1460
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1461
+	 * thrown.
1462
+	 *
1463
+	 * @param string $field_name The field name being checked
1464
+	 * @return EE_Datetime_Field
1465
+	 * @throws InvalidArgumentException
1466
+	 * @throws InvalidInterfaceException
1467
+	 * @throws InvalidDataTypeException
1468
+	 * @throws EE_Error
1469
+	 * @throws ReflectionException
1470
+	 */
1471
+	protected function _get_dtt_field_settings($field_name)
1472
+	{
1473
+		$field = $this->get_model()->field_settings_for($field_name);
1474
+		// check if field is dtt
1475
+		if ($field instanceof EE_Datetime_Field) {
1476
+			return $field;
1477
+		}
1478
+		throw new EE_Error(
1479
+			sprintf(
1480
+				esc_html__(
1481
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1482
+					'event_espresso'
1483
+				),
1484
+				$field_name,
1485
+				self::_get_model_classname(get_class($this))
1486
+			)
1487
+		);
1488
+	}
1489
+
1490
+
1491
+
1492
+
1493
+	/**
1494
+	 * NOTE ABOUT BELOW:
1495
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1496
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1497
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1498
+	 * method and make sure you send the entire datetime value for setting.
1499
+	 */
1500
+	/**
1501
+	 * sets the time on a datetime property
1502
+	 *
1503
+	 * @access protected
1504
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1505
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1506
+	 * @throws ReflectionException
1507
+	 * @throws InvalidArgumentException
1508
+	 * @throws InvalidInterfaceException
1509
+	 * @throws InvalidDataTypeException
1510
+	 * @throws EE_Error
1511
+	 */
1512
+	protected function _set_time_for($time, $fieldname)
1513
+	{
1514
+		$this->_set_date_time('T', $time, $fieldname);
1515
+	}
1516
+
1517
+
1518
+	/**
1519
+	 * sets the date on a datetime property
1520
+	 *
1521
+	 * @access protected
1522
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1523
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1524
+	 * @throws ReflectionException
1525
+	 * @throws InvalidArgumentException
1526
+	 * @throws InvalidInterfaceException
1527
+	 * @throws InvalidDataTypeException
1528
+	 * @throws EE_Error
1529
+	 */
1530
+	protected function _set_date_for($date, $fieldname)
1531
+	{
1532
+		$this->_set_date_time('D', $date, $fieldname);
1533
+	}
1534
+
1535
+
1536
+	/**
1537
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1538
+	 * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1539
+	 *
1540
+	 * @access protected
1541
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1542
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1543
+	 * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1544
+	 *                                        EE_Datetime_Field property)
1545
+	 * @throws ReflectionException
1546
+	 * @throws InvalidArgumentException
1547
+	 * @throws InvalidInterfaceException
1548
+	 * @throws InvalidDataTypeException
1549
+	 * @throws EE_Error
1550
+	 */
1551
+	protected function _set_date_time(string $what, $datetime_value, string $field_name)
1552
+	{
1553
+		$field = $this->_get_dtt_field_settings($field_name);
1554
+		$field->set_timezone($this->_timezone);
1555
+		$field->set_date_format($this->_dt_frmt);
1556
+		$field->set_time_format($this->_tm_frmt);
1557
+		switch ($what) {
1558
+			case 'T':
1559
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1560
+					$datetime_value,
1561
+					$this->_fields[ $field_name ]
1562
+				);
1563
+				$this->_has_changes           = true;
1564
+				break;
1565
+			case 'D':
1566
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1567
+					$datetime_value,
1568
+					$this->_fields[ $field_name ]
1569
+				);
1570
+				$this->_has_changes           = true;
1571
+				break;
1572
+			case 'B':
1573
+				$this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1574
+				$this->_has_changes           = true;
1575
+				break;
1576
+		}
1577
+		$this->_clear_cached_property($field_name);
1578
+	}
1579
+
1580
+
1581
+	/**
1582
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1583
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1584
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1585
+	 * that could lead to some unexpected results!
1586
+	 *
1587
+	 * @access public
1588
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1589
+	 *                                         value being returned.
1590
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1591
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1592
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1593
+	 * @param string $append                   You can include something to append on the timestamp
1594
+	 * @return string timestamp
1595
+	 * @throws ReflectionException
1596
+	 * @throws InvalidArgumentException
1597
+	 * @throws InvalidInterfaceException
1598
+	 * @throws InvalidDataTypeException
1599
+	 * @throws EE_Error
1600
+	 */
1601
+	public function display_in_my_timezone(
1602
+		$field_name,
1603
+		$callback = 'get_datetime',
1604
+		$args = null,
1605
+		$prepend = '',
1606
+		$append = ''
1607
+	) {
1608
+		$timezone = EEH_DTT_Helper::get_timezone();
1609
+		if ($timezone === $this->_timezone) {
1610
+			return '';
1611
+		}
1612
+		$original_timezone = $this->_timezone;
1613
+		$this->set_timezone($timezone);
1614
+		$fn   = (array) $field_name;
1615
+		$args = array_merge($fn, (array) $args);
1616
+		if (! method_exists($this, $callback)) {
1617
+			throw new EE_Error(
1618
+				sprintf(
1619
+					esc_html__(
1620
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1621
+						'event_espresso'
1622
+					),
1623
+					$callback
1624
+				)
1625
+			);
1626
+		}
1627
+		$args   = (array) $args;
1628
+		$return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
1629
+		$this->set_timezone($original_timezone);
1630
+		return $return;
1631
+	}
1632
+
1633
+
1634
+	/**
1635
+	 * Deletes this model object.
1636
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1637
+	 * override
1638
+	 * `EE_Base_Class::_delete` NOT this class.
1639
+	 *
1640
+	 * @return boolean | int
1641
+	 * @throws ReflectionException
1642
+	 * @throws InvalidArgumentException
1643
+	 * @throws InvalidInterfaceException
1644
+	 * @throws InvalidDataTypeException
1645
+	 * @throws EE_Error
1646
+	 */
1647
+	public function delete()
1648
+	{
1649
+		/**
1650
+		 * Called just before the `EE_Base_Class::_delete` method call.
1651
+		 * Note:
1652
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1653
+		 * should be aware that `_delete` may not always result in a permanent delete.
1654
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1655
+		 * soft deletes (trash) the object and does not permanently delete it.
1656
+		 *
1657
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1658
+		 */
1659
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1660
+		$result = $this->_delete();
1661
+		/**
1662
+		 * Called just after the `EE_Base_Class::_delete` method call.
1663
+		 * Note:
1664
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1665
+		 * should be aware that `_delete` may not always result in a permanent delete.
1666
+		 * For example `EE_Soft_Base_Class::_delete`
1667
+		 * soft deletes (trash) the object and does not permanently delete it.
1668
+		 *
1669
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1670
+		 * @param boolean       $result
1671
+		 */
1672
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1673
+		return $result;
1674
+	}
1675
+
1676
+
1677
+	/**
1678
+	 * Calls the specific delete method for the instantiated class.
1679
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1680
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1681
+	 * `EE_Base_Class::delete`
1682
+	 *
1683
+	 * @return bool|int
1684
+	 * @throws ReflectionException
1685
+	 * @throws InvalidArgumentException
1686
+	 * @throws InvalidInterfaceException
1687
+	 * @throws InvalidDataTypeException
1688
+	 * @throws EE_Error
1689
+	 */
1690
+	protected function _delete()
1691
+	{
1692
+		return $this->delete_permanently();
1693
+	}
1694
+
1695
+
1696
+	/**
1697
+	 * Deletes this model object permanently from db
1698
+	 * (but keep in mind related models may block the delete and return an error)
1699
+	 *
1700
+	 * @return bool | int
1701
+	 * @throws ReflectionException
1702
+	 * @throws InvalidArgumentException
1703
+	 * @throws InvalidInterfaceException
1704
+	 * @throws InvalidDataTypeException
1705
+	 * @throws EE_Error
1706
+	 */
1707
+	public function delete_permanently()
1708
+	{
1709
+		/**
1710
+		 * Called just before HARD deleting a model object
1711
+		 *
1712
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1713
+		 */
1714
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1715
+		$model  = $this->get_model();
1716
+		$result = $model->delete_permanently_by_ID($this->ID());
1717
+		$this->refresh_cache_of_related_objects();
1718
+		/**
1719
+		 * Called just after HARD deleting a model object
1720
+		 *
1721
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1722
+		 * @param boolean       $result
1723
+		 */
1724
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1725
+		return $result;
1726
+	}
1727
+
1728
+
1729
+	/**
1730
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1731
+	 * related model objects
1732
+	 *
1733
+	 * @throws ReflectionException
1734
+	 * @throws InvalidArgumentException
1735
+	 * @throws InvalidInterfaceException
1736
+	 * @throws InvalidDataTypeException
1737
+	 * @throws EE_Error
1738
+	 */
1739
+	public function refresh_cache_of_related_objects()
1740
+	{
1741
+		$model = $this->get_model();
1742
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1743
+			if (! empty($this->_model_relations[ $relation_name ])) {
1744
+				$related_objects = $this->_model_relations[ $relation_name ];
1745
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1746
+					// this relation only stores a single model object, not an array
1747
+					// but let's make it consistent
1748
+					$related_objects = [$related_objects];
1749
+				}
1750
+				foreach ($related_objects as $related_object) {
1751
+					// only refresh their cache if they're in memory
1752
+					if ($related_object instanceof EE_Base_Class) {
1753
+						$related_object->clear_cache(
1754
+							$model->get_this_model_name(),
1755
+							$this
1756
+						);
1757
+					}
1758
+				}
1759
+			}
1760
+		}
1761
+	}
1762
+
1763
+
1764
+	/**
1765
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1766
+	 * object just before saving.
1767
+	 *
1768
+	 * @access public
1769
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1770
+	 *                                 if provided during the save() method (often client code will change the fields'
1771
+	 *                                 values before calling save)
1772
+	 * @return bool|int|string         1 on a successful update
1773
+	 *                                 the ID of the new entry on insert
1774
+	 *                                 0 on failure or if the model object isn't allowed to persist
1775
+	 *                                 (as determined by EE_Base_Class::allow_persist())
1776
+	 * @throws InvalidInterfaceException
1777
+	 * @throws InvalidDataTypeException
1778
+	 * @throws EE_Error
1779
+	 * @throws InvalidArgumentException
1780
+	 * @throws ReflectionException
1781
+	 */
1782
+	public function save($set_cols_n_values = [])
1783
+	{
1784
+		$model = $this->get_model();
1785
+		/**
1786
+		 * Filters the fields we're about to save on the model object
1787
+		 *
1788
+		 * @param array         $set_cols_n_values
1789
+		 * @param EE_Base_Class $model_object
1790
+		 */
1791
+		$set_cols_n_values = (array) apply_filters(
1792
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1793
+			$set_cols_n_values,
1794
+			$this
1795
+		);
1796
+		// set attributes as provided in $set_cols_n_values
1797
+		foreach ($set_cols_n_values as $column => $value) {
1798
+			$this->set($column, $value);
1799
+		}
1800
+		// no changes ? then don't do anything
1801
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1802
+			return 0;
1803
+		}
1804
+		/**
1805
+		 * Saving a model object.
1806
+		 * Before we perform a save, this action is fired.
1807
+		 *
1808
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1809
+		 */
1810
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1811
+		if (! $this->allow_persist()) {
1812
+			return 0;
1813
+		}
1814
+		// now get current attribute values
1815
+		$save_cols_n_values = $this->_fields;
1816
+		// if the object already has an ID, update it. Otherwise, insert it
1817
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1818
+		// They have been
1819
+		$old_assumption_concerning_value_preparation = $model
1820
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1821
+		$model->assume_values_already_prepared_by_model_object(true);
1822
+		// does this model have an autoincrement PK?
1823
+		if ($model->has_primary_key_field()) {
1824
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1825
+				// ok check if it's set, if so: update; if not, insert
1826
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1827
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1828
+				} else {
1829
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1830
+					$results = $model->insert($save_cols_n_values);
1831
+					if ($results) {
1832
+						// if successful, set the primary key
1833
+						// but don't use the normal SET method, because it will check if
1834
+						// an item with the same ID exists in the mapper & db, then
1835
+						// will find it in the db (because we just added it) and THAT object
1836
+						// will get added to the mapper before we can add this one!
1837
+						// but if we just avoid using the SET method, all that headache can be avoided
1838
+						$pk_field_name                   = $model->primary_key_name();
1839
+						$this->_fields[ $pk_field_name ] = $results;
1840
+						$this->_clear_cached_property($pk_field_name);
1841
+						$model->add_to_entity_map($this);
1842
+						$this->_update_cached_related_model_objs_fks();
1843
+					}
1844
+				}
1845
+			} else {// PK is NOT auto-increment
1846
+				// so check if one like it already exists in the db
1847
+				if ($model->exists_by_ID($this->ID())) {
1848
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1849
+						throw new EE_Error(
1850
+							sprintf(
1851
+								esc_html__(
1852
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1853
+									'event_espresso'
1854
+								),
1855
+								get_class($this),
1856
+								get_class($model) . '::instance()->add_to_entity_map()',
1857
+								get_class($model) . '::instance()->get_one_by_ID()',
1858
+								'<br />'
1859
+							)
1860
+						);
1861
+					}
1862
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1863
+				} else {
1864
+					$results = $model->insert($save_cols_n_values);
1865
+					$this->_update_cached_related_model_objs_fks();
1866
+				}
1867
+			}
1868
+		} else {// there is NO primary key
1869
+			$already_in_db = false;
1870
+			foreach ($model->unique_indexes() as $index) {
1871
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1872
+				if ($model->exists([$uniqueness_where_params])) {
1873
+					$already_in_db = true;
1874
+				}
1875
+			}
1876
+			if ($already_in_db) {
1877
+				$combined_pk_fields_n_values = array_intersect_key(
1878
+					$save_cols_n_values,
1879
+					$model->get_combined_primary_key_fields()
1880
+				);
1881
+				$results                     = $model->update(
1882
+					$save_cols_n_values,
1883
+					$combined_pk_fields_n_values
1884
+				);
1885
+			} else {
1886
+				$results = $model->insert($save_cols_n_values);
1887
+			}
1888
+		}
1889
+		// restore the old assumption about values being prepared by the model object
1890
+		$model->assume_values_already_prepared_by_model_object(
1891
+			$old_assumption_concerning_value_preparation
1892
+		);
1893
+		/**
1894
+		 * After saving the model object this action is called
1895
+		 *
1896
+		 * @param EE_Base_Class $model_object which was just saved
1897
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1898
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1899
+		 */
1900
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1901
+		$this->_has_changes = false;
1902
+		return $results;
1903
+	}
1904
+
1905
+
1906
+	/**
1907
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1908
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1909
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1910
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1911
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1912
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1913
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1914
+	 *
1915
+	 * @return void
1916
+	 * @throws ReflectionException
1917
+	 * @throws InvalidArgumentException
1918
+	 * @throws InvalidInterfaceException
1919
+	 * @throws InvalidDataTypeException
1920
+	 * @throws EE_Error
1921
+	 */
1922
+	protected function _update_cached_related_model_objs_fks()
1923
+	{
1924
+		$model = $this->get_model();
1925
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1926
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1927
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1928
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1929
+						$model->get_this_model_name()
1930
+					);
1931
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1932
+					if ($related_model_obj_in_cache->ID()) {
1933
+						$related_model_obj_in_cache->save();
1934
+					}
1935
+				}
1936
+			}
1937
+		}
1938
+	}
1939
+
1940
+
1941
+	/**
1942
+	 * Saves this model object and its NEW cached relations to the database.
1943
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1944
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1945
+	 * because otherwise, there's a potential for infinite looping of saving
1946
+	 * Saves the cached related model objects, and ensures the relation between them
1947
+	 * and this object and properly setup
1948
+	 *
1949
+	 * @return int ID of new model object on save; 0 on failure+
1950
+	 * @throws ReflectionException
1951
+	 * @throws InvalidArgumentException
1952
+	 * @throws InvalidInterfaceException
1953
+	 * @throws InvalidDataTypeException
1954
+	 * @throws EE_Error
1955
+	 */
1956
+	public function save_new_cached_related_model_objs()
1957
+	{
1958
+		// make sure this has been saved
1959
+		if (! $this->ID()) {
1960
+			$id = $this->save();
1961
+		} else {
1962
+			$id = $this->ID();
1963
+		}
1964
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1965
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relationObj) {
1966
+			if ($this->_model_relations[ $relation_name ]) {
1967
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1968
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1969
+				/* @var $related_model_obj EE_Base_Class */
1970
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1971
+					// add a relation to that relation type (which saves the appropriate thing in the process)
1972
+					// but ONLY if it DOES NOT exist in the DB
1973
+					$related_model_obj = $this->_model_relations[ $relation_name ];
1974
+					// if( ! $related_model_obj->ID()){
1975
+					$this->_add_relation_to($related_model_obj, $relation_name);
1976
+					$related_model_obj->save_new_cached_related_model_objs();
1977
+					// }
1978
+				} else {
1979
+					foreach ($this->_model_relations[ $relation_name ] as $related_model_obj) {
1980
+						// add a relation to that relation type (which saves the appropriate thing in the process)
1981
+						// but ONLY if it DOES NOT exist in the DB
1982
+						// if( ! $related_model_obj->ID()){
1983
+						$this->_add_relation_to($related_model_obj, $relation_name);
1984
+						$related_model_obj->save_new_cached_related_model_objs();
1985
+						// }
1986
+					}
1987
+				}
1988
+			}
1989
+		}
1990
+		return $id;
1991
+	}
1992
+
1993
+
1994
+	/**
1995
+	 * for getting a model while instantiated.
1996
+	 *
1997
+	 * @return EEM_Base | EEM_CPT_Base
1998
+	 * @throws ReflectionException
1999
+	 * @throws InvalidArgumentException
2000
+	 * @throws InvalidInterfaceException
2001
+	 * @throws InvalidDataTypeException
2002
+	 * @throws EE_Error
2003
+	 */
2004
+	public function get_model()
2005
+	{
2006
+		if (! $this->_model) {
2007
+			$modelName    = self::_get_model_classname(get_class($this));
2008
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2009
+		} else {
2010
+			$this->_model->set_timezone($this->_timezone);
2011
+		}
2012
+		return $this->_model;
2013
+	}
2014
+
2015
+
2016
+	/**
2017
+	 * @param $props_n_values
2018
+	 * @param $classname
2019
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2020
+	 * @throws ReflectionException
2021
+	 * @throws InvalidArgumentException
2022
+	 * @throws InvalidInterfaceException
2023
+	 * @throws InvalidDataTypeException
2024
+	 * @throws EE_Error
2025
+	 */
2026
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2027
+	{
2028
+		// TODO: will not work for Term_Relationships because they have no PK!
2029
+		$primary_id_ref = self::_get_primary_key_name($classname);
2030
+		if (
2031
+			array_key_exists($primary_id_ref, $props_n_values)
2032
+			&& ! empty($props_n_values[ $primary_id_ref ])
2033
+		) {
2034
+			$id = $props_n_values[ $primary_id_ref ];
2035
+			return self::_get_model($classname)->get_from_entity_map($id);
2036
+		}
2037
+		return false;
2038
+	}
2039
+
2040
+
2041
+	/**
2042
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2043
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2044
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2045
+	 * we return false.
2046
+	 *
2047
+	 * @param array  $props_n_values    incoming array of properties and their values
2048
+	 * @param string $classname         the classname of the child class
2049
+	 * @param null   $timezone
2050
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the
2051
+	 *                                  date_format and the second value is the time format
2052
+	 * @return mixed (EE_Base_Class|bool)
2053
+	 * @throws InvalidArgumentException
2054
+	 * @throws InvalidInterfaceException
2055
+	 * @throws InvalidDataTypeException
2056
+	 * @throws EE_Error
2057
+	 * @throws ReflectionException
2058
+	 */
2059
+	protected static function _check_for_object($props_n_values, $classname, $timezone = '', $date_formats = [])
2060
+	{
2061
+		$existing = null;
2062
+		$model    = self::_get_model($classname, $timezone);
2063
+		if ($model->has_primary_key_field()) {
2064
+			$primary_id_ref = self::_get_primary_key_name($classname);
2065
+			if (
2066
+				array_key_exists($primary_id_ref, $props_n_values)
2067
+				&& ! empty($props_n_values[ $primary_id_ref ])
2068
+			) {
2069
+				$existing = $model->get_one_by_ID(
2070
+					$props_n_values[ $primary_id_ref ]
2071
+				);
2072
+			}
2073
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2074
+			// no primary key on this model, but there's still a matching item in the DB
2075
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2076
+				self::_get_model($classname, $timezone)
2077
+					->get_index_primary_key_string($props_n_values)
2078
+			);
2079
+		}
2080
+		if ($existing) {
2081
+			// set date formats if present before setting values
2082
+			if (! empty($date_formats) && is_array($date_formats)) {
2083
+				$existing->set_date_format($date_formats[0]);
2084
+				$existing->set_time_format($date_formats[1]);
2085
+			} else {
2086
+				// set default formats for date and time
2087
+				$existing->set_date_format(get_option('date_format'));
2088
+				$existing->set_time_format(get_option('time_format'));
2089
+			}
2090
+			foreach ($props_n_values as $property => $field_value) {
2091
+				$existing->set($property, $field_value);
2092
+			}
2093
+			return $existing;
2094
+		}
2095
+		return false;
2096
+	}
2097
+
2098
+
2099
+	/**
2100
+	 * Gets the EEM_*_Model for this class
2101
+	 *
2102
+	 * @access public now, as this is more convenient
2103
+	 * @param      $classname
2104
+	 * @param null $timezone
2105
+	 * @return EEM_Base
2106
+	 * @throws InvalidArgumentException
2107
+	 * @throws InvalidInterfaceException
2108
+	 * @throws InvalidDataTypeException
2109
+	 * @throws EE_Error
2110
+	 * @throws ReflectionException
2111
+	 */
2112
+	protected static function _get_model($classname, $timezone = '')
2113
+	{
2114
+		// find model for this class
2115
+		if (! $classname) {
2116
+			throw new EE_Error(
2117
+				sprintf(
2118
+					esc_html__(
2119
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2120
+						'event_espresso'
2121
+					),
2122
+					$classname
2123
+				)
2124
+			);
2125
+		}
2126
+		$modelName = self::_get_model_classname($classname);
2127
+		return self::_get_model_instance_with_name($modelName, $timezone);
2128
+	}
2129
+
2130
+
2131
+	/**
2132
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2133
+	 *
2134
+	 * @param string $model_classname
2135
+	 * @param null   $timezone
2136
+	 * @return EEM_Base
2137
+	 * @throws ReflectionException
2138
+	 * @throws InvalidArgumentException
2139
+	 * @throws InvalidInterfaceException
2140
+	 * @throws InvalidDataTypeException
2141
+	 * @throws EE_Error
2142
+	 */
2143
+	protected static function _get_model_instance_with_name($model_classname, $timezone = '')
2144
+	{
2145
+		$model_classname = str_replace('EEM_', '', $model_classname);
2146
+		$model           = EE_Registry::instance()->load_model($model_classname);
2147
+		$model->set_timezone($timezone);
2148
+		return $model;
2149
+	}
2150
+
2151
+
2152
+	/**
2153
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2154
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2155
+	 *
2156
+	 * @param string|null $model_name
2157
+	 * @return string like EEM_Attendee
2158
+	 */
2159
+	private static function _get_model_classname($model_name = '')
2160
+	{
2161
+		return strpos((string) $model_name, 'EE_') === 0
2162
+			? str_replace('EE_', 'EEM_', $model_name)
2163
+			: 'EEM_' . $model_name;
2164
+	}
2165
+
2166
+
2167
+	/**
2168
+	 * returns the name of the primary key attribute
2169
+	 *
2170
+	 * @param null $classname
2171
+	 * @return string
2172
+	 * @throws InvalidArgumentException
2173
+	 * @throws InvalidInterfaceException
2174
+	 * @throws InvalidDataTypeException
2175
+	 * @throws EE_Error
2176
+	 * @throws ReflectionException
2177
+	 */
2178
+	protected static function _get_primary_key_name($classname = null)
2179
+	{
2180
+		if (! $classname) {
2181
+			throw new EE_Error(
2182
+				sprintf(
2183
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2184
+					$classname
2185
+				)
2186
+			);
2187
+		}
2188
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2189
+	}
2190
+
2191
+
2192
+	/**
2193
+	 * Gets the value of the primary key.
2194
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2195
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2196
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2197
+	 *
2198
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2199
+	 * @throws ReflectionException
2200
+	 * @throws InvalidArgumentException
2201
+	 * @throws InvalidInterfaceException
2202
+	 * @throws InvalidDataTypeException
2203
+	 * @throws EE_Error
2204
+	 */
2205
+	public function ID()
2206
+	{
2207
+		$model = $this->get_model();
2208
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2209
+		if ($model->has_primary_key_field()) {
2210
+			return $this->_fields[ $model->primary_key_name() ];
2211
+		}
2212
+		return $model->get_index_primary_key_string($this->_fields);
2213
+	}
2214
+
2215
+
2216
+	/**
2217
+	 * @param EE_Base_Class|int|string $otherModelObjectOrID
2218
+	 * @param string                   $relation_name
2219
+	 * @return bool
2220
+	 * @throws EE_Error
2221
+	 * @throws ReflectionException
2222
+	 * @since   5.0.0.p
2223
+	 */
2224
+	public function hasRelation($otherModelObjectOrID, string $relation_name): bool
2225
+	{
2226
+		$other_model = self::_get_model_instance_with_name(
2227
+			self::_get_model_classname($relation_name),
2228
+			$this->_timezone
2229
+		);
2230
+		$primary_key = $other_model->primary_key_name();
2231
+		/** @var EE_Base_Class $otherModelObject */
2232
+		$otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relation_name);
2233
+		return $this->count_related($relation_name, [[$primary_key => $otherModelObject->ID()]]) > 0;
2234
+	}
2235
+
2236
+
2237
+	/**
2238
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2239
+	 * model is related to a group of events, the $relation_name should be 'Event', and should be a key in the EE
2240
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2241
+	 *
2242
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2243
+	 * @param string $relation_name                    eg 'Events','Question',etc.
2244
+	 *                                                 an attendee to a group, you also want to specify which role they
2245
+	 *                                                 will have in that group. So you would use this parameter to
2246
+	 *                                                 specify array('role-column-name'=>'role-id')
2247
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2248
+	 *                                                 allow you to further constrict the relation to being added.
2249
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2250
+	 *                                                 column on the JOIN table and currently only the HABTM models
2251
+	 *                                                 accept these additional conditions.  Also remember that if an
2252
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2253
+	 *                                                 NEW row is created in the join table.
2254
+	 * @param null   $cache_id
2255
+	 * @return EE_Base_Class the object the relation was added to
2256
+	 * @throws ReflectionException
2257
+	 * @throws InvalidArgumentException
2258
+	 * @throws InvalidInterfaceException
2259
+	 * @throws InvalidDataTypeException
2260
+	 * @throws EE_Error
2261
+	 */
2262
+	public function _add_relation_to(
2263
+		$otherObjectModelObjectOrID,
2264
+		$relation_name,
2265
+		$extra_join_model_fields_n_values = [],
2266
+		$cache_id = null
2267
+	) {
2268
+		$model = $this->get_model();
2269
+		// if this thing exists in the DB, save the relation to the DB
2270
+		if ($this->ID()) {
2271
+			$otherObject = $model->add_relationship_to(
2272
+				$this,
2273
+				$otherObjectModelObjectOrID,
2274
+				$relation_name,
2275
+				$extra_join_model_fields_n_values
2276
+			);
2277
+			// clear cache so future get_many_related and get_first_related() return new results.
2278
+			$this->clear_cache($relation_name, $otherObject, true);
2279
+			if ($otherObject instanceof EE_Base_Class) {
2280
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2281
+			}
2282
+		} else {
2283
+			// this thing doesn't exist in the DB,  so just cache it
2284
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2285
+				throw new EE_Error(
2286
+					sprintf(
2287
+						esc_html__(
2288
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2289
+							'event_espresso'
2290
+						),
2291
+						$otherObjectModelObjectOrID,
2292
+						get_class($this)
2293
+					)
2294
+				);
2295
+			}
2296
+			$otherObject = $otherObjectModelObjectOrID;
2297
+			$this->cache($relation_name, $otherObjectModelObjectOrID, $cache_id);
2298
+		}
2299
+		if ($otherObject instanceof EE_Base_Class) {
2300
+			// fix the reciprocal relation too
2301
+			if ($otherObject->ID()) {
2302
+				// its saved so assumed relations exist in the DB, so we can just
2303
+				// clear the cache so future queries use the updated info in the DB
2304
+				$otherObject->clear_cache(
2305
+					$model->get_this_model_name(),
2306
+					null,
2307
+					true
2308
+				);
2309
+			} else {
2310
+				// it's not saved, so it caches relations like this
2311
+				$otherObject->cache($model->get_this_model_name(), $this);
2312
+			}
2313
+		}
2314
+		return $otherObject;
2315
+	}
2316
+
2317
+
2318
+	/**
2319
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2320
+	 * model is related to a group of events, the $relation_name should be 'Events', and should be a key in the EE
2321
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2322
+	 * from the cache
2323
+	 *
2324
+	 * @param mixed  $otherObjectModelObjectOrID
2325
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2326
+	 *                to the DB yet
2327
+	 * @param string $relation_name
2328
+	 * @param array  $where_query
2329
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2330
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2331
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2332
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2333
+	 *                deleted.
2334
+	 * @return EE_Base_Class the relation was removed from
2335
+	 * @throws ReflectionException
2336
+	 * @throws InvalidArgumentException
2337
+	 * @throws InvalidInterfaceException
2338
+	 * @throws InvalidDataTypeException
2339
+	 * @throws EE_Error
2340
+	 */
2341
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relation_name, $where_query = [])
2342
+	{
2343
+		if ($this->ID()) {
2344
+			// if this exists in the DB, save the relation change to the DB too
2345
+			$otherObject = $this->get_model()->remove_relationship_to(
2346
+				$this,
2347
+				$otherObjectModelObjectOrID,
2348
+				$relation_name,
2349
+				$where_query
2350
+			);
2351
+			$this->clear_cache(
2352
+				$relation_name,
2353
+				$otherObject
2354
+			);
2355
+		} else {
2356
+			// this doesn't exist in the DB, just remove it from the cache
2357
+			$otherObject = $this->clear_cache(
2358
+				$relation_name,
2359
+				$otherObjectModelObjectOrID
2360
+			);
2361
+		}
2362
+		if ($otherObject instanceof EE_Base_Class) {
2363
+			$otherObject->clear_cache(
2364
+				$this->get_model()->get_this_model_name(),
2365
+				$this
2366
+			);
2367
+		}
2368
+		return $otherObject;
2369
+	}
2370
+
2371
+
2372
+	/**
2373
+	 * Removes ALL the related things for the $relation_name.
2374
+	 *
2375
+	 * @param string $relation_name
2376
+	 * @param array  $where_query_params @see
2377
+	 *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2378
+	 * @return EE_Base_Class
2379
+	 * @throws ReflectionException
2380
+	 * @throws InvalidArgumentException
2381
+	 * @throws InvalidInterfaceException
2382
+	 * @throws InvalidDataTypeException
2383
+	 * @throws EE_Error
2384
+	 */
2385
+	public function _remove_relations($relation_name, $where_query_params = [])
2386
+	{
2387
+		if ($this->ID()) {
2388
+			// if this exists in the DB, save the relation change to the DB too
2389
+			$otherObjects = $this->get_model()->remove_relations(
2390
+				$this,
2391
+				$relation_name,
2392
+				$where_query_params
2393
+			);
2394
+			$this->clear_cache(
2395
+				$relation_name,
2396
+				null,
2397
+				true
2398
+			);
2399
+		} else {
2400
+			// this doesn't exist in the DB, just remove it from the cache
2401
+			$otherObjects = $this->clear_cache(
2402
+				$relation_name,
2403
+				null,
2404
+				true
2405
+			);
2406
+		}
2407
+		if (is_array($otherObjects)) {
2408
+			foreach ($otherObjects as $otherObject) {
2409
+				$otherObject->clear_cache(
2410
+					$this->get_model()->get_this_model_name(),
2411
+					$this
2412
+				);
2413
+			}
2414
+		}
2415
+		return $otherObjects;
2416
+	}
2417
+
2418
+
2419
+	/**
2420
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2421
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2422
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2423
+	 * because we want to get even deleted items etc.
2424
+	 *
2425
+	 * @param string      $relation_name key in the model's _model_relations array
2426
+	 * @param array|null  $query_params  @see
2427
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2428
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2429
+	 *                              keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2430
+	 *                              results if you want IDs
2431
+	 * @throws ReflectionException
2432
+	 * @throws InvalidArgumentException
2433
+	 * @throws InvalidInterfaceException
2434
+	 * @throws InvalidDataTypeException
2435
+	 * @throws EE_Error
2436
+	 */
2437
+	public function get_many_related($relation_name, $query_params = [])
2438
+	{
2439
+		if ($this->ID()) {
2440
+			// this exists in the DB, so get the related things from either the cache or the DB
2441
+			// if there are query parameters, forget about caching the related model objects.
2442
+			if ($query_params) {
2443
+				$related_model_objects = $this->get_model()->get_all_related(
2444
+					$this,
2445
+					$relation_name,
2446
+					$query_params
2447
+				);
2448
+			} else {
2449
+				// did we already cache the result of this query?
2450
+				$cached_results = $this->get_all_from_cache($relation_name);
2451
+				if (! $cached_results) {
2452
+					$related_model_objects = $this->get_model()->get_all_related(
2453
+						$this,
2454
+						$relation_name,
2455
+						$query_params
2456
+					);
2457
+					// if no query parameters were passed, then we got all the related model objects
2458
+					// for that relation. We can cache them then.
2459
+					foreach ($related_model_objects as $related_model_object) {
2460
+						$this->cache($relation_name, $related_model_object);
2461
+					}
2462
+				} else {
2463
+					$related_model_objects = $cached_results;
2464
+				}
2465
+			}
2466
+		} else {
2467
+			// this doesn't exist in the DB, so just get the related things from the cache
2468
+			$related_model_objects = $this->get_all_from_cache($relation_name);
2469
+		}
2470
+		return $related_model_objects;
2471
+	}
2472
+
2473
+
2474
+	/**
2475
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2476
+	 * unless otherwise specified in the $query_params
2477
+	 *
2478
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2479
+	 * @param array  $query_params   @see
2480
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2481
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2482
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2483
+	 *                               that by the setting $distinct to TRUE;
2484
+	 * @return int
2485
+	 * @throws ReflectionException
2486
+	 * @throws InvalidArgumentException
2487
+	 * @throws InvalidInterfaceException
2488
+	 * @throws InvalidDataTypeException
2489
+	 * @throws EE_Error
2490
+	 */
2491
+	public function count_related($relation_name, $query_params = [], $field_to_count = null, $distinct = false)
2492
+	{
2493
+		return $this->get_model()->count_related(
2494
+			$this,
2495
+			$relation_name,
2496
+			$query_params,
2497
+			$field_to_count,
2498
+			$distinct
2499
+		);
2500
+	}
2501
+
2502
+
2503
+	/**
2504
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2505
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2506
+	 *
2507
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2508
+	 * @param array  $query_params  @see
2509
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2510
+	 * @param string $field_to_sum  name of field to count by.
2511
+	 *                              By default, uses primary key
2512
+	 *                              (which doesn't make much sense, so you should probably change it)
2513
+	 * @return int
2514
+	 * @throws ReflectionException
2515
+	 * @throws InvalidArgumentException
2516
+	 * @throws InvalidInterfaceException
2517
+	 * @throws InvalidDataTypeException
2518
+	 * @throws EE_Error
2519
+	 */
2520
+	public function sum_related($relation_name, $query_params = [], $field_to_sum = null)
2521
+	{
2522
+		return $this->get_model()->sum_related(
2523
+			$this,
2524
+			$relation_name,
2525
+			$query_params,
2526
+			$field_to_sum
2527
+		);
2528
+	}
2529
+
2530
+
2531
+	/**
2532
+	 * Gets the first (ie, one) related model object of the specified type.
2533
+	 *
2534
+	 * @param string $relation_name key in the model's _model_relations array
2535
+	 * @param array  $query_params  @see
2536
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2537
+	 * @return EE_Base_Class|null (not an array, a single object)
2538
+	 * @throws ReflectionException
2539
+	 * @throws InvalidArgumentException
2540
+	 * @throws InvalidInterfaceException
2541
+	 * @throws InvalidDataTypeException
2542
+	 * @throws EE_Error
2543
+	 */
2544
+	public function get_first_related(string $relation_name, array $query_params = []): ?EE_Base_Class
2545
+	{
2546
+		$model = $this->get_model();
2547
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2548
+			// if they've provided some query parameters, don't bother trying to cache the result
2549
+			// also make sure we're not caching the result of get_first_related
2550
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2551
+			if (
2552
+				$query_params
2553
+				|| ! $model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation
2554
+			) {
2555
+				$related_model_object = $model->get_first_related(
2556
+					$this,
2557
+					$relation_name,
2558
+					$query_params
2559
+				);
2560
+			} else {
2561
+				// first, check if we've already cached the result of this query
2562
+				$cached_result = $this->get_one_from_cache($relation_name);
2563
+				if (! $cached_result) {
2564
+					$related_model_object = $model->get_first_related(
2565
+						$this,
2566
+						$relation_name,
2567
+						$query_params
2568
+					);
2569
+					$this->cache($relation_name, $related_model_object);
2570
+				} else {
2571
+					$related_model_object = $cached_result;
2572
+				}
2573
+			}
2574
+		} else {
2575
+			$related_model_object = null;
2576
+			// this doesn't exist in the Db,
2577
+			// but maybe the relation is of type belongs to, and so the related thing might
2578
+			if ($model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation) {
2579
+				$related_model_object = $model->get_first_related(
2580
+					$this,
2581
+					$relation_name,
2582
+					$query_params
2583
+				);
2584
+			}
2585
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2586
+			// just get what's cached on this object
2587
+			if (! $related_model_object) {
2588
+				$related_model_object = $this->get_one_from_cache($relation_name);
2589
+			}
2590
+		}
2591
+		return $related_model_object;
2592
+	}
2593
+
2594
+
2595
+	/**
2596
+	 * Does a delete on all related objects of type $relation_name and removes
2597
+	 * the current model object's relation to them. If they can't be deleted (because
2598
+	 * of blocking related model objects) does nothing. If the related model objects are
2599
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2600
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2601
+	 *
2602
+	 * @param string $relation_name
2603
+	 * @param array  $query_params @see
2604
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2605
+	 * @return int how many deleted
2606
+	 * @throws ReflectionException
2607
+	 * @throws InvalidArgumentException
2608
+	 * @throws InvalidInterfaceException
2609
+	 * @throws InvalidDataTypeException
2610
+	 * @throws EE_Error
2611
+	 */
2612
+	public function delete_related($relation_name, $query_params = [])
2613
+	{
2614
+		if ($this->ID()) {
2615
+			$count = $this->get_model()->delete_related(
2616
+				$this,
2617
+				$relation_name,
2618
+				$query_params
2619
+			);
2620
+		} else {
2621
+			$count = count($this->get_all_from_cache($relation_name));
2622
+			$this->clear_cache($relation_name, null, true);
2623
+		}
2624
+		return $count;
2625
+	}
2626
+
2627
+
2628
+	/**
2629
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relation_name and removes
2630
+	 * the current model object's relation to them. If they can't be deleted (because
2631
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2632
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2633
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2634
+	 *
2635
+	 * @param string $relation_name
2636
+	 * @param array  $query_params @see
2637
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2638
+	 * @return int how many deleted (including those soft deleted)
2639
+	 * @throws ReflectionException
2640
+	 * @throws InvalidArgumentException
2641
+	 * @throws InvalidInterfaceException
2642
+	 * @throws InvalidDataTypeException
2643
+	 * @throws EE_Error
2644
+	 */
2645
+	public function delete_related_permanently($relation_name, $query_params = [])
2646
+	{
2647
+		$count = $this->ID()
2648
+			? $this->get_model()->delete_related_permanently(
2649
+				$this,
2650
+				$relation_name,
2651
+				$query_params
2652
+			)
2653
+			: count($this->get_all_from_cache($relation_name));
2654
+
2655
+		$this->clear_cache($relation_name, null, true);
2656
+		return $count;
2657
+	}
2658
+
2659
+
2660
+	/**
2661
+	 * is_set
2662
+	 * Just a simple utility function children can use for checking if property exists
2663
+	 *
2664
+	 * @access  public
2665
+	 * @param string $field_name property to check
2666
+	 * @return bool                              TRUE if existing,FALSE if not.
2667
+	 */
2668
+	public function is_set($field_name)
2669
+	{
2670
+		return isset($this->_fields[ $field_name ]);
2671
+	}
2672
+
2673
+
2674
+	/**
2675
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2676
+	 * EE_Error exception if they don't
2677
+	 *
2678
+	 * @param mixed (string|array) $properties properties to check
2679
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2680
+	 * @throws EE_Error
2681
+	 */
2682
+	protected function _property_exists($properties)
2683
+	{
2684
+		foreach ((array) $properties as $property_name) {
2685
+			// first make sure this property exists
2686
+			if (! $this->_fields[ $property_name ]) {
2687
+				throw new EE_Error(
2688
+					sprintf(
2689
+						esc_html__(
2690
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2691
+							'event_espresso'
2692
+						),
2693
+						$property_name
2694
+					)
2695
+				);
2696
+			}
2697
+		}
2698
+		return true;
2699
+	}
2700
+
2701
+
2702
+	/**
2703
+	 * This simply returns an array of model fields for this object
2704
+	 *
2705
+	 * @return array
2706
+	 * @throws ReflectionException
2707
+	 * @throws InvalidArgumentException
2708
+	 * @throws InvalidInterfaceException
2709
+	 * @throws InvalidDataTypeException
2710
+	 * @throws EE_Error
2711
+	 */
2712
+	public function model_field_array()
2713
+	{
2714
+		$fields     = $this->get_model()->field_settings(false);
2715
+		$properties = [];
2716
+		// remove prepended underscore
2717
+		foreach ($fields as $field_name => $settings) {
2718
+			$properties[ $field_name ] = $this->get($field_name);
2719
+		}
2720
+		return $properties;
2721
+	}
2722
+
2723
+
2724
+	/**
2725
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2726
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2727
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2728
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2729
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2730
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2731
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2732
+	 * and accepts 2 arguments: the object on which the function was called,
2733
+	 * and an array of the original arguments passed to the function.
2734
+	 * Whatever their callback function returns will be returned by this function.
2735
+	 * Example: in functions.php (or in a plugin):
2736
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2737
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2738
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2739
+	 *          return $previousReturnValue.$returnString;
2740
+	 *      }
2741
+	 * require('EE_Answer.class.php');
2742
+	 * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2743
+	 *      ->my_callback('monkeys',100);
2744
+	 * // will output "you called my_callback! and passed args:monkeys,100"
2745
+	 *
2746
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2747
+	 * @param array  $args       array of original arguments passed to the function
2748
+	 * @return mixed whatever the plugin which calls add_filter decides
2749
+	 * @throws EE_Error
2750
+	 */
2751
+	public function __call($methodName, $args)
2752
+	{
2753
+		$className = get_class($this);
2754
+		$tagName   = "FHEE__{$className}__{$methodName}";
2755
+		if (! has_filter($tagName)) {
2756
+			throw new EE_Error(
2757
+				sprintf(
2758
+					esc_html__(
2759
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2760
+						'event_espresso'
2761
+					),
2762
+					$methodName,
2763
+					$className,
2764
+					$tagName
2765
+				)
2766
+			);
2767
+		}
2768
+		return apply_filters($tagName, null, $this, $args);
2769
+	}
2770
+
2771
+
2772
+	/**
2773
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2774
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2775
+	 *
2776
+	 * @param string $meta_key
2777
+	 * @param mixed  $meta_value
2778
+	 * @param mixed  $previous_value
2779
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2780
+	 *                  NOTE: if the values haven't changed, returns 0
2781
+	 * @throws InvalidArgumentException
2782
+	 * @throws InvalidInterfaceException
2783
+	 * @throws InvalidDataTypeException
2784
+	 * @throws EE_Error
2785
+	 * @throws ReflectionException
2786
+	 */
2787
+	public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2788
+	{
2789
+		$query_params = [
2790
+			[
2791
+				'EXM_key'  => $meta_key,
2792
+				'OBJ_ID'   => $this->ID(),
2793
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2794
+			],
2795
+		];
2796
+		if ($previous_value !== null) {
2797
+			$query_params[0]['EXM_value'] = $meta_value;
2798
+		}
2799
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2800
+		if (! $existing_rows_like_that) {
2801
+			return $this->add_extra_meta($meta_key, $meta_value);
2802
+		}
2803
+		foreach ($existing_rows_like_that as $existing_row) {
2804
+			$existing_row->save(['EXM_value' => $meta_value]);
2805
+		}
2806
+		return count($existing_rows_like_that);
2807
+	}
2808
+
2809
+
2810
+	/**
2811
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2812
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2813
+	 * extra meta row was entered, false if not
2814
+	 *
2815
+	 * @param string $meta_key
2816
+	 * @param mixed  $meta_value
2817
+	 * @param bool   $unique
2818
+	 * @return bool
2819
+	 * @throws InvalidArgumentException
2820
+	 * @throws InvalidInterfaceException
2821
+	 * @throws InvalidDataTypeException
2822
+	 * @throws EE_Error
2823
+	 * @throws ReflectionException
2824
+	 */
2825
+	public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2826
+	{
2827
+		if ($unique) {
2828
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2829
+				[
2830
+					[
2831
+						'EXM_key'  => $meta_key,
2832
+						'OBJ_ID'   => $this->ID(),
2833
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2834
+					],
2835
+				]
2836
+			);
2837
+			if ($existing_extra_meta) {
2838
+				return false;
2839
+			}
2840
+		}
2841
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2842
+			[
2843
+				'EXM_key'   => $meta_key,
2844
+				'EXM_value' => $meta_value,
2845
+				'OBJ_ID'    => $this->ID(),
2846
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2847
+			]
2848
+		);
2849
+		$new_extra_meta->save();
2850
+		return true;
2851
+	}
2852
+
2853
+
2854
+	/**
2855
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2856
+	 * is specified, only deletes extra meta records with that value.
2857
+	 *
2858
+	 * @param string $meta_key
2859
+	 * @param mixed  $meta_value
2860
+	 * @return int|bool number of extra meta rows deleted
2861
+	 * @throws InvalidArgumentException
2862
+	 * @throws InvalidInterfaceException
2863
+	 * @throws InvalidDataTypeException
2864
+	 * @throws EE_Error
2865
+	 * @throws ReflectionException
2866
+	 */
2867
+	public function delete_extra_meta(string $meta_key, $meta_value = null)
2868
+	{
2869
+		$query_params = [
2870
+			[
2871
+				'EXM_key'  => $meta_key,
2872
+				'OBJ_ID'   => $this->ID(),
2873
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2874
+			],
2875
+		];
2876
+		if ($meta_value !== null) {
2877
+			$query_params[0]['EXM_value'] = $meta_value;
2878
+		}
2879
+		return EEM_Extra_Meta::instance()->delete($query_params);
2880
+	}
2881
+
2882
+
2883
+	/**
2884
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2885
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2886
+	 * You can specify $default is case you haven't found the extra meta
2887
+	 *
2888
+	 * @param string     $meta_key
2889
+	 * @param bool       $single
2890
+	 * @param mixed      $default if we don't find anything, what should we return?
2891
+	 * @param array|null $extra_where
2892
+	 * @return mixed single value if $single; array if ! $single
2893
+	 * @throws ReflectionException
2894
+	 * @throws EE_Error
2895
+	 */
2896
+	public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2897
+	{
2898
+		$query_params = [$extra_where + ['EXM_key' => $meta_key]];
2899
+		if ($single) {
2900
+			$result = $this->get_first_related('Extra_Meta', $query_params);
2901
+			if ($result instanceof EE_Extra_Meta) {
2902
+				return $result->value();
2903
+			}
2904
+		} else {
2905
+			$results = $this->get_many_related('Extra_Meta', $query_params);
2906
+			if ($results) {
2907
+				$values = [];
2908
+				foreach ($results as $result) {
2909
+					if ($result instanceof EE_Extra_Meta) {
2910
+						$values[ $result->ID() ] = $result->value();
2911
+					}
2912
+				}
2913
+				return $values;
2914
+			}
2915
+		}
2916
+		// if nothing discovered yet return default.
2917
+		return apply_filters(
2918
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2919
+			$default,
2920
+			$meta_key,
2921
+			$single,
2922
+			$this
2923
+		);
2924
+	}
2925
+
2926
+
2927
+	/**
2928
+	 * Returns a simple array of all the extra meta associated with this model object.
2929
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2930
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2931
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2932
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2933
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2934
+	 * finally the extra meta's value as each sub-value. (eg
2935
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2936
+	 *
2937
+	 * @param bool $one_of_each_key
2938
+	 * @return array
2939
+	 * @throws ReflectionException
2940
+	 * @throws InvalidArgumentException
2941
+	 * @throws InvalidInterfaceException
2942
+	 * @throws InvalidDataTypeException
2943
+	 * @throws EE_Error
2944
+	 */
2945
+	public function all_extra_meta_array(bool $one_of_each_key = true): array
2946
+	{
2947
+		$return_array = [];
2948
+		if ($one_of_each_key) {
2949
+			$extra_meta_objs = $this->get_many_related(
2950
+				'Extra_Meta',
2951
+				['group_by' => 'EXM_key']
2952
+			);
2953
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2954
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2955
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2956
+				}
2957
+			}
2958
+		} else {
2959
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2960
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2961
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2962
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2963
+						$return_array[ $extra_meta_obj->key() ] = [];
2964
+					}
2965
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2966
+				}
2967
+			}
2968
+		}
2969
+		return $return_array;
2970
+	}
2971
+
2972
+
2973
+	/**
2974
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2975
+	 *
2976
+	 * @return string
2977
+	 * @throws ReflectionException
2978
+	 * @throws InvalidArgumentException
2979
+	 * @throws InvalidInterfaceException
2980
+	 * @throws InvalidDataTypeException
2981
+	 * @throws EE_Error
2982
+	 */
2983
+	public function name()
2984
+	{
2985
+		// find a field that's not a text field
2986
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2987
+		if ($field_we_can_use) {
2988
+			return $this->get($field_we_can_use->get_name());
2989
+		}
2990
+		$first_few_properties = $this->model_field_array();
2991
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
2992
+		$name_parts           = [];
2993
+		foreach ($first_few_properties as $name => $value) {
2994
+			$name_parts[] = "$name:$value";
2995
+		}
2996
+		return implode(',', $name_parts);
2997
+	}
2998
+
2999
+
3000
+	/**
3001
+	 * in_entity_map
3002
+	 * Checks if this model object has been proven to already be in the entity map
3003
+	 *
3004
+	 * @return boolean
3005
+	 * @throws ReflectionException
3006
+	 * @throws InvalidArgumentException
3007
+	 * @throws InvalidInterfaceException
3008
+	 * @throws InvalidDataTypeException
3009
+	 * @throws EE_Error
3010
+	 */
3011
+	public function in_entity_map()
3012
+	{
3013
+		// well, if we looked, did we find it in the entity map?
3014
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3015
+	}
3016
+
3017
+
3018
+	/**
3019
+	 * refresh_from_db
3020
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3021
+	 *
3022
+	 * @throws ReflectionException
3023
+	 * @throws InvalidArgumentException
3024
+	 * @throws InvalidInterfaceException
3025
+	 * @throws InvalidDataTypeException
3026
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3027
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3028
+	 */
3029
+	public function refresh_from_db()
3030
+	{
3031
+		if ($this->ID() && $this->in_entity_map()) {
3032
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3033
+		} else {
3034
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3035
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3036
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3037
+			// absolutely nothing in it for this ID
3038
+			if (WP_DEBUG) {
3039
+				throw new EE_Error(
3040
+					sprintf(
3041
+						esc_html__(
3042
+							'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3043
+							'event_espresso'
3044
+						),
3045
+						$this->ID(),
3046
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3047
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3048
+					)
3049
+				);
3050
+			}
3051
+		}
3052
+	}
3053
+
3054
+
3055
+	/**
3056
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3057
+	 *
3058
+	 * @param EE_Model_Field_Base[] $fields
3059
+	 * @param string                $new_value_sql
3060
+	 *          example: 'column_name=123',
3061
+	 *          or 'column_name=column_name+1',
3062
+	 *          or 'column_name= CASE
3063
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3064
+	 *          THEN `column_name` + 5
3065
+	 *          ELSE `column_name`
3066
+	 *          END'
3067
+	 *          Also updates $field on this model object with the latest value from the database.
3068
+	 * @return bool
3069
+	 * @throws EE_Error
3070
+	 * @throws InvalidArgumentException
3071
+	 * @throws InvalidDataTypeException
3072
+	 * @throws InvalidInterfaceException
3073
+	 * @throws ReflectionException
3074
+	 * @since 4.9.80.p
3075
+	 */
3076
+	protected function updateFieldsInDB($fields, $new_value_sql)
3077
+	{
3078
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3079
+		// if it wasn't even there to start off.
3080
+		if (! $this->ID()) {
3081
+			$this->save();
3082
+		}
3083
+		global $wpdb;
3084
+		if (empty($fields)) {
3085
+			throw new InvalidArgumentException(
3086
+				esc_html__(
3087
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3088
+					'event_espresso'
3089
+				)
3090
+			);
3091
+		}
3092
+		$first_field = reset($fields);
3093
+		$table_alias = $first_field->get_table_alias();
3094
+		foreach ($fields as $field) {
3095
+			if ($table_alias !== $field->get_table_alias()) {
3096
+				throw new InvalidArgumentException(
3097
+					sprintf(
3098
+						esc_html__(
3099
+						// @codingStandardsIgnoreStart
3100
+							'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3101
+							// @codingStandardsIgnoreEnd
3102
+							'event_espresso'
3103
+						),
3104
+						$table_alias,
3105
+						$field->get_table_alias()
3106
+					)
3107
+				);
3108
+			}
3109
+		}
3110
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3111
+		$table_obj      = $this->get_model()->get_table_obj_by_alias($table_alias);
3112
+		$table_pk_value = $this->ID();
3113
+		$table_name     = $table_obj->get_table_name();
3114
+		if ($table_obj instanceof EE_Secondary_Table) {
3115
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3116
+		} else {
3117
+			$table_pk_field_name = $table_obj->get_pk_column();
3118
+		}
3119
+
3120
+		$query  =
3121
+			"UPDATE `{$table_name}`
3122 3122
             SET "
3123
-            . $new_value_sql
3124
-            . $wpdb->prepare(
3125
-                "
3123
+			. $new_value_sql
3124
+			. $wpdb->prepare(
3125
+				"
3126 3126
             WHERE `{$table_pk_field_name}` = %d;",
3127
-                $table_pk_value
3128
-            );
3129
-        $result = $wpdb->query($query);
3130
-        foreach ($fields as $field) {
3131
-            // If it was successful, we'd like to know the new value.
3132
-            // If it failed, we'd also like to know the new value.
3133
-            $new_value = $this->get_model()->get_var(
3134
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3135
-                    $this->get_model()->get_index_primary_key_string(
3136
-                        $this->model_field_array()
3137
-                    ),
3138
-                    [
3139
-                        'default_where_conditions' => 'minimum',
3140
-                    ]
3141
-                ),
3142
-                $field->get_name()
3143
-            );
3144
-            $this->set_from_db(
3145
-                $field->get_name(),
3146
-                $new_value
3147
-            );
3148
-        }
3149
-        return (bool) $result;
3150
-    }
3151
-
3152
-
3153
-    /**
3154
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3155
-     * Does not allow negative values, however.
3156
-     *
3157
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3158
-     *                                   (positive or negative). One important gotcha: all these values must be
3159
-     *                                   on the same table (eg don't pass in one field for the posts table and
3160
-     *                                   another for the event meta table.)
3161
-     * @return bool
3162
-     * @throws EE_Error
3163
-     * @throws InvalidArgumentException
3164
-     * @throws InvalidDataTypeException
3165
-     * @throws InvalidInterfaceException
3166
-     * @throws ReflectionException
3167
-     * @since 4.9.80.p
3168
-     */
3169
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3170
-    {
3171
-        global $wpdb;
3172
-        if (empty($fields_n_quantities)) {
3173
-            // No fields to update? Well sure, we updated them to that value just fine.
3174
-            return true;
3175
-        }
3176
-        $fields             = [];
3177
-        $set_sql_statements = [];
3178
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3179
-            $field       = $this->get_model()->field_settings_for($field_name, true);
3180
-            $fields[]    = $field;
3181
-            $column_name = $field->get_table_column();
3182
-
3183
-            $abs_qty = absint($quantity);
3184
-            if ($quantity > 0) {
3185
-                // don't let the value be negative as often these fields are unsigned
3186
-                $set_sql_statements[] = $wpdb->prepare(
3187
-                    "`{$column_name}` = `{$column_name}` + %d",
3188
-                    $abs_qty
3189
-                );
3190
-            } else {
3191
-                $set_sql_statements[] = $wpdb->prepare(
3192
-                    "`{$column_name}` = CASE
3127
+				$table_pk_value
3128
+			);
3129
+		$result = $wpdb->query($query);
3130
+		foreach ($fields as $field) {
3131
+			// If it was successful, we'd like to know the new value.
3132
+			// If it failed, we'd also like to know the new value.
3133
+			$new_value = $this->get_model()->get_var(
3134
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3135
+					$this->get_model()->get_index_primary_key_string(
3136
+						$this->model_field_array()
3137
+					),
3138
+					[
3139
+						'default_where_conditions' => 'minimum',
3140
+					]
3141
+				),
3142
+				$field->get_name()
3143
+			);
3144
+			$this->set_from_db(
3145
+				$field->get_name(),
3146
+				$new_value
3147
+			);
3148
+		}
3149
+		return (bool) $result;
3150
+	}
3151
+
3152
+
3153
+	/**
3154
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3155
+	 * Does not allow negative values, however.
3156
+	 *
3157
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3158
+	 *                                   (positive or negative). One important gotcha: all these values must be
3159
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3160
+	 *                                   another for the event meta table.)
3161
+	 * @return bool
3162
+	 * @throws EE_Error
3163
+	 * @throws InvalidArgumentException
3164
+	 * @throws InvalidDataTypeException
3165
+	 * @throws InvalidInterfaceException
3166
+	 * @throws ReflectionException
3167
+	 * @since 4.9.80.p
3168
+	 */
3169
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3170
+	{
3171
+		global $wpdb;
3172
+		if (empty($fields_n_quantities)) {
3173
+			// No fields to update? Well sure, we updated them to that value just fine.
3174
+			return true;
3175
+		}
3176
+		$fields             = [];
3177
+		$set_sql_statements = [];
3178
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3179
+			$field       = $this->get_model()->field_settings_for($field_name, true);
3180
+			$fields[]    = $field;
3181
+			$column_name = $field->get_table_column();
3182
+
3183
+			$abs_qty = absint($quantity);
3184
+			if ($quantity > 0) {
3185
+				// don't let the value be negative as often these fields are unsigned
3186
+				$set_sql_statements[] = $wpdb->prepare(
3187
+					"`{$column_name}` = `{$column_name}` + %d",
3188
+					$abs_qty
3189
+				);
3190
+			} else {
3191
+				$set_sql_statements[] = $wpdb->prepare(
3192
+					"`{$column_name}` = CASE
3193 3193
                        WHEN (`{$column_name}` >= %d)
3194 3194
                        THEN `{$column_name}` - %d
3195 3195
                        ELSE 0
3196 3196
                     END",
3197
-                    $abs_qty,
3198
-                    $abs_qty
3199
-                );
3200
-            }
3201
-        }
3202
-        return $this->updateFieldsInDB(
3203
-            $fields,
3204
-            implode(', ', $set_sql_statements)
3205
-        );
3206
-    }
3207
-
3208
-
3209
-    /**
3210
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3211
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3212
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3213
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3214
-     * Otherwise returns false.
3215
-     *
3216
-     * @param string $field_name_to_bump
3217
-     * @param string $field_name_affecting_total
3218
-     * @param string $limit_field_name
3219
-     * @param int    $quantity
3220
-     * @return bool
3221
-     * @throws EE_Error
3222
-     * @throws InvalidArgumentException
3223
-     * @throws InvalidDataTypeException
3224
-     * @throws InvalidInterfaceException
3225
-     * @throws ReflectionException
3226
-     * @since 4.9.80.p
3227
-     */
3228
-    public function incrementFieldConditionallyInDb(
3229
-        $field_name_to_bump,
3230
-        $field_name_affecting_total,
3231
-        $limit_field_name,
3232
-        $quantity
3233
-    ) {
3234
-        global $wpdb;
3235
-        $field       = $this->get_model()->field_settings_for($field_name_to_bump, true);
3236
-        $column_name = $field->get_table_column();
3237
-
3238
-        $field_affecting_total  = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3239
-        $column_affecting_total = $field_affecting_total->get_table_column();
3240
-
3241
-        $limiting_field  = $this->get_model()->field_settings_for($limit_field_name, true);
3242
-        $limiting_column = $limiting_field->get_table_column();
3243
-        return $this->updateFieldsInDB(
3244
-            [$field],
3245
-            $wpdb->prepare(
3246
-                "`{$column_name}` =
3197
+					$abs_qty,
3198
+					$abs_qty
3199
+				);
3200
+			}
3201
+		}
3202
+		return $this->updateFieldsInDB(
3203
+			$fields,
3204
+			implode(', ', $set_sql_statements)
3205
+		);
3206
+	}
3207
+
3208
+
3209
+	/**
3210
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3211
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3212
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3213
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3214
+	 * Otherwise returns false.
3215
+	 *
3216
+	 * @param string $field_name_to_bump
3217
+	 * @param string $field_name_affecting_total
3218
+	 * @param string $limit_field_name
3219
+	 * @param int    $quantity
3220
+	 * @return bool
3221
+	 * @throws EE_Error
3222
+	 * @throws InvalidArgumentException
3223
+	 * @throws InvalidDataTypeException
3224
+	 * @throws InvalidInterfaceException
3225
+	 * @throws ReflectionException
3226
+	 * @since 4.9.80.p
3227
+	 */
3228
+	public function incrementFieldConditionallyInDb(
3229
+		$field_name_to_bump,
3230
+		$field_name_affecting_total,
3231
+		$limit_field_name,
3232
+		$quantity
3233
+	) {
3234
+		global $wpdb;
3235
+		$field       = $this->get_model()->field_settings_for($field_name_to_bump, true);
3236
+		$column_name = $field->get_table_column();
3237
+
3238
+		$field_affecting_total  = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3239
+		$column_affecting_total = $field_affecting_total->get_table_column();
3240
+
3241
+		$limiting_field  = $this->get_model()->field_settings_for($limit_field_name, true);
3242
+		$limiting_column = $limiting_field->get_table_column();
3243
+		return $this->updateFieldsInDB(
3244
+			[$field],
3245
+			$wpdb->prepare(
3246
+				"`{$column_name}` =
3247 3247
             CASE
3248 3248
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3249 3249
                THEN `{$column_name}` + %d
3250 3250
                ELSE `{$column_name}`
3251 3251
             END",
3252
-                $quantity,
3253
-                EE_INF_IN_DB,
3254
-                $quantity
3255
-            )
3256
-        );
3257
-    }
3258
-
3259
-
3260
-    /**
3261
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3262
-     * (probably a bad assumption they have made, oh well)
3263
-     *
3264
-     * @return string
3265
-     */
3266
-    public function __toString()
3267
-    {
3268
-        try {
3269
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3270
-        } catch (Exception $e) {
3271
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3272
-            return '';
3273
-        }
3274
-    }
3275
-
3276
-
3277
-    /**
3278
-     * Clear related model objects if they're already in the DB, because otherwise when we
3279
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3280
-     * This means if we have made changes to those related model objects, and want to unserialize
3281
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3282
-     * Instead, those related model objects should be directly serialized and stored.
3283
-     * Eg, the following won't work:
3284
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3285
-     * $att = $reg->attendee();
3286
-     * $att->set( 'ATT_fname', 'Dirk' );
3287
-     * update_option( 'my_option', serialize( $reg ) );
3288
-     * //END REQUEST
3289
-     * //START NEXT REQUEST
3290
-     * $reg = get_option( 'my_option' );
3291
-     * $reg->attendee()->save();
3292
-     * And would need to be replace with:
3293
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3294
-     * $att = $reg->attendee();
3295
-     * $att->set( 'ATT_fname', 'Dirk' );
3296
-     * update_option( 'my_option', serialize( $reg ) );
3297
-     * //END REQUEST
3298
-     * //START NEXT REQUEST
3299
-     * $att = get_option( 'my_option' );
3300
-     * $att->save();
3301
-     *
3302
-     * @return array
3303
-     * @throws ReflectionException
3304
-     * @throws InvalidArgumentException
3305
-     * @throws InvalidInterfaceException
3306
-     * @throws InvalidDataTypeException
3307
-     * @throws EE_Error
3308
-     */
3309
-    public function __sleep()
3310
-    {
3311
-        $model = $this->get_model();
3312
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3313
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3314
-                $classname = 'EE_' . $model->get_this_model_name();
3315
-                if (
3316
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3317
-                    && $this->get_one_from_cache($relation_name)->ID()
3318
-                ) {
3319
-                    $this->clear_cache(
3320
-                        $relation_name,
3321
-                        $this->get_one_from_cache($relation_name)->ID()
3322
-                    );
3323
-                }
3324
-            }
3325
-        }
3326
-        $this->_props_n_values_provided_in_constructor = [];
3327
-        $properties_to_serialize                       = get_object_vars($this);
3328
-        // don't serialize the model. It's big and that risks recursion
3329
-        unset($properties_to_serialize['_model']);
3330
-        return array_keys($properties_to_serialize);
3331
-    }
3332
-
3333
-
3334
-    /**
3335
-     * restore _props_n_values_provided_in_constructor
3336
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3337
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3338
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3339
-     */
3340
-    public function __wakeup()
3341
-    {
3342
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3343
-    }
3344
-
3345
-
3346
-    /**
3347
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3348
-     * distinct with the clone host instance are also cloned.
3349
-     */
3350
-    public function __clone()
3351
-    {
3352
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3353
-        foreach ($this->_fields as $field => $value) {
3354
-            if ($value instanceof DateTime) {
3355
-                $this->_fields[ $field ] = clone $value;
3356
-            }
3357
-        }
3358
-    }
3359
-
3360
-
3361
-    public function debug()
3362
-    {
3363
-        $this->echoProperty(get_class($this), get_object_vars($this));
3364
-        echo "\n\n";
3365
-    }
3366
-
3367
-
3368
-    private function echoProperty($field, $value, int $indent = 0)
3369
-    {
3370
-        $bullets = str_repeat(' -', $indent) . ' ';
3371
-        $field = strpos($field, '_') === 0 ? substr($field, 1) : $field;
3372
-        echo "\n$bullets$field: ";
3373
-        if ($value instanceof EEM_Base) {
3374
-            $value = get_class($value);
3375
-        } elseif (is_object($value)) {
3376
-            $value = get_object_vars($value);
3377
-        }
3378
-        if (is_array($value)) {
3379
-            foreach ($value as $f => $v) {
3380
-                $this->echoProperty($f, $v, $indent + 1);
3381
-            }
3382
-            return;
3383
-        }
3384
-        ob_start();
3385
-        var_dump($value);
3386
-        echo rtrim(ob_get_clean(), "\n");
3387
-    }
3252
+				$quantity,
3253
+				EE_INF_IN_DB,
3254
+				$quantity
3255
+			)
3256
+		);
3257
+	}
3258
+
3259
+
3260
+	/**
3261
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3262
+	 * (probably a bad assumption they have made, oh well)
3263
+	 *
3264
+	 * @return string
3265
+	 */
3266
+	public function __toString()
3267
+	{
3268
+		try {
3269
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3270
+		} catch (Exception $e) {
3271
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3272
+			return '';
3273
+		}
3274
+	}
3275
+
3276
+
3277
+	/**
3278
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3279
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3280
+	 * This means if we have made changes to those related model objects, and want to unserialize
3281
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3282
+	 * Instead, those related model objects should be directly serialized and stored.
3283
+	 * Eg, the following won't work:
3284
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3285
+	 * $att = $reg->attendee();
3286
+	 * $att->set( 'ATT_fname', 'Dirk' );
3287
+	 * update_option( 'my_option', serialize( $reg ) );
3288
+	 * //END REQUEST
3289
+	 * //START NEXT REQUEST
3290
+	 * $reg = get_option( 'my_option' );
3291
+	 * $reg->attendee()->save();
3292
+	 * And would need to be replace with:
3293
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3294
+	 * $att = $reg->attendee();
3295
+	 * $att->set( 'ATT_fname', 'Dirk' );
3296
+	 * update_option( 'my_option', serialize( $reg ) );
3297
+	 * //END REQUEST
3298
+	 * //START NEXT REQUEST
3299
+	 * $att = get_option( 'my_option' );
3300
+	 * $att->save();
3301
+	 *
3302
+	 * @return array
3303
+	 * @throws ReflectionException
3304
+	 * @throws InvalidArgumentException
3305
+	 * @throws InvalidInterfaceException
3306
+	 * @throws InvalidDataTypeException
3307
+	 * @throws EE_Error
3308
+	 */
3309
+	public function __sleep()
3310
+	{
3311
+		$model = $this->get_model();
3312
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3313
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3314
+				$classname = 'EE_' . $model->get_this_model_name();
3315
+				if (
3316
+					$this->get_one_from_cache($relation_name) instanceof $classname
3317
+					&& $this->get_one_from_cache($relation_name)->ID()
3318
+				) {
3319
+					$this->clear_cache(
3320
+						$relation_name,
3321
+						$this->get_one_from_cache($relation_name)->ID()
3322
+					);
3323
+				}
3324
+			}
3325
+		}
3326
+		$this->_props_n_values_provided_in_constructor = [];
3327
+		$properties_to_serialize                       = get_object_vars($this);
3328
+		// don't serialize the model. It's big and that risks recursion
3329
+		unset($properties_to_serialize['_model']);
3330
+		return array_keys($properties_to_serialize);
3331
+	}
3332
+
3333
+
3334
+	/**
3335
+	 * restore _props_n_values_provided_in_constructor
3336
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3337
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3338
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3339
+	 */
3340
+	public function __wakeup()
3341
+	{
3342
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3343
+	}
3344
+
3345
+
3346
+	/**
3347
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3348
+	 * distinct with the clone host instance are also cloned.
3349
+	 */
3350
+	public function __clone()
3351
+	{
3352
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3353
+		foreach ($this->_fields as $field => $value) {
3354
+			if ($value instanceof DateTime) {
3355
+				$this->_fields[ $field ] = clone $value;
3356
+			}
3357
+		}
3358
+	}
3359
+
3360
+
3361
+	public function debug()
3362
+	{
3363
+		$this->echoProperty(get_class($this), get_object_vars($this));
3364
+		echo "\n\n";
3365
+	}
3366
+
3367
+
3368
+	private function echoProperty($field, $value, int $indent = 0)
3369
+	{
3370
+		$bullets = str_repeat(' -', $indent) . ' ';
3371
+		$field = strpos($field, '_') === 0 ? substr($field, 1) : $field;
3372
+		echo "\n$bullets$field: ";
3373
+		if ($value instanceof EEM_Base) {
3374
+			$value = get_class($value);
3375
+		} elseif (is_object($value)) {
3376
+			$value = get_object_vars($value);
3377
+		}
3378
+		if (is_array($value)) {
3379
+			foreach ($value as $f => $v) {
3380
+				$this->echoProperty($f, $v, $indent + 1);
3381
+			}
3382
+			return;
3383
+		}
3384
+		ob_start();
3385
+		var_dump($value);
3386
+		echo rtrim(ob_get_clean(), "\n");
3387
+	}
3388 3388
 }
Please login to merge, or discard this patch.
Spacing   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
         $fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
133 133
         // verify client code has not passed any invalid field names
134 134
         foreach ($fieldValues as $field_name => $field_value) {
135
-            if (! isset($model_fields[ $field_name ])) {
135
+            if ( ! isset($model_fields[$field_name])) {
136 136
                 throw new EE_Error(
137 137
                     sprintf(
138 138
                         esc_html__(
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
         $date_format     = null;
151 151
         $time_format     = null;
152 152
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
153
-        if (! empty($date_formats) && is_array($date_formats)) {
153
+        if ( ! empty($date_formats) && is_array($date_formats)) {
154 154
             [$date_format, $time_format] = $date_formats;
155 155
         }
156 156
         $this->set_date_format($date_format);
@@ -161,14 +161,14 @@  discard block
 block discarded – undo
161 161
                 // client code has indicated these field values are from the database
162 162
                 $this->set_from_db(
163 163
                     $fieldName,
164
-                    $fieldValues[ $fieldName ] ?? null
164
+                    $fieldValues[$fieldName] ?? null
165 165
                 );
166 166
             } else {
167 167
                 // we're constructing a brand new instance of the model object.
168 168
                 // Generally, this means we'll need to do more field validation
169 169
                 $this->set(
170 170
                     $fieldName,
171
-                    $fieldValues[ $fieldName ] ?? null,
171
+                    $fieldValues[$fieldName] ?? null,
172 172
                     true
173 173
                 );
174 174
             }
@@ -176,15 +176,15 @@  discard block
 block discarded – undo
176 176
         // remember what values were passed to this constructor
177 177
         $this->_props_n_values_provided_in_constructor = $fieldValues;
178 178
         // remember in entity mapper
179
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
179
+        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
180 180
             $model->add_to_entity_map($this);
181 181
         }
182 182
         // setup all the relations
183 183
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
184 184
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
185
-                $this->_model_relations[ $relation_name ] = null;
185
+                $this->_model_relations[$relation_name] = null;
186 186
             } else {
187
-                $this->_model_relations[ $relation_name ] = [];
187
+                $this->_model_relations[$relation_name] = [];
188 188
             }
189 189
         }
190 190
         /**
@@ -236,10 +236,10 @@  discard block
 block discarded – undo
236 236
     public function get_original($field_name)
237 237
     {
238 238
         if (
239
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
239
+            isset($this->_props_n_values_provided_in_constructor[$field_name])
240 240
             && $field_settings = $this->get_model()->field_settings_for($field_name)
241 241
         ) {
242
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
242
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
243 243
         }
244 244
         return null;
245 245
     }
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
         // then don't do anything
276 276
         if (
277 277
             ! $use_default
278
-            && $this->_fields[ $field_name ] === $field_value
278
+            && $this->_fields[$field_name] === $field_value
279 279
             && $this->ID()
280 280
         ) {
281 281
             return;
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
         $model              = $this->get_model();
284 284
         $this->_has_changes = true;
285 285
         $field_obj          = $model->field_settings_for($field_name);
286
-        if (! $field_obj instanceof EE_Model_Field_Base) {
286
+        if ( ! $field_obj instanceof EE_Model_Field_Base) {
287 287
             throw new EE_Error(
288 288
                 sprintf(
289 289
                     esc_html__(
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
             ? $field_obj->get_default_value()
307 307
             : $field_value;
308 308
 
309
-        $this->_fields[ $field_name ] = $field_obj->prepare_for_set($value);
309
+        $this->_fields[$field_name] = $field_obj->prepare_for_set($value);
310 310
 
311 311
         // if we're not in the constructor...
312 312
         // now check if what we set was a primary key
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
             } else {
369 369
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
370 370
             }
371
-            $this->_fields[ $field_name ] = $field_value;
371
+            $this->_fields[$field_name] = $field_value;
372 372
             $this->_clear_cached_property($field_name);
373 373
         }
374 374
     }
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
      */
395 395
     public function getCustomSelect($alias)
396 396
     {
397
-        return $this->custom_selection_results[ $alias ] ?? null;
397
+        return $this->custom_selection_results[$alias] ?? null;
398 398
     }
399 399
 
400 400
 
@@ -481,8 +481,8 @@  discard block
 block discarded – undo
481 481
         foreach ($model_fields as $field_name => $field_obj) {
482 482
             if ($field_obj instanceof EE_Datetime_Field) {
483 483
                 $field_obj->set_timezone($this->_timezone);
484
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
485
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
485
+                    EEH_DTT_Helper::setTimezone($this->_fields[$field_name], new DateTimeZone($this->_timezone));
486 486
                 }
487 487
             }
488 488
         }
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
      */
541 541
     public function get_format($full = true)
542 542
     {
543
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
543
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
544 544
     }
545 545
 
546 546
 
@@ -566,11 +566,11 @@  discard block
 block discarded – undo
566 566
     public function cache($relation_name = '', $object_to_cache = null, $cache_id = null)
567 567
     {
568 568
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
569
-        if (! $object_to_cache instanceof EE_Base_Class) {
569
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
570 570
             return false;
571 571
         }
572 572
         // also get "how" the object is related, or throw an error
573
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
573
+        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
574 574
             throw new EE_Error(
575 575
                 sprintf(
576 576
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -584,38 +584,38 @@  discard block
 block discarded – undo
584 584
             // if it's a "belongs to" relationship, then there's only one related model object
585 585
             // eg, if this is a registration, there's only 1 attendee for it
586 586
             // so for these model objects just set it to be cached
587
-            $this->_model_relations[ $relation_name ] = $object_to_cache;
587
+            $this->_model_relations[$relation_name] = $object_to_cache;
588 588
             $return                                   = true;
589 589
         } else {
590 590
             // otherwise, this is the "many" side of a one to many relationship,
591 591
             // so we'll add the object to the array of related objects for that type.
592 592
             // eg: if this is an event, there are many registrations for that event,
593 593
             // so we cache the registrations in an array
594
-            if (! is_array($this->_model_relations[ $relation_name ])) {
594
+            if ( ! is_array($this->_model_relations[$relation_name])) {
595 595
                 // if for some reason, the cached item is a model object,
596 596
                 // then stick that in the array, otherwise start with an empty array
597
-                $this->_model_relations[ $relation_name ] =
598
-                    $this->_model_relations[ $relation_name ] instanceof EE_Base_Class
599
-                        ? [$this->_model_relations[ $relation_name ]]
597
+                $this->_model_relations[$relation_name] =
598
+                    $this->_model_relations[$relation_name] instanceof EE_Base_Class
599
+                        ? [$this->_model_relations[$relation_name]]
600 600
                         : [];
601 601
             }
602 602
             // first check for a cache_id which is normally empty
603
-            if (! empty($cache_id)) {
603
+            if ( ! empty($cache_id)) {
604 604
                 // if the cache_id exists, then it means we are purposely trying to cache this
605 605
                 // with a known key that can then be used to retrieve the object later on
606
-                $this->_model_relations[ $relation_name ][ $cache_id ] = $object_to_cache;
606
+                $this->_model_relations[$relation_name][$cache_id] = $object_to_cache;
607 607
                 $return                                                = $cache_id;
608 608
             } elseif ($object_to_cache->ID()) {
609 609
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
610
-                $this->_model_relations[ $relation_name ][ $object_to_cache->ID() ] = $object_to_cache;
610
+                $this->_model_relations[$relation_name][$object_to_cache->ID()] = $object_to_cache;
611 611
                 $return                                                             = $object_to_cache->ID();
612 612
             } else {
613 613
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
614
-                $this->_model_relations[ $relation_name ][] = $object_to_cache;
614
+                $this->_model_relations[$relation_name][] = $object_to_cache;
615 615
                 // move the internal pointer to the end of the array
616
-                end($this->_model_relations[ $relation_name ]);
616
+                end($this->_model_relations[$relation_name]);
617 617
                 // and grab the key so that we can return it
618
-                $return = key($this->_model_relations[ $relation_name ]);
618
+                $return = key($this->_model_relations[$relation_name]);
619 619
             }
620 620
         }
621 621
         return $return;
@@ -642,7 +642,7 @@  discard block
 block discarded – undo
642 642
         $this->get_model()->field_settings_for($fieldname);
643 643
         $cache_type = empty($cache_type) ? 'standard' : $cache_type;
644 644
 
645
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
645
+        $this->_cached_properties[$fieldname][$cache_type] = $value;
646 646
     }
647 647
 
648 648
 
@@ -671,9 +671,9 @@  discard block
 block discarded – undo
671 671
         $model = $this->get_model();
672 672
         $model->field_settings_for($fieldname);
673 673
         $cache_type = $pretty ? 'pretty' : 'standard';
674
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
675
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
676
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
675
+        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
676
+            return $this->_cached_properties[$fieldname][$cache_type];
677 677
         }
678 678
         $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
679 679
         $this->_set_cached_property($fieldname, $value, $cache_type);
@@ -701,12 +701,12 @@  discard block
 block discarded – undo
701 701
         if ($field_obj instanceof EE_Datetime_Field) {
702 702
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
703 703
         }
704
-        if (! isset($this->_fields[ $fieldname ])) {
705
-            $this->_fields[ $fieldname ] = null;
704
+        if ( ! isset($this->_fields[$fieldname])) {
705
+            $this->_fields[$fieldname] = null;
706 706
         }
707 707
         return $pretty
708
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
709
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
708
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
709
+            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
710 710
     }
711 711
 
712 712
 
@@ -762,8 +762,8 @@  discard block
 block discarded – undo
762 762
      */
763 763
     protected function _clear_cached_property($property_name)
764 764
     {
765
-        if (isset($this->_cached_properties[ $property_name ])) {
766
-            unset($this->_cached_properties[ $property_name ]);
765
+        if (isset($this->_cached_properties[$property_name])) {
766
+            unset($this->_cached_properties[$property_name]);
767 767
         }
768 768
     }
769 769
 
@@ -815,7 +815,7 @@  discard block
 block discarded – undo
815 815
     {
816 816
         $relationship_to_model = $this->get_model()->related_settings_for($relation_name);
817 817
         $index_in_cache        = '';
818
-        if (! $relationship_to_model) {
818
+        if ( ! $relationship_to_model) {
819 819
             throw new EE_Error(
820 820
                 sprintf(
821 821
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -826,10 +826,10 @@  discard block
 block discarded – undo
826 826
         }
827 827
         if ($clear_all) {
828 828
             $obj_removed                              = true;
829
-            $this->_model_relations[ $relation_name ] = null;
829
+            $this->_model_relations[$relation_name] = null;
830 830
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
831
-            $obj_removed                              = $this->_model_relations[ $relation_name ];
832
-            $this->_model_relations[ $relation_name ] = null;
831
+            $obj_removed                              = $this->_model_relations[$relation_name];
832
+            $this->_model_relations[$relation_name] = null;
833 833
         } else {
834 834
             if (
835 835
                 $object_to_remove_or_index_into_array instanceof EE_Base_Class
@@ -837,12 +837,12 @@  discard block
 block discarded – undo
837 837
             ) {
838 838
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
839 839
                 if (
840
-                    is_array($this->_model_relations[ $relation_name ])
841
-                    && ! isset($this->_model_relations[ $relation_name ][ $index_in_cache ])
840
+                    is_array($this->_model_relations[$relation_name])
841
+                    && ! isset($this->_model_relations[$relation_name][$index_in_cache])
842 842
                 ) {
843 843
                     $index_found_at = null;
844 844
                     // find this object in the array even though it has a different key
845
-                    foreach ($this->_model_relations[ $relation_name ] as $index => $obj) {
845
+                    foreach ($this->_model_relations[$relation_name] as $index => $obj) {
846 846
                         /** @noinspection TypeUnsafeComparisonInspection */
847 847
                         if (
848 848
                             $obj instanceof EE_Base_Class
@@ -876,9 +876,9 @@  discard block
 block discarded – undo
876 876
             }
877 877
             // supposedly we've found it. But it could just be that the client code
878 878
             // provided a bad index/object
879
-            if (isset($this->_model_relations[ $relation_name ][ $index_in_cache ])) {
880
-                $obj_removed = $this->_model_relations[ $relation_name ][ $index_in_cache ];
881
-                unset($this->_model_relations[ $relation_name ][ $index_in_cache ]);
879
+            if (isset($this->_model_relations[$relation_name][$index_in_cache])) {
880
+                $obj_removed = $this->_model_relations[$relation_name][$index_in_cache];
881
+                unset($this->_model_relations[$relation_name][$index_in_cache]);
882 882
             } else {
883 883
                 // that thing was never cached anyways.
884 884
                 $obj_removed = null;
@@ -909,7 +909,7 @@  discard block
 block discarded – undo
909 909
         $current_cache_id = ''
910 910
     ) {
911 911
         // verify that incoming object is of the correct type
912
-        $obj_class = 'EE_' . $relation_name;
912
+        $obj_class = 'EE_'.$relation_name;
913 913
         if ($newly_saved_object instanceof $obj_class) {
914 914
             /* @type EE_Base_Class $newly_saved_object */
915 915
             // now get the type of relation
@@ -917,18 +917,18 @@  discard block
 block discarded – undo
917 917
             // if this is a 1:1 relationship
918 918
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
919 919
                 // then just replace the cached object with the newly saved object
920
-                $this->_model_relations[ $relation_name ] = $newly_saved_object;
920
+                $this->_model_relations[$relation_name] = $newly_saved_object;
921 921
                 return true;
922 922
                 // or if it's some kind of sordid feral polyamorous relationship...
923 923
             }
924 924
             if (
925
-                is_array($this->_model_relations[ $relation_name ])
926
-                && isset($this->_model_relations[ $relation_name ][ $current_cache_id ])
925
+                is_array($this->_model_relations[$relation_name])
926
+                && isset($this->_model_relations[$relation_name][$current_cache_id])
927 927
             ) {
928 928
                 // then remove the current cached item
929
-                unset($this->_model_relations[ $relation_name ][ $current_cache_id ]);
929
+                unset($this->_model_relations[$relation_name][$current_cache_id]);
930 930
                 // and cache the newly saved object using it's new ID
931
-                $this->_model_relations[ $relation_name ][ $newly_saved_object->ID() ] = $newly_saved_object;
931
+                $this->_model_relations[$relation_name][$newly_saved_object->ID()] = $newly_saved_object;
932 932
                 return true;
933 933
             }
934 934
         }
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
      */
946 946
     public function get_one_from_cache($relation_name)
947 947
     {
948
-        $cached_array_or_object = $this->_model_relations[ $relation_name ] ?? null;
948
+        $cached_array_or_object = $this->_model_relations[$relation_name] ?? null;
949 949
         if (is_array($cached_array_or_object)) {
950 950
             return array_shift($cached_array_or_object);
951 951
         }
@@ -967,7 +967,7 @@  discard block
 block discarded – undo
967 967
      */
968 968
     public function get_all_from_cache($relation_name)
969 969
     {
970
-        $objects = $this->_model_relations[ $relation_name ] ?? [];
970
+        $objects = $this->_model_relations[$relation_name] ?? [];
971 971
         // if the result is not an array, but exists, make it an array
972 972
         $objects = is_array($objects)
973 973
             ? $objects
@@ -1159,9 +1159,9 @@  discard block
 block discarded – undo
1159 1159
     public function get_raw($field_name)
1160 1160
     {
1161 1161
         $field_settings = $this->get_model()->field_settings_for($field_name);
1162
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1163
-            ? $this->_fields[ $field_name ]->format('U')
1164
-            : $this->_fields[ $field_name ];
1162
+        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1163
+            ? $this->_fields[$field_name]->format('U')
1164
+            : $this->_fields[$field_name];
1165 1165
     }
1166 1166
 
1167 1167
 
@@ -1183,7 +1183,7 @@  discard block
 block discarded – undo
1183 1183
     public function get_DateTime_object($field_name)
1184 1184
     {
1185 1185
         $field_settings = $this->get_model()->field_settings_for($field_name);
1186
-        if (! $field_settings instanceof EE_Datetime_Field) {
1186
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1187 1187
             EE_Error::add_error(
1188 1188
                 sprintf(
1189 1189
                     esc_html__(
@@ -1198,8 +1198,8 @@  discard block
 block discarded – undo
1198 1198
             );
1199 1199
             return false;
1200 1200
         }
1201
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1202
-            ? clone $this->_fields[ $field_name ]
1201
+        return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1202
+            ? clone $this->_fields[$field_name]
1203 1203
             : null;
1204 1204
     }
1205 1205
 
@@ -1444,7 +1444,7 @@  discard block
 block discarded – undo
1444 1444
      */
1445 1445
     public function get_i18n_datetime(string $field_name, string $format = ''): string
1446 1446
     {
1447
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1447
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1448 1448
         return date_i18n(
1449 1449
             $format,
1450 1450
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -1556,21 +1556,21 @@  discard block
 block discarded – undo
1556 1556
         $field->set_time_format($this->_tm_frmt);
1557 1557
         switch ($what) {
1558 1558
             case 'T':
1559
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1559
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_time(
1560 1560
                     $datetime_value,
1561
-                    $this->_fields[ $field_name ]
1561
+                    $this->_fields[$field_name]
1562 1562
                 );
1563 1563
                 $this->_has_changes           = true;
1564 1564
                 break;
1565 1565
             case 'D':
1566
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1566
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_date(
1567 1567
                     $datetime_value,
1568
-                    $this->_fields[ $field_name ]
1568
+                    $this->_fields[$field_name]
1569 1569
                 );
1570 1570
                 $this->_has_changes           = true;
1571 1571
                 break;
1572 1572
             case 'B':
1573
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1573
+                $this->_fields[$field_name] = $field->prepare_for_set($datetime_value);
1574 1574
                 $this->_has_changes           = true;
1575 1575
                 break;
1576 1576
         }
@@ -1613,7 +1613,7 @@  discard block
 block discarded – undo
1613 1613
         $this->set_timezone($timezone);
1614 1614
         $fn   = (array) $field_name;
1615 1615
         $args = array_merge($fn, (array) $args);
1616
-        if (! method_exists($this, $callback)) {
1616
+        if ( ! method_exists($this, $callback)) {
1617 1617
             throw new EE_Error(
1618 1618
                 sprintf(
1619 1619
                     esc_html__(
@@ -1625,7 +1625,7 @@  discard block
 block discarded – undo
1625 1625
             );
1626 1626
         }
1627 1627
         $args   = (array) $args;
1628
-        $return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
1628
+        $return = $prepend.call_user_func_array([$this, $callback], $args).$append;
1629 1629
         $this->set_timezone($original_timezone);
1630 1630
         return $return;
1631 1631
     }
@@ -1740,8 +1740,8 @@  discard block
 block discarded – undo
1740 1740
     {
1741 1741
         $model = $this->get_model();
1742 1742
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1743
-            if (! empty($this->_model_relations[ $relation_name ])) {
1744
-                $related_objects = $this->_model_relations[ $relation_name ];
1743
+            if ( ! empty($this->_model_relations[$relation_name])) {
1744
+                $related_objects = $this->_model_relations[$relation_name];
1745 1745
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
1746 1746
                     // this relation only stores a single model object, not an array
1747 1747
                     // but let's make it consistent
@@ -1798,7 +1798,7 @@  discard block
 block discarded – undo
1798 1798
             $this->set($column, $value);
1799 1799
         }
1800 1800
         // no changes ? then don't do anything
1801
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1801
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1802 1802
             return 0;
1803 1803
         }
1804 1804
         /**
@@ -1808,7 +1808,7 @@  discard block
 block discarded – undo
1808 1808
          * @param EE_Base_Class $model_object the model object about to be saved.
1809 1809
          */
1810 1810
         do_action('AHEE__EE_Base_Class__save__begin', $this);
1811
-        if (! $this->allow_persist()) {
1811
+        if ( ! $this->allow_persist()) {
1812 1812
             return 0;
1813 1813
         }
1814 1814
         // now get current attribute values
@@ -1823,10 +1823,10 @@  discard block
 block discarded – undo
1823 1823
         if ($model->has_primary_key_field()) {
1824 1824
             if ($model->get_primary_key_field()->is_auto_increment()) {
1825 1825
                 // ok check if it's set, if so: update; if not, insert
1826
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1826
+                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1827 1827
                     $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1828 1828
                 } else {
1829
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1829
+                    unset($save_cols_n_values[$model->primary_key_name()]);
1830 1830
                     $results = $model->insert($save_cols_n_values);
1831 1831
                     if ($results) {
1832 1832
                         // if successful, set the primary key
@@ -1836,7 +1836,7 @@  discard block
 block discarded – undo
1836 1836
                         // will get added to the mapper before we can add this one!
1837 1837
                         // but if we just avoid using the SET method, all that headache can be avoided
1838 1838
                         $pk_field_name                   = $model->primary_key_name();
1839
-                        $this->_fields[ $pk_field_name ] = $results;
1839
+                        $this->_fields[$pk_field_name] = $results;
1840 1840
                         $this->_clear_cached_property($pk_field_name);
1841 1841
                         $model->add_to_entity_map($this);
1842 1842
                         $this->_update_cached_related_model_objs_fks();
@@ -1853,8 +1853,8 @@  discard block
 block discarded – undo
1853 1853
                                     'event_espresso'
1854 1854
                                 ),
1855 1855
                                 get_class($this),
1856
-                                get_class($model) . '::instance()->add_to_entity_map()',
1857
-                                get_class($model) . '::instance()->get_one_by_ID()',
1856
+                                get_class($model).'::instance()->add_to_entity_map()',
1857
+                                get_class($model).'::instance()->get_one_by_ID()',
1858 1858
                                 '<br />'
1859 1859
                             )
1860 1860
                         );
@@ -1878,7 +1878,7 @@  discard block
 block discarded – undo
1878 1878
                     $save_cols_n_values,
1879 1879
                     $model->get_combined_primary_key_fields()
1880 1880
                 );
1881
-                $results                     = $model->update(
1881
+                $results = $model->update(
1882 1882
                     $save_cols_n_values,
1883 1883
                     $combined_pk_fields_n_values
1884 1884
                 );
@@ -1956,27 +1956,27 @@  discard block
 block discarded – undo
1956 1956
     public function save_new_cached_related_model_objs()
1957 1957
     {
1958 1958
         // make sure this has been saved
1959
-        if (! $this->ID()) {
1959
+        if ( ! $this->ID()) {
1960 1960
             $id = $this->save();
1961 1961
         } else {
1962 1962
             $id = $this->ID();
1963 1963
         }
1964 1964
         // now save all the NEW cached model objects  (ie they don't exist in the DB)
1965 1965
         foreach ($this->get_model()->relation_settings() as $relation_name => $relationObj) {
1966
-            if ($this->_model_relations[ $relation_name ]) {
1966
+            if ($this->_model_relations[$relation_name]) {
1967 1967
                 // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1968 1968
                 // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1969 1969
                 /* @var $related_model_obj EE_Base_Class */
1970 1970
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
1971 1971
                     // add a relation to that relation type (which saves the appropriate thing in the process)
1972 1972
                     // but ONLY if it DOES NOT exist in the DB
1973
-                    $related_model_obj = $this->_model_relations[ $relation_name ];
1973
+                    $related_model_obj = $this->_model_relations[$relation_name];
1974 1974
                     // if( ! $related_model_obj->ID()){
1975 1975
                     $this->_add_relation_to($related_model_obj, $relation_name);
1976 1976
                     $related_model_obj->save_new_cached_related_model_objs();
1977 1977
                     // }
1978 1978
                 } else {
1979
-                    foreach ($this->_model_relations[ $relation_name ] as $related_model_obj) {
1979
+                    foreach ($this->_model_relations[$relation_name] as $related_model_obj) {
1980 1980
                         // add a relation to that relation type (which saves the appropriate thing in the process)
1981 1981
                         // but ONLY if it DOES NOT exist in the DB
1982 1982
                         // if( ! $related_model_obj->ID()){
@@ -2003,7 +2003,7 @@  discard block
 block discarded – undo
2003 2003
      */
2004 2004
     public function get_model()
2005 2005
     {
2006
-        if (! $this->_model) {
2006
+        if ( ! $this->_model) {
2007 2007
             $modelName    = self::_get_model_classname(get_class($this));
2008 2008
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2009 2009
         } else {
@@ -2029,9 +2029,9 @@  discard block
 block discarded – undo
2029 2029
         $primary_id_ref = self::_get_primary_key_name($classname);
2030 2030
         if (
2031 2031
             array_key_exists($primary_id_ref, $props_n_values)
2032
-            && ! empty($props_n_values[ $primary_id_ref ])
2032
+            && ! empty($props_n_values[$primary_id_ref])
2033 2033
         ) {
2034
-            $id = $props_n_values[ $primary_id_ref ];
2034
+            $id = $props_n_values[$primary_id_ref];
2035 2035
             return self::_get_model($classname)->get_from_entity_map($id);
2036 2036
         }
2037 2037
         return false;
@@ -2064,10 +2064,10 @@  discard block
 block discarded – undo
2064 2064
             $primary_id_ref = self::_get_primary_key_name($classname);
2065 2065
             if (
2066 2066
                 array_key_exists($primary_id_ref, $props_n_values)
2067
-                && ! empty($props_n_values[ $primary_id_ref ])
2067
+                && ! empty($props_n_values[$primary_id_ref])
2068 2068
             ) {
2069 2069
                 $existing = $model->get_one_by_ID(
2070
-                    $props_n_values[ $primary_id_ref ]
2070
+                    $props_n_values[$primary_id_ref]
2071 2071
                 );
2072 2072
             }
2073 2073
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -2079,7 +2079,7 @@  discard block
 block discarded – undo
2079 2079
         }
2080 2080
         if ($existing) {
2081 2081
             // set date formats if present before setting values
2082
-            if (! empty($date_formats) && is_array($date_formats)) {
2082
+            if ( ! empty($date_formats) && is_array($date_formats)) {
2083 2083
                 $existing->set_date_format($date_formats[0]);
2084 2084
                 $existing->set_time_format($date_formats[1]);
2085 2085
             } else {
@@ -2112,7 +2112,7 @@  discard block
 block discarded – undo
2112 2112
     protected static function _get_model($classname, $timezone = '')
2113 2113
     {
2114 2114
         // find model for this class
2115
-        if (! $classname) {
2115
+        if ( ! $classname) {
2116 2116
             throw new EE_Error(
2117 2117
                 sprintf(
2118 2118
                     esc_html__(
@@ -2160,7 +2160,7 @@  discard block
 block discarded – undo
2160 2160
     {
2161 2161
         return strpos((string) $model_name, 'EE_') === 0
2162 2162
             ? str_replace('EE_', 'EEM_', $model_name)
2163
-            : 'EEM_' . $model_name;
2163
+            : 'EEM_'.$model_name;
2164 2164
     }
2165 2165
 
2166 2166
 
@@ -2177,7 +2177,7 @@  discard block
 block discarded – undo
2177 2177
      */
2178 2178
     protected static function _get_primary_key_name($classname = null)
2179 2179
     {
2180
-        if (! $classname) {
2180
+        if ( ! $classname) {
2181 2181
             throw new EE_Error(
2182 2182
                 sprintf(
2183 2183
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -2207,7 +2207,7 @@  discard block
 block discarded – undo
2207 2207
         $model = $this->get_model();
2208 2208
         // now that we know the name of the variable, use a variable variable to get its value and return its
2209 2209
         if ($model->has_primary_key_field()) {
2210
-            return $this->_fields[ $model->primary_key_name() ];
2210
+            return $this->_fields[$model->primary_key_name()];
2211 2211
         }
2212 2212
         return $model->get_index_primary_key_string($this->_fields);
2213 2213
     }
@@ -2281,7 +2281,7 @@  discard block
 block discarded – undo
2281 2281
             }
2282 2282
         } else {
2283 2283
             // this thing doesn't exist in the DB,  so just cache it
2284
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2284
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2285 2285
                 throw new EE_Error(
2286 2286
                     sprintf(
2287 2287
                         esc_html__(
@@ -2448,7 +2448,7 @@  discard block
 block discarded – undo
2448 2448
             } else {
2449 2449
                 // did we already cache the result of this query?
2450 2450
                 $cached_results = $this->get_all_from_cache($relation_name);
2451
-                if (! $cached_results) {
2451
+                if ( ! $cached_results) {
2452 2452
                     $related_model_objects = $this->get_model()->get_all_related(
2453 2453
                         $this,
2454 2454
                         $relation_name,
@@ -2560,7 +2560,7 @@  discard block
 block discarded – undo
2560 2560
             } else {
2561 2561
                 // first, check if we've already cached the result of this query
2562 2562
                 $cached_result = $this->get_one_from_cache($relation_name);
2563
-                if (! $cached_result) {
2563
+                if ( ! $cached_result) {
2564 2564
                     $related_model_object = $model->get_first_related(
2565 2565
                         $this,
2566 2566
                         $relation_name,
@@ -2584,7 +2584,7 @@  discard block
 block discarded – undo
2584 2584
             }
2585 2585
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2586 2586
             // just get what's cached on this object
2587
-            if (! $related_model_object) {
2587
+            if ( ! $related_model_object) {
2588 2588
                 $related_model_object = $this->get_one_from_cache($relation_name);
2589 2589
             }
2590 2590
         }
@@ -2667,7 +2667,7 @@  discard block
 block discarded – undo
2667 2667
      */
2668 2668
     public function is_set($field_name)
2669 2669
     {
2670
-        return isset($this->_fields[ $field_name ]);
2670
+        return isset($this->_fields[$field_name]);
2671 2671
     }
2672 2672
 
2673 2673
 
@@ -2683,7 +2683,7 @@  discard block
 block discarded – undo
2683 2683
     {
2684 2684
         foreach ((array) $properties as $property_name) {
2685 2685
             // first make sure this property exists
2686
-            if (! $this->_fields[ $property_name ]) {
2686
+            if ( ! $this->_fields[$property_name]) {
2687 2687
                 throw new EE_Error(
2688 2688
                     sprintf(
2689 2689
                         esc_html__(
@@ -2715,7 +2715,7 @@  discard block
 block discarded – undo
2715 2715
         $properties = [];
2716 2716
         // remove prepended underscore
2717 2717
         foreach ($fields as $field_name => $settings) {
2718
-            $properties[ $field_name ] = $this->get($field_name);
2718
+            $properties[$field_name] = $this->get($field_name);
2719 2719
         }
2720 2720
         return $properties;
2721 2721
     }
@@ -2752,7 +2752,7 @@  discard block
 block discarded – undo
2752 2752
     {
2753 2753
         $className = get_class($this);
2754 2754
         $tagName   = "FHEE__{$className}__{$methodName}";
2755
-        if (! has_filter($tagName)) {
2755
+        if ( ! has_filter($tagName)) {
2756 2756
             throw new EE_Error(
2757 2757
                 sprintf(
2758 2758
                     esc_html__(
@@ -2797,7 +2797,7 @@  discard block
 block discarded – undo
2797 2797
             $query_params[0]['EXM_value'] = $meta_value;
2798 2798
         }
2799 2799
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2800
-        if (! $existing_rows_like_that) {
2800
+        if ( ! $existing_rows_like_that) {
2801 2801
             return $this->add_extra_meta($meta_key, $meta_value);
2802 2802
         }
2803 2803
         foreach ($existing_rows_like_that as $existing_row) {
@@ -2907,7 +2907,7 @@  discard block
 block discarded – undo
2907 2907
                 $values = [];
2908 2908
                 foreach ($results as $result) {
2909 2909
                     if ($result instanceof EE_Extra_Meta) {
2910
-                        $values[ $result->ID() ] = $result->value();
2910
+                        $values[$result->ID()] = $result->value();
2911 2911
                     }
2912 2912
                 }
2913 2913
                 return $values;
@@ -2952,17 +2952,17 @@  discard block
 block discarded – undo
2952 2952
             );
2953 2953
             foreach ($extra_meta_objs as $extra_meta_obj) {
2954 2954
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2955
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2955
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2956 2956
                 }
2957 2957
             }
2958 2958
         } else {
2959 2959
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
2960 2960
             foreach ($extra_meta_objs as $extra_meta_obj) {
2961 2961
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2962
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2963
-                        $return_array[ $extra_meta_obj->key() ] = [];
2962
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2963
+                        $return_array[$extra_meta_obj->key()] = [];
2964 2964
                     }
2965
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2965
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2966 2966
                 }
2967 2967
             }
2968 2968
         }
@@ -3043,8 +3043,8 @@  discard block
 block discarded – undo
3043 3043
                             'event_espresso'
3044 3044
                         ),
3045 3045
                         $this->ID(),
3046
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3047
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3046
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
3047
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
3048 3048
                     )
3049 3049
                 );
3050 3050
             }
@@ -3077,7 +3077,7 @@  discard block
 block discarded – undo
3077 3077
     {
3078 3078
         // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3079 3079
         // if it wasn't even there to start off.
3080
-        if (! $this->ID()) {
3080
+        if ( ! $this->ID()) {
3081 3081
             $this->save();
3082 3082
         }
3083 3083
         global $wpdb;
@@ -3117,7 +3117,7 @@  discard block
 block discarded – undo
3117 3117
             $table_pk_field_name = $table_obj->get_pk_column();
3118 3118
         }
3119 3119
 
3120
-        $query  =
3120
+        $query =
3121 3121
             "UPDATE `{$table_name}`
3122 3122
             SET "
3123 3123
             . $new_value_sql
@@ -3311,7 +3311,7 @@  discard block
 block discarded – undo
3311 3311
         $model = $this->get_model();
3312 3312
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3313 3313
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3314
-                $classname = 'EE_' . $model->get_this_model_name();
3314
+                $classname = 'EE_'.$model->get_this_model_name();
3315 3315
                 if (
3316 3316
                     $this->get_one_from_cache($relation_name) instanceof $classname
3317 3317
                     && $this->get_one_from_cache($relation_name)->ID()
@@ -3352,7 +3352,7 @@  discard block
 block discarded – undo
3352 3352
         // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3353 3353
         foreach ($this->_fields as $field => $value) {
3354 3354
             if ($value instanceof DateTime) {
3355
-                $this->_fields[ $field ] = clone $value;
3355
+                $this->_fields[$field] = clone $value;
3356 3356
             }
3357 3357
         }
3358 3358
     }
@@ -3367,7 +3367,7 @@  discard block
 block discarded – undo
3367 3367
 
3368 3368
     private function echoProperty($field, $value, int $indent = 0)
3369 3369
     {
3370
-        $bullets = str_repeat(' -', $indent) . ' ';
3370
+        $bullets = str_repeat(' -', $indent).' ';
3371 3371
         $field = strpos($field, '_') === 0 ? substr($field, 1) : $field;
3372 3372
         echo "\n$bullets$field: ";
3373 3373
         if ($value instanceof EEM_Base) {
Please login to merge, or discard this patch.
core/db_classes/EE_Attendee.class.php 2 patches
Indentation   +745 added lines, -745 removed lines patch added patch discarded remove patch
@@ -15,749 +15,749 @@
 block discarded – undo
15 15
  */
16 16
 class EE_Attendee extends EE_CPT_Base implements EEI_Contact, AddressInterface, EEI_Admin_Links, EEI_Attendee
17 17
 {
18
-    /**
19
-     * Sets some dynamic defaults
20
-     *
21
-     * @param array  $fieldValues
22
-     * @param bool   $bydb
23
-     * @param string $timezone
24
-     * @param array  $date_formats
25
-     * @throws EE_Error
26
-     * @throws ReflectionException
27
-     */
28
-    protected function __construct($fieldValues = null, $bydb = false, $timezone = '', $date_formats = [])
29
-    {
30
-        if (! isset($fieldValues['ATT_full_name'])) {
31
-            $fname                        = $fieldValues['ATT_fname'] ?? '';
32
-            $lname                        = $fieldValues['ATT_lname'] ?? '';
33
-            $fieldValues['ATT_full_name'] = "$fname $lname";
34
-        }
35
-        if (! isset($fieldValues['ATT_slug'])) {
36
-            // $fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
37
-            $fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
38
-        }
39
-        if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
40
-            $fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
41
-        }
42
-        parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
43
-    }
44
-
45
-
46
-    /**
47
-     * @param array       $props_n_values     incoming values
48
-     * @param string|null $timezone           incoming timezone (if not set the timezone set for the website
49
-     *                                        will be
50
-     *                                        used.)
51
-     * @param array       $date_formats       incoming date_formats in an array where the first value is the
52
-     *                                        date_format and the second value is the time format
53
-     * @return EE_Attendee
54
-     * @throws EE_Error
55
-     * @throws ReflectionException
56
-     */
57
-    public static function new_instance(
58
-        array $props_n_values = [],
59
-        ?string $timezone = '',
60
-        array $date_formats = []
61
-    ): EE_Attendee {
62
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
63
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
64
-    }
65
-
66
-
67
-    /**
68
-     * @param array       $props_n_values incoming values from the database
69
-     * @param string|null $timezone       incoming timezone as set by the model.
70
-     *                                    If not set, the timezone for the website will be used.
71
-     * @return EE_Attendee
72
-     * @throws EE_Error
73
-     * @throws ReflectionException
74
-     */
75
-    public static function new_instance_from_db(array $props_n_values = [], ?string $timezone = ''): EE_Attendee
76
-    {
77
-        return new self($props_n_values, true, $timezone);
78
-    }
79
-
80
-
81
-    /**
82
-     * @param string|null $fname
83
-     * @throws EE_Error
84
-     * @throws ReflectionException
85
-     */
86
-    public function set_fname(?string $fname = '')
87
-    {
88
-        $this->set('ATT_fname', (string) $fname);
89
-    }
90
-
91
-
92
-    /**
93
-     * @param string|null $lname
94
-     * @throws EE_Error
95
-     * @throws ReflectionException
96
-     */
97
-    public function set_lname(?string $lname = '')
98
-    {
99
-        $this->set('ATT_lname', (string) $lname);
100
-    }
101
-
102
-
103
-    /**
104
-     * @param string|null $address
105
-     * @throws EE_Error
106
-     * @throws ReflectionException
107
-     */
108
-    public function set_address(?string $address = '')
109
-    {
110
-        $this->set('ATT_address', (string) $address);
111
-    }
112
-
113
-
114
-    /**
115
-     * @param string|null $address2
116
-     * @throws EE_Error
117
-     * @throws ReflectionException
118
-     */
119
-    public function set_address2(?string $address2 = '')
120
-    {
121
-        $this->set('ATT_address2', (string) $address2);
122
-    }
123
-
124
-
125
-    /**
126
-     * @param string|null $city
127
-     * @throws EE_Error
128
-     * @throws ReflectionException
129
-     */
130
-    public function set_city(?string $city = '')
131
-    {
132
-        $this->set('ATT_city', $city);
133
-    }
134
-
135
-
136
-    /**
137
-     * @param int|null $STA_ID
138
-     * @throws EE_Error
139
-     * @throws ReflectionException
140
-     */
141
-    public function set_state(?int $STA_ID = 0)
142
-    {
143
-        $this->set('STA_ID', $STA_ID);
144
-    }
145
-
146
-
147
-    /**
148
-     * @param string|null $CNT_ISO
149
-     * @throws EE_Error
150
-     * @throws ReflectionException
151
-     */
152
-    public function set_country(?string $CNT_ISO = '')
153
-    {
154
-        $this->set('CNT_ISO', $CNT_ISO);
155
-    }
156
-
157
-
158
-    /**
159
-     * @param string|null $zip
160
-     * @throws EE_Error
161
-     * @throws ReflectionException
162
-     */
163
-    public function set_zip(?string $zip = '')
164
-    {
165
-        $this->set('ATT_zip', $zip);
166
-    }
167
-
168
-
169
-    /**
170
-     * @param string|null $email
171
-     * @throws EE_Error
172
-     * @throws ReflectionException
173
-     */
174
-    public function set_email(?string $email = '')
175
-    {
176
-        $this->set('ATT_email', $email);
177
-    }
178
-
179
-
180
-    /**
181
-     * @param string|null $phone
182
-     * @throws EE_Error
183
-     * @throws ReflectionException
184
-     */
185
-    public function set_phone(?string $phone = '')
186
-    {
187
-        $this->set('ATT_phone', $phone);
188
-    }
189
-
190
-
191
-    /**
192
-     * @param bool|int|string|null $ATT_deleted
193
-     * @throws EE_Error
194
-     * @throws ReflectionException
195
-     */
196
-    public function set_deleted($ATT_deleted = false)
197
-    {
198
-        $this->set('ATT_deleted', $ATT_deleted);
199
-    }
200
-
201
-
202
-    /**
203
-     * Returns the value for the post_author id saved with the cpt
204
-     *
205
-     * @return int
206
-     * @throws EE_Error
207
-     * @throws ReflectionException
208
-     * @since 4.5.0
209
-     */
210
-    public function wp_user(): int
211
-    {
212
-        return (int) $this->get('ATT_author');
213
-    }
214
-
215
-
216
-    /**
217
-     * @return string
218
-     * @throws EE_Error
219
-     * @throws ReflectionException
220
-     */
221
-    public function fname(): string
222
-    {
223
-        return (string) $this->get('ATT_fname');
224
-    }
225
-
226
-
227
-    /**
228
-     * echoes out the attendee's first name
229
-     *
230
-     * @return void
231
-     * @throws EE_Error
232
-     * @throws ReflectionException
233
-     */
234
-    public function e_full_name()
235
-    {
236
-        echo esc_html($this->full_name());
237
-    }
238
-
239
-
240
-    /**
241
-     * Returns the first and last name concatenated together with a space.
242
-     *
243
-     * @param bool $apply_html_entities
244
-     * @return string
245
-     * @throws EE_Error
246
-     * @throws ReflectionException
247
-     */
248
-    public function full_name(bool $apply_html_entities = false): string
249
-    {
250
-        $full_name = [$this->fname(), $this->lname()];
251
-        $full_name = array_filter($full_name);
252
-        $full_name = implode(' ', $full_name);
253
-        return $apply_html_entities
254
-            ? htmlentities($full_name, ENT_QUOTES, 'UTF-8')
255
-            : $full_name;
256
-    }
257
-
258
-
259
-    /**
260
-     * This returns the value of the `ATT_full_name` field which is usually equivalent to calling `full_name()` unless
261
-     * the post_title field has been directly modified in the db for the post (espresso_attendees post type) for this
262
-     * attendee.
263
-     *
264
-     * @param bool $apply_html_entities
265
-     * @return string
266
-     * @throws EE_Error
267
-     * @throws ReflectionException
268
-     */
269
-    public function ATT_full_name(bool $apply_html_entities = false): string
270
-    {
271
-        return $apply_html_entities
272
-            ? htmlentities((string) $this->get('ATT_full_name'), ENT_QUOTES, 'UTF-8')
273
-            : (string) $this->get('ATT_full_name');
274
-    }
275
-
276
-
277
-    /**
278
-     * @return string
279
-     * @throws EE_Error
280
-     * @throws ReflectionException
281
-     */
282
-    public function lname(): string
283
-    {
284
-        return (string) $this->get('ATT_lname');
285
-    }
286
-
287
-
288
-    /**
289
-     * @return string
290
-     * @throws EE_Error
291
-     * @throws ReflectionException
292
-     */
293
-    public function bio(): string
294
-    {
295
-        return (string) $this->get('ATT_bio');
296
-    }
297
-
298
-
299
-    /**
300
-     * @return string
301
-     * @throws EE_Error
302
-     * @throws ReflectionException
303
-     */
304
-    public function short_bio(): string
305
-    {
306
-        return (string) $this->get('ATT_short_bio');
307
-    }
308
-
309
-
310
-    /**
311
-     * Gets the attendee's full address as an array so client code can decide hwo to display it
312
-     *
313
-     * @return array numerically indexed, with each part of the address that is known.
314
-     * Eg, if the user only responded to state and country,
315
-     * it would be array(0=>'Alabama',1=>'USA')
316
-     * @return array
317
-     * @throws EE_Error
318
-     * @throws ReflectionException
319
-     */
320
-    public function full_address_as_array(): array
321
-    {
322
-        $full_address_array     = [];
323
-        $initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city',];
324
-        foreach ($initial_address_fields as $address_field_name) {
325
-            $address_fields_value = $this->get($address_field_name);
326
-            if (! empty($address_fields_value)) {
327
-                $full_address_array[] = $address_fields_value;
328
-            }
329
-        }
330
-        // now handle state and country
331
-        $state_obj = $this->state_obj();
332
-        if ($state_obj instanceof EE_State) {
333
-            $full_address_array[] = $state_obj->name();
334
-        }
335
-        $country_obj = $this->country_obj();
336
-        if ($country_obj instanceof EE_Country) {
337
-            $full_address_array[] = $country_obj->name();
338
-        }
339
-        // lastly get the xip
340
-        $zip_value = $this->zip();
341
-        if (! empty($zip_value)) {
342
-            $full_address_array[] = $zip_value;
343
-        }
344
-        return $full_address_array;
345
-    }
346
-
347
-
348
-    /**
349
-     * @return string
350
-     * @throws EE_Error
351
-     * @throws ReflectionException
352
-     */
353
-    public function address(): string
354
-    {
355
-        return (string) $this->get('ATT_address');
356
-    }
357
-
358
-
359
-    /**
360
-     * @return string
361
-     * @throws EE_Error
362
-     * @throws ReflectionException
363
-     */
364
-    public function address2(): string
365
-    {
366
-        return (string) $this->get('ATT_address2');
367
-    }
368
-
369
-
370
-    /**
371
-     * @return string
372
-     * @throws EE_Error
373
-     * @throws ReflectionException
374
-     */
375
-    public function city(): string
376
-    {
377
-        return (string) $this->get('ATT_city');
378
-    }
379
-
380
-
381
-    /**
382
-     * @return int
383
-     * @throws EE_Error
384
-     * @throws ReflectionException
385
-     */
386
-    public function state_ID(): int
387
-    {
388
-        return (int) $this->get('STA_ID');
389
-    }
390
-
391
-
392
-    /**
393
-     * @return string
394
-     * @throws EE_Error
395
-     * @throws ReflectionException
396
-     */
397
-    public function state_abbrev(): string
398
-    {
399
-        return $this->state_obj() instanceof EE_State
400
-            ? $this->state_obj()->abbrev()
401
-            : '';
402
-    }
403
-
404
-
405
-    /**
406
-     * @return EE_State|null
407
-     * @throws EE_Error
408
-     * @throws ReflectionException
409
-     */
410
-    public function state_obj(): ?EE_State
411
-    {
412
-        return $this->get_first_related('State');
413
-    }
414
-
415
-
416
-    /**
417
-     * @return string
418
-     * @throws EE_Error
419
-     * @throws ReflectionException
420
-     */
421
-    public function state_name(): string
422
-    {
423
-        return $this->state_obj() instanceof EE_State
424
-            ? $this->state_obj()->name()
425
-            : '';
426
-    }
427
-
428
-
429
-    /**
430
-     * either displays the state abbreviation or the state name, as determined
431
-     * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
432
-     * defaults to abbreviation
433
-     *
434
-     * @return string
435
-     * @throws EE_Error
436
-     * @throws ReflectionException
437
-     */
438
-    public function state(): string
439
-    {
440
-        return apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())
441
-            ? $this->state_abbrev()
442
-            : $this->state_name();
443
-    }
444
-
445
-
446
-    /**
447
-     * @return string
448
-     * @throws EE_Error
449
-     * @throws ReflectionException
450
-     */
451
-    public function country_ID(): string
452
-    {
453
-        return (string) $this->get('CNT_ISO');
454
-    }
455
-
456
-
457
-    /**
458
-     * @return EE_Country|null
459
-     * @throws EE_Error
460
-     * @throws ReflectionException
461
-     */
462
-    public function country_obj(): ?EE_Country
463
-    {
464
-        return $this->get_first_related('Country');
465
-    }
466
-
467
-
468
-    /**
469
-     * @return string
470
-     * @throws EE_Error
471
-     * @throws ReflectionException
472
-     */
473
-    public function country_name(): string
474
-    {
475
-        return $this->country_obj() instanceof EE_Country
476
-            ? $this->country_obj()->name()
477
-            : '';
478
-    }
479
-
480
-
481
-    /**
482
-     * either displays the country ISO2 code or the country name, as determined
483
-     * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
484
-     * defaults to abbreviation
485
-     *
486
-     * @return string
487
-     * @throws EE_Error
488
-     * @throws ReflectionException
489
-     */
490
-    public function country(): string
491
-    {
492
-        return apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())
493
-            ? $this->country_ID()
494
-            : $this->country_name();
495
-    }
496
-
497
-
498
-    /**
499
-     * @return string
500
-     * @throws EE_Error
501
-     * @throws ReflectionException
502
-     */
503
-    public function zip(): string
504
-    {
505
-        return (string) $this->get('ATT_zip');
506
-    }
507
-
508
-
509
-    /**
510
-     * @return string
511
-     * @throws EE_Error
512
-     * @throws ReflectionException
513
-     */
514
-    public function email(): string
515
-    {
516
-        return (string) $this->get('ATT_email');
517
-    }
518
-
519
-
520
-    /**
521
-     * @return string
522
-     * @throws EE_Error
523
-     * @throws ReflectionException
524
-     */
525
-    public function phone(): string
526
-    {
527
-        return (string) $this->get('ATT_phone');
528
-    }
529
-
530
-
531
-    /**
532
-     * @return bool
533
-     * @throws EE_Error
534
-     * @throws ReflectionException
535
-     */
536
-    public function deleted(): bool
537
-    {
538
-        return (bool) $this->get('ATT_deleted');
539
-    }
540
-
541
-
542
-    /**
543
-     * @param array $query_params
544
-     * @return EE_Registration[]
545
-     * @throws EE_Error
546
-     * @throws ReflectionException
547
-     */
548
-    public function get_registrations(array $query_params = []): array
549
-    {
550
-        return $this->get_many_related('Registration', $query_params);
551
-    }
552
-
553
-
554
-    /**
555
-     * Gets the most recent registration of this attendee
556
-     *
557
-     * @return EE_Registration|null
558
-     * @throws EE_Error
559
-     * @throws ReflectionException
560
-     */
561
-    public function get_most_recent_registration(): ?EE_Registration
562
-    {
563
-        return $this->get_first_related('Registration', ['order_by' => ['REG_date' => 'DESC']]);
564
-    }
565
-
566
-
567
-    /**
568
-     * Gets the most recent registration for this attend at this event
569
-     *
570
-     * @param int $event_id
571
-     * @return EE_Registration|null
572
-     * @throws EE_Error
573
-     * @throws ReflectionException
574
-     */
575
-    public function get_most_recent_registration_for_event(int $event_id): ?EE_Registration
576
-    {
577
-        return $this->get_first_related(
578
-            'Registration',
579
-            [['EVT_ID' => $event_id], 'order_by' => ['REG_date' => 'DESC']]
580
-        );
581
-    }
582
-
583
-
584
-    /**
585
-     * returns any events attached to this attendee ($_Event property);
586
-     *
587
-     * @return EE_Event[]
588
-     * @throws EE_Error
589
-     * @throws ReflectionException
590
-     */
591
-    public function events(): array
592
-    {
593
-        return $this->get_many_related('Event');
594
-    }
595
-
596
-
597
-    /**
598
-     * Gets the billing info array where keys match espresso_reg_page_billing_inputs(),
599
-     * and keys are their cleaned values. @param EE_Payment_Method $payment_method the _gateway_name property on the
600
-     * gateway class
601
-     *
602
-     * @return EE_Form_Section_Proper|null
603
-     * @throws EE_Error
604
-     * @throws ReflectionException
605
-     * @see EE_Attendee::save_and_clean_billing_info_for_payment_method() which was used to save the billing info
606
-     */
607
-    public function billing_info_for_payment_method(EE_Payment_Method $payment_method): ?EE_Form_Section_Proper
608
-    {
609
-        $pm_type = $payment_method->type_obj();
610
-        if (! $pm_type instanceof EE_PMT_Base) {
611
-            return null;
612
-        }
613
-        $billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
614
-        if (! $billing_info) {
615
-            return null;
616
-        }
617
-        $billing_form = $pm_type->billing_form();
618
-        if (! $billing_form instanceof EE_Billing_Info_Form) {
619
-            return null;
620
-        }
621
-        // double-check the form isn't totally hidden, in which case pretend there is no form
622
-        $form_totally_hidden = true;
623
-        foreach ($billing_form->inputs_in_subsections() as $input) {
624
-            if (! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
625
-                $form_totally_hidden = false;
626
-                break;
627
-            }
628
-        }
629
-        if ($form_totally_hidden) {
630
-            return null;
631
-        }
632
-        if ($billing_form instanceof EE_Form_Section_Proper) {
633
-            $billing_form->receive_form_submission([$billing_form->name() => $billing_info], false);
634
-        }
635
-
636
-        return $billing_form;
637
-    }
638
-
639
-
640
-    /**
641
-     * Gets the postmeta key that holds this attendee's billing info for the
642
-     * specified payment method
643
-     *
644
-     * @param EE_Payment_Method $payment_method
645
-     * @return string
646
-     * @throws EE_Error
647
-     */
648
-    public function get_billing_info_postmeta_name(EE_Payment_Method $payment_method): string
649
-    {
650
-        return $payment_method->type_obj() instanceof EE_PMT_Base
651
-            ? 'billing_info_' . $payment_method->type_obj()->system_name()
652
-            : '';
653
-    }
654
-
655
-
656
-    /**
657
-     * Saves the billing info to the attendee.
658
-     *
659
-     * @param EE_Billing_Attendee_Info_Form|null $billing_form
660
-     * @param EE_Payment_Method                  $payment_method
661
-     * @return boolean
662
-     * @throws EE_Error
663
-     * @throws ReflectionException
664
-     * @see EE_Attendee::billing_info_for_payment_method() which is used to retrieve it
665
-     */
666
-    public function save_and_clean_billing_info_for_payment_method(
667
-        ?EE_Billing_Attendee_Info_Form $billing_form,
668
-        EE_Payment_Method $payment_method
669
-    ): bool {
670
-        if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
671
-            EE_Error::add_error(
672
-                esc_html__('Cannot save billing info because there is none.', 'event_espresso'),
673
-                __FILE__,
674
-                __FUNCTION__,
675
-                __LINE__
676
-            );
677
-            return false;
678
-        }
679
-        $billing_form->clean_sensitive_data();
680
-        $postmeta_name = $this->get_billing_info_postmeta_name($payment_method);
681
-        $saved_values  = get_post_meta($this->ID(), $postmeta_name);
682
-        $input_values  = $billing_form->input_values(true);
683
-        // Merge the values in case some fields were already saved somewhere.
684
-        if ($saved_values && is_array($saved_values)) {
685
-            // Need a one dimensional array.
686
-            $saved_values = array_merge(...$saved_values);
687
-            $input_values = array_merge($saved_values, $input_values);
688
-        }
689
-        return update_post_meta($this->ID(), $postmeta_name, $input_values);
690
-    }
691
-
692
-
693
-    /**
694
-     * Return the link to the admin details for the object.
695
-     *
696
-     * @return string
697
-     * @throws EE_Error
698
-     * @throws InvalidArgumentException
699
-     * @throws InvalidDataTypeException
700
-     * @throws InvalidInterfaceException
701
-     * @throws ReflectionException
702
-     */
703
-    public function get_admin_details_link(): string
704
-    {
705
-        return $this->get_admin_edit_link();
706
-    }
707
-
708
-
709
-    /**
710
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
711
-     *
712
-     * @return string
713
-     * @throws EE_Error
714
-     * @throws InvalidArgumentException
715
-     * @throws ReflectionException
716
-     * @throws InvalidDataTypeException
717
-     * @throws InvalidInterfaceException
718
-     */
719
-    public function get_admin_edit_link(): string
720
-    {
721
-        return EEH_URL::add_query_args_and_nonce(
722
-            [
723
-                'page'   => 'espresso_registrations',
724
-                'action' => 'edit_attendee',
725
-                'post'   => $this->ID(),
726
-            ],
727
-            admin_url('admin.php')
728
-        );
729
-    }
730
-
731
-
732
-    /**
733
-     * Returns the link to a settings page for the object.
734
-     *
735
-     * @return string
736
-     * @throws EE_Error
737
-     * @throws InvalidArgumentException
738
-     * @throws InvalidDataTypeException
739
-     * @throws InvalidInterfaceException
740
-     * @throws ReflectionException
741
-     */
742
-    public function get_admin_settings_link(): string
743
-    {
744
-        return $this->get_admin_edit_link();
745
-    }
746
-
747
-
748
-    /**
749
-     * Returns the link to the "overview" for the object (typically the "list table" view).
750
-     *
751
-     * @return string
752
-     */
753
-    public function get_admin_overview_link(): string
754
-    {
755
-        return EEH_URL::add_query_args_and_nonce(
756
-            [
757
-                'page'   => 'espresso_registrations',
758
-                'action' => 'contact_list',
759
-            ],
760
-            admin_url('admin.php')
761
-        );
762
-    }
18
+	/**
19
+	 * Sets some dynamic defaults
20
+	 *
21
+	 * @param array  $fieldValues
22
+	 * @param bool   $bydb
23
+	 * @param string $timezone
24
+	 * @param array  $date_formats
25
+	 * @throws EE_Error
26
+	 * @throws ReflectionException
27
+	 */
28
+	protected function __construct($fieldValues = null, $bydb = false, $timezone = '', $date_formats = [])
29
+	{
30
+		if (! isset($fieldValues['ATT_full_name'])) {
31
+			$fname                        = $fieldValues['ATT_fname'] ?? '';
32
+			$lname                        = $fieldValues['ATT_lname'] ?? '';
33
+			$fieldValues['ATT_full_name'] = "$fname $lname";
34
+		}
35
+		if (! isset($fieldValues['ATT_slug'])) {
36
+			// $fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
37
+			$fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
38
+		}
39
+		if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
40
+			$fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
41
+		}
42
+		parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
43
+	}
44
+
45
+
46
+	/**
47
+	 * @param array       $props_n_values     incoming values
48
+	 * @param string|null $timezone           incoming timezone (if not set the timezone set for the website
49
+	 *                                        will be
50
+	 *                                        used.)
51
+	 * @param array       $date_formats       incoming date_formats in an array where the first value is the
52
+	 *                                        date_format and the second value is the time format
53
+	 * @return EE_Attendee
54
+	 * @throws EE_Error
55
+	 * @throws ReflectionException
56
+	 */
57
+	public static function new_instance(
58
+		array $props_n_values = [],
59
+		?string $timezone = '',
60
+		array $date_formats = []
61
+	): EE_Attendee {
62
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
63
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
64
+	}
65
+
66
+
67
+	/**
68
+	 * @param array       $props_n_values incoming values from the database
69
+	 * @param string|null $timezone       incoming timezone as set by the model.
70
+	 *                                    If not set, the timezone for the website will be used.
71
+	 * @return EE_Attendee
72
+	 * @throws EE_Error
73
+	 * @throws ReflectionException
74
+	 */
75
+	public static function new_instance_from_db(array $props_n_values = [], ?string $timezone = ''): EE_Attendee
76
+	{
77
+		return new self($props_n_values, true, $timezone);
78
+	}
79
+
80
+
81
+	/**
82
+	 * @param string|null $fname
83
+	 * @throws EE_Error
84
+	 * @throws ReflectionException
85
+	 */
86
+	public function set_fname(?string $fname = '')
87
+	{
88
+		$this->set('ATT_fname', (string) $fname);
89
+	}
90
+
91
+
92
+	/**
93
+	 * @param string|null $lname
94
+	 * @throws EE_Error
95
+	 * @throws ReflectionException
96
+	 */
97
+	public function set_lname(?string $lname = '')
98
+	{
99
+		$this->set('ATT_lname', (string) $lname);
100
+	}
101
+
102
+
103
+	/**
104
+	 * @param string|null $address
105
+	 * @throws EE_Error
106
+	 * @throws ReflectionException
107
+	 */
108
+	public function set_address(?string $address = '')
109
+	{
110
+		$this->set('ATT_address', (string) $address);
111
+	}
112
+
113
+
114
+	/**
115
+	 * @param string|null $address2
116
+	 * @throws EE_Error
117
+	 * @throws ReflectionException
118
+	 */
119
+	public function set_address2(?string $address2 = '')
120
+	{
121
+		$this->set('ATT_address2', (string) $address2);
122
+	}
123
+
124
+
125
+	/**
126
+	 * @param string|null $city
127
+	 * @throws EE_Error
128
+	 * @throws ReflectionException
129
+	 */
130
+	public function set_city(?string $city = '')
131
+	{
132
+		$this->set('ATT_city', $city);
133
+	}
134
+
135
+
136
+	/**
137
+	 * @param int|null $STA_ID
138
+	 * @throws EE_Error
139
+	 * @throws ReflectionException
140
+	 */
141
+	public function set_state(?int $STA_ID = 0)
142
+	{
143
+		$this->set('STA_ID', $STA_ID);
144
+	}
145
+
146
+
147
+	/**
148
+	 * @param string|null $CNT_ISO
149
+	 * @throws EE_Error
150
+	 * @throws ReflectionException
151
+	 */
152
+	public function set_country(?string $CNT_ISO = '')
153
+	{
154
+		$this->set('CNT_ISO', $CNT_ISO);
155
+	}
156
+
157
+
158
+	/**
159
+	 * @param string|null $zip
160
+	 * @throws EE_Error
161
+	 * @throws ReflectionException
162
+	 */
163
+	public function set_zip(?string $zip = '')
164
+	{
165
+		$this->set('ATT_zip', $zip);
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param string|null $email
171
+	 * @throws EE_Error
172
+	 * @throws ReflectionException
173
+	 */
174
+	public function set_email(?string $email = '')
175
+	{
176
+		$this->set('ATT_email', $email);
177
+	}
178
+
179
+
180
+	/**
181
+	 * @param string|null $phone
182
+	 * @throws EE_Error
183
+	 * @throws ReflectionException
184
+	 */
185
+	public function set_phone(?string $phone = '')
186
+	{
187
+		$this->set('ATT_phone', $phone);
188
+	}
189
+
190
+
191
+	/**
192
+	 * @param bool|int|string|null $ATT_deleted
193
+	 * @throws EE_Error
194
+	 * @throws ReflectionException
195
+	 */
196
+	public function set_deleted($ATT_deleted = false)
197
+	{
198
+		$this->set('ATT_deleted', $ATT_deleted);
199
+	}
200
+
201
+
202
+	/**
203
+	 * Returns the value for the post_author id saved with the cpt
204
+	 *
205
+	 * @return int
206
+	 * @throws EE_Error
207
+	 * @throws ReflectionException
208
+	 * @since 4.5.0
209
+	 */
210
+	public function wp_user(): int
211
+	{
212
+		return (int) $this->get('ATT_author');
213
+	}
214
+
215
+
216
+	/**
217
+	 * @return string
218
+	 * @throws EE_Error
219
+	 * @throws ReflectionException
220
+	 */
221
+	public function fname(): string
222
+	{
223
+		return (string) $this->get('ATT_fname');
224
+	}
225
+
226
+
227
+	/**
228
+	 * echoes out the attendee's first name
229
+	 *
230
+	 * @return void
231
+	 * @throws EE_Error
232
+	 * @throws ReflectionException
233
+	 */
234
+	public function e_full_name()
235
+	{
236
+		echo esc_html($this->full_name());
237
+	}
238
+
239
+
240
+	/**
241
+	 * Returns the first and last name concatenated together with a space.
242
+	 *
243
+	 * @param bool $apply_html_entities
244
+	 * @return string
245
+	 * @throws EE_Error
246
+	 * @throws ReflectionException
247
+	 */
248
+	public function full_name(bool $apply_html_entities = false): string
249
+	{
250
+		$full_name = [$this->fname(), $this->lname()];
251
+		$full_name = array_filter($full_name);
252
+		$full_name = implode(' ', $full_name);
253
+		return $apply_html_entities
254
+			? htmlentities($full_name, ENT_QUOTES, 'UTF-8')
255
+			: $full_name;
256
+	}
257
+
258
+
259
+	/**
260
+	 * This returns the value of the `ATT_full_name` field which is usually equivalent to calling `full_name()` unless
261
+	 * the post_title field has been directly modified in the db for the post (espresso_attendees post type) for this
262
+	 * attendee.
263
+	 *
264
+	 * @param bool $apply_html_entities
265
+	 * @return string
266
+	 * @throws EE_Error
267
+	 * @throws ReflectionException
268
+	 */
269
+	public function ATT_full_name(bool $apply_html_entities = false): string
270
+	{
271
+		return $apply_html_entities
272
+			? htmlentities((string) $this->get('ATT_full_name'), ENT_QUOTES, 'UTF-8')
273
+			: (string) $this->get('ATT_full_name');
274
+	}
275
+
276
+
277
+	/**
278
+	 * @return string
279
+	 * @throws EE_Error
280
+	 * @throws ReflectionException
281
+	 */
282
+	public function lname(): string
283
+	{
284
+		return (string) $this->get('ATT_lname');
285
+	}
286
+
287
+
288
+	/**
289
+	 * @return string
290
+	 * @throws EE_Error
291
+	 * @throws ReflectionException
292
+	 */
293
+	public function bio(): string
294
+	{
295
+		return (string) $this->get('ATT_bio');
296
+	}
297
+
298
+
299
+	/**
300
+	 * @return string
301
+	 * @throws EE_Error
302
+	 * @throws ReflectionException
303
+	 */
304
+	public function short_bio(): string
305
+	{
306
+		return (string) $this->get('ATT_short_bio');
307
+	}
308
+
309
+
310
+	/**
311
+	 * Gets the attendee's full address as an array so client code can decide hwo to display it
312
+	 *
313
+	 * @return array numerically indexed, with each part of the address that is known.
314
+	 * Eg, if the user only responded to state and country,
315
+	 * it would be array(0=>'Alabama',1=>'USA')
316
+	 * @return array
317
+	 * @throws EE_Error
318
+	 * @throws ReflectionException
319
+	 */
320
+	public function full_address_as_array(): array
321
+	{
322
+		$full_address_array     = [];
323
+		$initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city',];
324
+		foreach ($initial_address_fields as $address_field_name) {
325
+			$address_fields_value = $this->get($address_field_name);
326
+			if (! empty($address_fields_value)) {
327
+				$full_address_array[] = $address_fields_value;
328
+			}
329
+		}
330
+		// now handle state and country
331
+		$state_obj = $this->state_obj();
332
+		if ($state_obj instanceof EE_State) {
333
+			$full_address_array[] = $state_obj->name();
334
+		}
335
+		$country_obj = $this->country_obj();
336
+		if ($country_obj instanceof EE_Country) {
337
+			$full_address_array[] = $country_obj->name();
338
+		}
339
+		// lastly get the xip
340
+		$zip_value = $this->zip();
341
+		if (! empty($zip_value)) {
342
+			$full_address_array[] = $zip_value;
343
+		}
344
+		return $full_address_array;
345
+	}
346
+
347
+
348
+	/**
349
+	 * @return string
350
+	 * @throws EE_Error
351
+	 * @throws ReflectionException
352
+	 */
353
+	public function address(): string
354
+	{
355
+		return (string) $this->get('ATT_address');
356
+	}
357
+
358
+
359
+	/**
360
+	 * @return string
361
+	 * @throws EE_Error
362
+	 * @throws ReflectionException
363
+	 */
364
+	public function address2(): string
365
+	{
366
+		return (string) $this->get('ATT_address2');
367
+	}
368
+
369
+
370
+	/**
371
+	 * @return string
372
+	 * @throws EE_Error
373
+	 * @throws ReflectionException
374
+	 */
375
+	public function city(): string
376
+	{
377
+		return (string) $this->get('ATT_city');
378
+	}
379
+
380
+
381
+	/**
382
+	 * @return int
383
+	 * @throws EE_Error
384
+	 * @throws ReflectionException
385
+	 */
386
+	public function state_ID(): int
387
+	{
388
+		return (int) $this->get('STA_ID');
389
+	}
390
+
391
+
392
+	/**
393
+	 * @return string
394
+	 * @throws EE_Error
395
+	 * @throws ReflectionException
396
+	 */
397
+	public function state_abbrev(): string
398
+	{
399
+		return $this->state_obj() instanceof EE_State
400
+			? $this->state_obj()->abbrev()
401
+			: '';
402
+	}
403
+
404
+
405
+	/**
406
+	 * @return EE_State|null
407
+	 * @throws EE_Error
408
+	 * @throws ReflectionException
409
+	 */
410
+	public function state_obj(): ?EE_State
411
+	{
412
+		return $this->get_first_related('State');
413
+	}
414
+
415
+
416
+	/**
417
+	 * @return string
418
+	 * @throws EE_Error
419
+	 * @throws ReflectionException
420
+	 */
421
+	public function state_name(): string
422
+	{
423
+		return $this->state_obj() instanceof EE_State
424
+			? $this->state_obj()->name()
425
+			: '';
426
+	}
427
+
428
+
429
+	/**
430
+	 * either displays the state abbreviation or the state name, as determined
431
+	 * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
432
+	 * defaults to abbreviation
433
+	 *
434
+	 * @return string
435
+	 * @throws EE_Error
436
+	 * @throws ReflectionException
437
+	 */
438
+	public function state(): string
439
+	{
440
+		return apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())
441
+			? $this->state_abbrev()
442
+			: $this->state_name();
443
+	}
444
+
445
+
446
+	/**
447
+	 * @return string
448
+	 * @throws EE_Error
449
+	 * @throws ReflectionException
450
+	 */
451
+	public function country_ID(): string
452
+	{
453
+		return (string) $this->get('CNT_ISO');
454
+	}
455
+
456
+
457
+	/**
458
+	 * @return EE_Country|null
459
+	 * @throws EE_Error
460
+	 * @throws ReflectionException
461
+	 */
462
+	public function country_obj(): ?EE_Country
463
+	{
464
+		return $this->get_first_related('Country');
465
+	}
466
+
467
+
468
+	/**
469
+	 * @return string
470
+	 * @throws EE_Error
471
+	 * @throws ReflectionException
472
+	 */
473
+	public function country_name(): string
474
+	{
475
+		return $this->country_obj() instanceof EE_Country
476
+			? $this->country_obj()->name()
477
+			: '';
478
+	}
479
+
480
+
481
+	/**
482
+	 * either displays the country ISO2 code or the country name, as determined
483
+	 * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
484
+	 * defaults to abbreviation
485
+	 *
486
+	 * @return string
487
+	 * @throws EE_Error
488
+	 * @throws ReflectionException
489
+	 */
490
+	public function country(): string
491
+	{
492
+		return apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())
493
+			? $this->country_ID()
494
+			: $this->country_name();
495
+	}
496
+
497
+
498
+	/**
499
+	 * @return string
500
+	 * @throws EE_Error
501
+	 * @throws ReflectionException
502
+	 */
503
+	public function zip(): string
504
+	{
505
+		return (string) $this->get('ATT_zip');
506
+	}
507
+
508
+
509
+	/**
510
+	 * @return string
511
+	 * @throws EE_Error
512
+	 * @throws ReflectionException
513
+	 */
514
+	public function email(): string
515
+	{
516
+		return (string) $this->get('ATT_email');
517
+	}
518
+
519
+
520
+	/**
521
+	 * @return string
522
+	 * @throws EE_Error
523
+	 * @throws ReflectionException
524
+	 */
525
+	public function phone(): string
526
+	{
527
+		return (string) $this->get('ATT_phone');
528
+	}
529
+
530
+
531
+	/**
532
+	 * @return bool
533
+	 * @throws EE_Error
534
+	 * @throws ReflectionException
535
+	 */
536
+	public function deleted(): bool
537
+	{
538
+		return (bool) $this->get('ATT_deleted');
539
+	}
540
+
541
+
542
+	/**
543
+	 * @param array $query_params
544
+	 * @return EE_Registration[]
545
+	 * @throws EE_Error
546
+	 * @throws ReflectionException
547
+	 */
548
+	public function get_registrations(array $query_params = []): array
549
+	{
550
+		return $this->get_many_related('Registration', $query_params);
551
+	}
552
+
553
+
554
+	/**
555
+	 * Gets the most recent registration of this attendee
556
+	 *
557
+	 * @return EE_Registration|null
558
+	 * @throws EE_Error
559
+	 * @throws ReflectionException
560
+	 */
561
+	public function get_most_recent_registration(): ?EE_Registration
562
+	{
563
+		return $this->get_first_related('Registration', ['order_by' => ['REG_date' => 'DESC']]);
564
+	}
565
+
566
+
567
+	/**
568
+	 * Gets the most recent registration for this attend at this event
569
+	 *
570
+	 * @param int $event_id
571
+	 * @return EE_Registration|null
572
+	 * @throws EE_Error
573
+	 * @throws ReflectionException
574
+	 */
575
+	public function get_most_recent_registration_for_event(int $event_id): ?EE_Registration
576
+	{
577
+		return $this->get_first_related(
578
+			'Registration',
579
+			[['EVT_ID' => $event_id], 'order_by' => ['REG_date' => 'DESC']]
580
+		);
581
+	}
582
+
583
+
584
+	/**
585
+	 * returns any events attached to this attendee ($_Event property);
586
+	 *
587
+	 * @return EE_Event[]
588
+	 * @throws EE_Error
589
+	 * @throws ReflectionException
590
+	 */
591
+	public function events(): array
592
+	{
593
+		return $this->get_many_related('Event');
594
+	}
595
+
596
+
597
+	/**
598
+	 * Gets the billing info array where keys match espresso_reg_page_billing_inputs(),
599
+	 * and keys are their cleaned values. @param EE_Payment_Method $payment_method the _gateway_name property on the
600
+	 * gateway class
601
+	 *
602
+	 * @return EE_Form_Section_Proper|null
603
+	 * @throws EE_Error
604
+	 * @throws ReflectionException
605
+	 * @see EE_Attendee::save_and_clean_billing_info_for_payment_method() which was used to save the billing info
606
+	 */
607
+	public function billing_info_for_payment_method(EE_Payment_Method $payment_method): ?EE_Form_Section_Proper
608
+	{
609
+		$pm_type = $payment_method->type_obj();
610
+		if (! $pm_type instanceof EE_PMT_Base) {
611
+			return null;
612
+		}
613
+		$billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
614
+		if (! $billing_info) {
615
+			return null;
616
+		}
617
+		$billing_form = $pm_type->billing_form();
618
+		if (! $billing_form instanceof EE_Billing_Info_Form) {
619
+			return null;
620
+		}
621
+		// double-check the form isn't totally hidden, in which case pretend there is no form
622
+		$form_totally_hidden = true;
623
+		foreach ($billing_form->inputs_in_subsections() as $input) {
624
+			if (! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
625
+				$form_totally_hidden = false;
626
+				break;
627
+			}
628
+		}
629
+		if ($form_totally_hidden) {
630
+			return null;
631
+		}
632
+		if ($billing_form instanceof EE_Form_Section_Proper) {
633
+			$billing_form->receive_form_submission([$billing_form->name() => $billing_info], false);
634
+		}
635
+
636
+		return $billing_form;
637
+	}
638
+
639
+
640
+	/**
641
+	 * Gets the postmeta key that holds this attendee's billing info for the
642
+	 * specified payment method
643
+	 *
644
+	 * @param EE_Payment_Method $payment_method
645
+	 * @return string
646
+	 * @throws EE_Error
647
+	 */
648
+	public function get_billing_info_postmeta_name(EE_Payment_Method $payment_method): string
649
+	{
650
+		return $payment_method->type_obj() instanceof EE_PMT_Base
651
+			? 'billing_info_' . $payment_method->type_obj()->system_name()
652
+			: '';
653
+	}
654
+
655
+
656
+	/**
657
+	 * Saves the billing info to the attendee.
658
+	 *
659
+	 * @param EE_Billing_Attendee_Info_Form|null $billing_form
660
+	 * @param EE_Payment_Method                  $payment_method
661
+	 * @return boolean
662
+	 * @throws EE_Error
663
+	 * @throws ReflectionException
664
+	 * @see EE_Attendee::billing_info_for_payment_method() which is used to retrieve it
665
+	 */
666
+	public function save_and_clean_billing_info_for_payment_method(
667
+		?EE_Billing_Attendee_Info_Form $billing_form,
668
+		EE_Payment_Method $payment_method
669
+	): bool {
670
+		if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
671
+			EE_Error::add_error(
672
+				esc_html__('Cannot save billing info because there is none.', 'event_espresso'),
673
+				__FILE__,
674
+				__FUNCTION__,
675
+				__LINE__
676
+			);
677
+			return false;
678
+		}
679
+		$billing_form->clean_sensitive_data();
680
+		$postmeta_name = $this->get_billing_info_postmeta_name($payment_method);
681
+		$saved_values  = get_post_meta($this->ID(), $postmeta_name);
682
+		$input_values  = $billing_form->input_values(true);
683
+		// Merge the values in case some fields were already saved somewhere.
684
+		if ($saved_values && is_array($saved_values)) {
685
+			// Need a one dimensional array.
686
+			$saved_values = array_merge(...$saved_values);
687
+			$input_values = array_merge($saved_values, $input_values);
688
+		}
689
+		return update_post_meta($this->ID(), $postmeta_name, $input_values);
690
+	}
691
+
692
+
693
+	/**
694
+	 * Return the link to the admin details for the object.
695
+	 *
696
+	 * @return string
697
+	 * @throws EE_Error
698
+	 * @throws InvalidArgumentException
699
+	 * @throws InvalidDataTypeException
700
+	 * @throws InvalidInterfaceException
701
+	 * @throws ReflectionException
702
+	 */
703
+	public function get_admin_details_link(): string
704
+	{
705
+		return $this->get_admin_edit_link();
706
+	}
707
+
708
+
709
+	/**
710
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
711
+	 *
712
+	 * @return string
713
+	 * @throws EE_Error
714
+	 * @throws InvalidArgumentException
715
+	 * @throws ReflectionException
716
+	 * @throws InvalidDataTypeException
717
+	 * @throws InvalidInterfaceException
718
+	 */
719
+	public function get_admin_edit_link(): string
720
+	{
721
+		return EEH_URL::add_query_args_and_nonce(
722
+			[
723
+				'page'   => 'espresso_registrations',
724
+				'action' => 'edit_attendee',
725
+				'post'   => $this->ID(),
726
+			],
727
+			admin_url('admin.php')
728
+		);
729
+	}
730
+
731
+
732
+	/**
733
+	 * Returns the link to a settings page for the object.
734
+	 *
735
+	 * @return string
736
+	 * @throws EE_Error
737
+	 * @throws InvalidArgumentException
738
+	 * @throws InvalidDataTypeException
739
+	 * @throws InvalidInterfaceException
740
+	 * @throws ReflectionException
741
+	 */
742
+	public function get_admin_settings_link(): string
743
+	{
744
+		return $this->get_admin_edit_link();
745
+	}
746
+
747
+
748
+	/**
749
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
750
+	 *
751
+	 * @return string
752
+	 */
753
+	public function get_admin_overview_link(): string
754
+	{
755
+		return EEH_URL::add_query_args_and_nonce(
756
+			[
757
+				'page'   => 'espresso_registrations',
758
+				'action' => 'contact_list',
759
+			],
760
+			admin_url('admin.php')
761
+		);
762
+	}
763 763
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -27,16 +27,16 @@  discard block
 block discarded – undo
27 27
      */
28 28
     protected function __construct($fieldValues = null, $bydb = false, $timezone = '', $date_formats = [])
29 29
     {
30
-        if (! isset($fieldValues['ATT_full_name'])) {
30
+        if ( ! isset($fieldValues['ATT_full_name'])) {
31 31
             $fname                        = $fieldValues['ATT_fname'] ?? '';
32 32
             $lname                        = $fieldValues['ATT_lname'] ?? '';
33 33
             $fieldValues['ATT_full_name'] = "$fname $lname";
34 34
         }
35
-        if (! isset($fieldValues['ATT_slug'])) {
35
+        if ( ! isset($fieldValues['ATT_slug'])) {
36 36
             // $fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
37 37
             $fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
38 38
         }
39
-        if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
39
+        if ( ! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
40 40
             $fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
41 41
         }
42 42
         parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
@@ -320,10 +320,10 @@  discard block
 block discarded – undo
320 320
     public function full_address_as_array(): array
321 321
     {
322 322
         $full_address_array     = [];
323
-        $initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city',];
323
+        $initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city', ];
324 324
         foreach ($initial_address_fields as $address_field_name) {
325 325
             $address_fields_value = $this->get($address_field_name);
326
-            if (! empty($address_fields_value)) {
326
+            if ( ! empty($address_fields_value)) {
327 327
                 $full_address_array[] = $address_fields_value;
328 328
             }
329 329
         }
@@ -338,7 +338,7 @@  discard block
 block discarded – undo
338 338
         }
339 339
         // lastly get the xip
340 340
         $zip_value = $this->zip();
341
-        if (! empty($zip_value)) {
341
+        if ( ! empty($zip_value)) {
342 342
             $full_address_array[] = $zip_value;
343 343
         }
344 344
         return $full_address_array;
@@ -607,21 +607,21 @@  discard block
 block discarded – undo
607 607
     public function billing_info_for_payment_method(EE_Payment_Method $payment_method): ?EE_Form_Section_Proper
608 608
     {
609 609
         $pm_type = $payment_method->type_obj();
610
-        if (! $pm_type instanceof EE_PMT_Base) {
610
+        if ( ! $pm_type instanceof EE_PMT_Base) {
611 611
             return null;
612 612
         }
613 613
         $billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
614
-        if (! $billing_info) {
614
+        if ( ! $billing_info) {
615 615
             return null;
616 616
         }
617 617
         $billing_form = $pm_type->billing_form();
618
-        if (! $billing_form instanceof EE_Billing_Info_Form) {
618
+        if ( ! $billing_form instanceof EE_Billing_Info_Form) {
619 619
             return null;
620 620
         }
621 621
         // double-check the form isn't totally hidden, in which case pretend there is no form
622 622
         $form_totally_hidden = true;
623 623
         foreach ($billing_form->inputs_in_subsections() as $input) {
624
-            if (! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
624
+            if ( ! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
625 625
                 $form_totally_hidden = false;
626 626
                 break;
627 627
             }
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
     public function get_billing_info_postmeta_name(EE_Payment_Method $payment_method): string
649 649
     {
650 650
         return $payment_method->type_obj() instanceof EE_PMT_Base
651
-            ? 'billing_info_' . $payment_method->type_obj()->system_name()
651
+            ? 'billing_info_'.$payment_method->type_obj()->system_name()
652 652
             : '';
653 653
     }
654 654
 
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
         ?EE_Billing_Attendee_Info_Form $billing_form,
668 668
         EE_Payment_Method $payment_method
669 669
     ): bool {
670
-        if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
670
+        if ( ! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
671 671
             EE_Error::add_error(
672 672
                 esc_html__('Cannot save billing info because there is none.', 'event_espresso'),
673 673
                 __FILE__,
Please login to merge, or discard this patch.
core/db_classes/EE_CSV.class.php 1 patch
Indentation   +660 added lines, -660 removed lines patch added patch discarded remove patch
@@ -13,664 +13,664 @@
 block discarded – undo
13 13
  */
14 14
 class EE_CSV
15 15
 {
16
-    // instance of the EE_CSV object
17
-    private static $_instance = null;
18
-
19
-
20
-    // multidimensional array to store update & error messages
21
-    // var $_notices = array( 'updates' => array(), 'errors' => array() );
22
-
23
-
24
-    private $_primary_keys;
25
-
26
-    /**
27
-     * @var EE_Registry
28
-     */
29
-    private $EE;
30
-    /**
31
-     * string used for 1st cell in exports, which indicates that the following 2 rows will be metadata keys and values
32
-     */
33
-    const metadata_header = 'Event Espresso Export Meta Data';
34
-
35
-    /**
36
-     * private constructor to prevent direct creation
37
-     *
38
-     * @return void
39
-     */
40
-    private function __construct()
41
-    {
42
-        global $wpdb;
43
-
44
-        $this->_primary_keys = array(
45
-            $wpdb->prefix . 'esp_answer'                  => array('ANS_ID'),
46
-            $wpdb->prefix . 'esp_attendee'                => array('ATT_ID'),
47
-            $wpdb->prefix . 'esp_datetime'                => array('DTT_ID'),
48
-            $wpdb->prefix . 'esp_event_question_group'    => array('EQG_ID'),
49
-            $wpdb->prefix . 'esp_message_template'        => array('MTP_ID'),
50
-            $wpdb->prefix . 'esp_payment'                 => array('PAY_ID'),
51
-            $wpdb->prefix . 'esp_price'                   => array('PRC_ID'),
52
-            $wpdb->prefix . 'esp_price_type'              => array('PRT_ID'),
53
-            $wpdb->prefix . 'esp_question'                => array('QST_ID'),
54
-            $wpdb->prefix . 'esp_question_group'          => array('QSG_ID'),
55
-            $wpdb->prefix . 'esp_question_group_question' => array('QGQ_ID'),
56
-            $wpdb->prefix . 'esp_question_option'         => array('QSO_ID'),
57
-            $wpdb->prefix . 'esp_registration'            => array('REG_ID'),
58
-            $wpdb->prefix . 'esp_status'                  => array('STS_ID'),
59
-            $wpdb->prefix . 'esp_transaction'             => array('TXN_ID'),
60
-            $wpdb->prefix . 'esp_transaction'             => array('TXN_ID'),
61
-            $wpdb->prefix . 'events_detail'               => array('id'),
62
-            $wpdb->prefix . 'events_category_detail'      => array('id'),
63
-            $wpdb->prefix . 'events_category_rel'         => array('id'),
64
-            $wpdb->prefix . 'events_venue'                => array('id'),
65
-            $wpdb->prefix . 'events_venue_rel'            => array('emeta_id'),
66
-            $wpdb->prefix . 'events_locale'               => array('id'),
67
-            $wpdb->prefix . 'events_locale_rel'           => array('id'),
68
-            $wpdb->prefix . 'events_personnel'            => array('id'),
69
-            $wpdb->prefix . 'events_personnel_rel'        => array('id'),
70
-        );
71
-    }
72
-
73
-
74
-    /**
75
-     * singleton method used to instantiate class object
76
-     *
77
-     * @return EE_CSV
78
-     */
79
-    public static function instance()
80
-    {
81
-        // check if class object is instantiated
82
-        if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_CSV)) {
83
-            self::$_instance = new self();
84
-        }
85
-        return self::$_instance;
86
-    }
87
-
88
-    /**
89
-     * Opens a unicode or utf file (normal file_get_contents has difficulty reading ga unicode file)
90
-     * @see http://stackoverflow.com/questions/15092764/how-to-read-unicode-text-file-in-php
91
-     *
92
-     * @param string $file_path
93
-     * @return string
94
-     * @throws EE_Error
95
-     */
96
-    private function read_unicode_file($file_path)
97
-    {
98
-        $fc = "";
99
-        $fh = fopen($file_path, "rb");
100
-        if (! $fh) {
101
-            throw new EE_Error(sprintf(esc_html__("Cannot open file for read: %s<br>\n", 'event_espresso'), $file_path));
102
-        }
103
-        $flen = filesize($file_path);
104
-        $bc = fread($fh, $flen);
105
-        for ($i = 0; $i < $flen; $i++) {
106
-            $c = substr($bc, $i, 1);
107
-            if ((ord($c) != 0) && (ord($c) != 13)) {
108
-                $fc = $fc . $c;
109
-            }
110
-        }
111
-        if ((ord(substr($fc, 0, 1)) == 255) && (ord(substr($fc, 1, 1)) == 254)) {
112
-            $fc = substr($fc, 2);
113
-        }
114
-        return ($fc);
115
-    }
116
-
117
-
118
-    /**
119
-     * Generic CSV-functionality to turn an entire CSV file into a single array that's
120
-     * NOT in a specific format to EE. It's just a 2-level array, with top-level arrays
121
-     * representing each row in the CSV file, and the second-level arrays being each column in that row
122
-     *
123
-     * @param string $path_to_file
124
-     * @return array of arrays. Top-level array has rows, second-level array has each item
125
-     */
126
-    public function import_csv_to_multi_dimensional_array($path_to_file)
127
-    {
128
-        // needed to deal with Mac line endings
129
-        ini_set('auto_detect_line_endings', true);
130
-
131
-        // because fgetcsv does not correctly deal with backslashed quotes such as \"
132
-        // we'll read the file into a string
133
-        $file_contents = $this->read_unicode_file($path_to_file);
134
-        // replace backslashed quotes with CSV enclosures
135
-        $file_contents = str_replace('\\"', '"""', $file_contents);
136
-        // HEY YOU! PUT THAT FILE BACK!!!
137
-        file_put_contents($path_to_file, $file_contents);
138
-
139
-        if (($file_handle = fopen($path_to_file, "r")) !== false) {
140
-            # Set the parent multidimensional array key to 0.
141
-            $nn = 0;
142
-            $csvarray = array();
143
-
144
-            // in PHP 5.3 fgetcsv accepts a 5th parameter, but the pre 5.3 versions of fgetcsv choke if passed more than 4 - is that crazy or what?
145
-            if (version_compare(PHP_VERSION, '5.3.0') < 0) {
146
-                //  PHP 5.2- version
147
-                // loop through each row of the file
148
-                while (($data = fgetcsv($file_handle, 0, ',', '"')) !== false) {
149
-                    $csvarray[] = $data;
150
-                }
151
-            } else {
152
-                // loop through each row of the file
153
-                while (($data = fgetcsv($file_handle, 0, ',', '"', '\\')) !== false) {
154
-                    $csvarray[] = $data;
155
-                }
156
-            }
157
-            # Close the File.
158
-            fclose($file_handle);
159
-            return $csvarray;
160
-        } else {
161
-            EE_Error::add_error(
162
-                sprintf(esc_html__("An error occurred - the file: %s could not opened.", "event_espresso"), $path_to_file),
163
-                __FILE__,
164
-                __FUNCTION__,
165
-                __LINE__
166
-            );
167
-            return false;
168
-        }
169
-    }
170
-
171
-
172
-    /**
173
-     * Import contents of csv file and store values in an array to be manipulated by other functions
174
-     * @param string  $path_to_file         - the csv file to be imported including the path to it's location.
175
-     *                                      If $model_name is provided, assumes that each row in the CSV represents a
176
-     *                                      model object for that model If $model_name ISN'T provided, assumes that
177
-     *                                      before model object data, there is a row where the first entry is simply
178
-     *                                      'MODEL', and next entry is the model's name, (untranslated) like Event, and
179
-     *                                      then maybe a row of headers, and then the model data. Eg.
180
-     *                                      '<br>MODEL,Event,<br>EVT_ID,EVT_name,...<br>1,Monkey
181
-     *                                      Party,...<br>2,Llamarama,...<br>MODEL,Venue,<br>VNU_ID,VNU_name<br>1,The
182
-     *                                      Forest
183
-     * @param string  $model_name           model name if we know what model we're importing
184
-     * @param boolean $first_row_is_headers - whether the first row of data is headers or not - TRUE = headers, FALSE =
185
-     *                                      data
186
-     * @return mixed - array on success - multi dimensional with headers as keys (if headers exist) OR string on fail -
187
-     *               error message like the following array('Event'=>array( array('EVT_ID'=>1,'EVT_name'=>'bob
188
-     *               party',...), array('EVT_ID'=>2,'EVT_name'=>'llamarama',...),
189
-     *                                      ...
190
-     *                                      )
191
-     *                                      'Venue'=>array(
192
-     *                                      array('VNU_ID'=>1,'VNU_name'=>'the shack',...),
193
-     *                                      array('VNU_ID'=>2,'VNU_name'=>'tree house',...),
194
-     *                                      ...
195
-     *                                      )
196
-     *                                      ...
197
-     *                                      )
198
-     */
199
-    public function import_csv_to_model_data_array($path_to_file, $model_name = false, $first_row_is_headers = true)
200
-    {
201
-        $multi_dimensional_array = $this->import_csv_to_multi_dimensional_array($path_to_file);
202
-        if (! $multi_dimensional_array) {
203
-            return false;
204
-        }
205
-        // gotta start somewhere
206
-        $row = 1;
207
-        // array to store csv data in
208
-        $ee_formatted_data = array();
209
-        // array to store headers (column names)
210
-        $headers = array();
211
-        foreach ($multi_dimensional_array as $data) {
212
-            // if first cell is MODEL, then second cell is the MODEL name
213
-            if ($data[0] == 'MODEL') {
214
-                $model_name = $data[1];
215
-                // don't bother looking for model data in this row. The rest of this
216
-                // row should be blank
217
-                // AND pretend this is the first row again
218
-                $row = 1;
219
-                // reset headers
220
-                $headers = array();
221
-                continue;
222
-            }
223
-            if (strpos($data[0], EE_CSV::metadata_header) !== false) {
224
-                $model_name = EE_CSV::metadata_header;
225
-                // store like model data, we just won't try importing it etc.
226
-                $row = 1;
227
-                continue;
228
-            }
229
-
230
-
231
-            // how many columns are there?
232
-            $columns = count($data);
233
-
234
-            $model_entry = array();
235
-            // loop through each column
236
-            for ($i = 0; $i < $columns; $i++) {
237
-                // replace csv_enclosures with backslashed quotes
238
-                $data[ $i ] = str_replace('"""', '\\"', $data[ $i ]);
239
-                // do we need to grab the column names?
240
-                if ($row === 1) {
241
-                    if ($first_row_is_headers) {
242
-                        // store the column names to use for keys
243
-                        $column_name = $data[ $i ];
244
-                        // check it's not blank... sometimes CSV editign programs adda bunch of empty columns onto the end...
245
-                        if (! $column_name) {
246
-                            continue;
247
-                        }
248
-                        $matches = array();
249
-                        if ($model_name == EE_CSV::metadata_header) {
250
-                            $headers[ $i ] = $column_name;
251
-                        } else {
252
-                            // now get the db table name from it (the part between square brackets)
253
-                            $success = preg_match('~(.*)\[(.*)\]~', $column_name, $matches);
254
-                            if (! $success) {
255
-                                EE_Error::add_error(
256
-                                    sprintf(
257
-                                        esc_html__(
258
-                                            "The column titled %s is invalid for importing. It must be be in the format of 'Nice Name[model_field_name]' in row %s",
259
-                                            "event_espresso"
260
-                                        ),
261
-                                        $column_name,
262
-                                        implode(",", $data)
263
-                                    ),
264
-                                    __FILE__,
265
-                                    __FUNCTION__,
266
-                                    __LINE__
267
-                                );
268
-                                return false;
269
-                            }
270
-                            $headers[ $i ] = $matches[2];
271
-                        }
272
-                    } else {
273
-                        // no column names means our final array will just use counters for keys
274
-                        $model_entry[ $headers[ $i ] ] = $data[ $i ];
275
-                        $headers[ $i ] = $i;
276
-                    }
277
-                    // and we need to store csv data
278
-                } else {
279
-                    // this column isn' ta header, store it if there is a header for it
280
-                    if (isset($headers[ $i ])) {
281
-                        $model_entry[ $headers[ $i ] ] = $data[ $i ];
282
-                    }
283
-                }
284
-            }
285
-            // save the row's data IF it's a non-header-row
286
-            if (! $first_row_is_headers || ($first_row_is_headers && $row > 1)) {
287
-                $ee_formatted_data[ $model_name ][] = $model_entry;
288
-            }
289
-            // advance to next row
290
-            $row++;
291
-        }
292
-
293
-        // delete the uploaded file
294
-        unlink($path_to_file);
295
-        // echo '<pre style="height:auto;border:2px solid lightblue;">' . print_r( $ee_formatted_data, TRUE ) . '</pre><br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>';
296
-        // die();
297
-
298
-        // it's good to give back
299
-        return $ee_formatted_data;
300
-    }
301
-
302
-
303
-    public function save_csv_to_db($csv_data_array, $model_name = false)
304
-    {
305
-        EE_Error::doing_it_wrong(
306
-            'save_csv_to_db',
307
-            esc_html__(
308
-                'Function moved to EE_Import and renamed to save_csv_data_array_to_db',
309
-                'event_espresso'
310
-            ),
311
-            '4.6.7'
312
-        );
313
-        return EE_Import::instance()->save_csv_data_array_to_db($csv_data_array, $model_name);
314
-    }
315
-
316
-    /**
317
-     * Sends HTTP headers to indicate that the browser should download a file,
318
-     * and starts writing the file to PHP's output. Returns the file handle so other functions can
319
-     * also write to it
320
-     *
321
-     * @param string $new_filename the name of the file that the user will download
322
-     * @return resource, like the results of fopen(), which can be used for fwrite, fputcsv2, etc.
323
-     */
324
-    public function begin_sending_csv($filename)
325
-    {
326
-        // grab file extension
327
-        $ext = substr(strrchr($filename, '.'), 1);
328
-        if ($ext == '.csv' or $ext == '.xls') {
329
-            str_replace($ext, '', $filename);
330
-        }
331
-        $filename .= '.csv';
332
-
333
-        // if somebody's been naughty and already started outputting stuff, trash it
334
-        // and start writing our stuff.
335
-        if (ob_get_length()) {
336
-            @ob_flush();
337
-            @flush();
338
-            @ob_end_flush();
339
-        }
340
-        @ob_start();
341
-        header("Pragma: public");
342
-        header("Expires: 0");
343
-        header("Pragma: no-cache");
344
-        header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
345
-        // header("Content-Type: application/force-download");
346
-        // header("Content-Type: application/octet-stream");
347
-        // header("Content-Type: application/download");
348
-        header('Content-disposition: attachment; filename=' . $filename);
349
-        header("Content-Type: text/csv; charset=utf-8");
350
-        do_action('AHEE__EE_CSV__begin_sending_csv__headers');
351
-        echo apply_filters(
352
-            'FHEE__EE_CSV__begin_sending_csv__start_writing',
353
-            "\xEF\xBB\xBF"
354
-        ); // makes excel open it as UTF-8. UTF-8 BOM, see http://stackoverflow.com/a/4440143/2773835
355
-        $fh = fopen('php://output', 'w');
356
-        return $fh;
357
-    }
358
-
359
-    /**
360
-     * Writes some meta data to the CSV as a bunch of columns. Initially we're only
361
-     * mentioning the version and timezone
362
-     *
363
-     * @param resource $filehandle
364
-     */
365
-    public function write_metadata_to_csv($filehandle)
366
-    {
367
-        $data_row = array(EE_CSV::metadata_header);// do NOT translate because this exact string is used when importing
368
-        $this->fputcsv2($filehandle, $data_row);
369
-        $meta_data = array(
370
-            0 => array(
371
-                'version'        => espresso_version(),
372
-                'timezone'       => EEH_DTT_Helper::get_timezone(),
373
-                'time_of_export' => current_time('mysql'),
374
-                'site_url'       => site_url(),
375
-            ),
376
-        );
377
-        $this->write_data_array_to_csv($filehandle, $meta_data);
378
-    }
379
-
380
-
381
-    /**
382
-     * Writes $data to the csv file open in $filehandle. uses the array indices of $data for column headers
383
-     *
384
-     * @param array   $data                 2D array, first numerically-indexed, and next-level-down preferably indexed
385
-     *                                      by string
386
-     * @param boolean $add_csv_column_names whether or not we should add the keys in the bottom-most array as a row for
387
-     *                                      headers in the CSV. Eg, if $data looked like
388
-     *                                      array(0=>array('EVT_ID'=>1,'EVT_name'=>'monkey'...), 1=>array(...),...))
389
-     *                                      then the first row we'd write to the CSV would be "EVT_ID,EVT_name,..."
390
-     * @return boolean if we successfully wrote to the CSV or not. If there's no $data, we consider that a success
391
-     *                 (because we wrote everything there was...nothing)
392
-     */
393
-    public function write_data_array_to_csv($filehandle, $data)
394
-    {
395
-
396
-
397
-        // determine if $data is actually a 2d array
398
-        if ($data && is_array($data) && is_array(EEH_Array::get_one_item_from_array($data))) {
399
-            // make sure top level is numerically indexed,
400
-
401
-            if (EEH_Array::is_associative_array($data)) {
402
-                throw new EE_Error(
403
-                    sprintf(
404
-                        esc_html__(
405
-                            "top-level array must be numerically indexed. Does these look like numbers to you? %s",
406
-                            "event_espresso"
407
-                        ),
408
-                        implode(",", array_keys($data))
409
-                    )
410
-                );
411
-            }
412
-            $item_in_top_level_array = EEH_Array::get_one_item_from_array($data);
413
-            // now, is the last item in the top-level array of $data an associative or numeric array?
414
-            if (EEH_Array::is_associative_array($item_in_top_level_array)) {
415
-                // its associative, so we want to output its keys as column headers
416
-                $keys = array_keys($item_in_top_level_array);
417
-                $this->fputcsv2($filehandle, $keys);
418
-            }
419
-            // start writing data
420
-            foreach ($data as $data_row) {
421
-                $this->fputcsv2($filehandle, $data_row);
422
-            }
423
-            return true;
424
-        } else {
425
-            // no data TO write... so we can assume that's a success
426
-            return true;
427
-        }
428
-        // //if 2nd level is indexed by strings, use those as csv column headers (ie, the first row)
429
-        //
430
-        //
431
-        // $no_table = TRUE;
432
-        //
433
-        // // loop through data and add each row to the file/stream as csv
434
-        // foreach ( $data as $model_name => $model_data ) {
435
-        // // test first row to see if it is data or a model name
436
-        // $model = EE_Registry::instance();->load_model($model_name);
437
-        // //if the model really exists,
438
-        // if ( $model ) {
439
-        //
440
-        // // we have a table name
441
-        // $no_table = FALSE;
442
-        //
443
-        // // put the tablename into an array cuz that's how fputcsv rolls
444
-        // $model_name_row = array( 'MODEL', $model_name );
445
-        //
446
-        // // add table name to csv output
447
-        // echo self::fputcsv2($filehandle, $model_name_row);
448
-        //
449
-        // // now get the rest of the data
450
-        // foreach ( $model_data as $row ) {
451
-        // // output the row
452
-        // echo self::fputcsv2($filehandle, $row);
453
-        // }
454
-        //
455
-        // }
456
-        //
457
-        // if ( $no_table ) {
458
-        // // no table so just put the data
459
-        // echo self::fputcsv2($filehandle, $model_data);
460
-        // }
461
-        //
462
-        // } // END OF foreach ( $data )
463
-    }
464
-
465
-    /**
466
-     * Should be called after begin_sending_csv(), and one or more write_data_array_to_csv()s.
467
-     * Calls exit to prevent polluting the CSV file with other junk
468
-     *
469
-     * @param resource $fh filehandle where we're writing the CSV to
470
-     */
471
-    public function end_sending_csv($fh)
472
-    {
473
-        fclose($fh);
474
-        exit(0);
475
-    }
476
-
477
-    /**
478
-     * Given an open file, writes all the model data to it in the format the importer expects.
479
-     * Usually preceded by begin_sending_csv($filename), and followed by end_sending_csv($filehandle).
480
-     *
481
-     * @param resource $filehandle
482
-     * @param array    $model_data_array is assumed to be a 3d array: 1st layer has keys of model names (eg 'Event'),
483
-     *                                   next layer is numerically indexed to represent each model object (eg, each
484
-     *                                   individual event), and the last layer has all the attributes o fthat model
485
-     *                                   object (eg, the event's id, name, etc)
486
-     * @return boolean success
487
-     */
488
-    public function write_model_data_to_csv($filehandle, $model_data_array)
489
-    {
490
-        $this->write_metadata_to_csv($filehandle);
491
-        foreach ($model_data_array as $model_name => $model_instance_arrays) {
492
-            // first: output a special row stating the model
493
-            $this->fputcsv2($filehandle, array('MODEL', $model_name));
494
-            // if we have items to put in the CSV, do it normally
495
-
496
-            if (! empty($model_instance_arrays)) {
497
-                $this->write_data_array_to_csv($filehandle, $model_instance_arrays);
498
-            } else {
499
-                // echo "no data to write... so just write the headers";
500
-                // so there's actually NO model objects for that model.
501
-                // probably still want to show the columns
502
-                $model = EE_Registry::instance()->load_model($model_name);
503
-                $column_names = array();
504
-                foreach ($model->field_settings() as $field) {
505
-                    $column_names[ $field->get_nicename() . "[" . $field->get_name() . "]" ] = null;
506
-                }
507
-                $this->write_data_array_to_csv($filehandle, array($column_names));
508
-            }
509
-        }
510
-    }
511
-
512
-    /**
513
-     * Writes the CSV file to the output buffer, with rows corresponding to $model_data_array,
514
-     * and dies (in order to avoid other plugins from messing up the csv output)
515
-     *
516
-     * @param string $filename         the filename you want to give the file
517
-     * @param array  $model_data_array 3d array, as described in EE_CSV::write_model_data_to_csv()
518
-     * @return bool | void writes CSV file to output and dies
519
-     */
520
-    public function export_multiple_model_data_to_csv($filename, $model_data_array)
521
-    {
522
-        $filehandle = $this->begin_sending_csv($filename);
523
-        $this->write_model_data_to_csv($filehandle, $model_data_array);
524
-        $this->end_sending_csv($filehandle);
525
-    }
526
-
527
-    /**
528
-     * Export contents of an array to csv file
529
-     * @param array  $data     - the array of data to be converted to csv and exported
530
-     * @param string $filename - name for newly created csv file
531
-     * @return TRUE on success, FALSE on fail
532
-     */
533
-    public function export_array_to_csv($data = false, $filename = false)
534
-    {
535
-
536
-        // no data file?? get outta here
537
-        if (! $data or ! is_array($data) or empty($data)) {
538
-            return false;
539
-        }
540
-
541
-        // no filename?? get outta here
542
-        if (! $filename) {
543
-            return false;
544
-        }
545
-
546
-
547
-        // somebody told me i might need this ???
548
-        global $wpdb;
549
-        $prefix = $wpdb->prefix;
550
-
551
-
552
-        $fh = $this->begin_sending_csv($filename);
553
-
554
-
555
-        $this->end_sending_csv($fh);
556
-    }
557
-
558
-
559
-    /**
560
-     * Determine the maximum upload file size based on php.ini settings
561
-     * @param int $percent_of_max - desired percentage of the max upload_mb
562
-     * @return int KB
563
-     */
564
-    public function get_max_upload_size($percent_of_max = false)
565
-    {
566
-
567
-        $max_upload = (int) (ini_get('upload_max_filesize'));
568
-        $max_post = (int) (ini_get('post_max_size'));
569
-        $memory_limit = (int) (ini_get('memory_limit'));
570
-
571
-        // determine the smallest of the three values from above
572
-        $upload_mb = min($max_upload, $max_post, $memory_limit);
573
-
574
-        // convert MB to KB
575
-        $upload_mb = $upload_mb * 1024;
576
-
577
-        // don't want the full monty? then reduce the max uplaod size
578
-        if ($percent_of_max) {
579
-            // is percent_of_max like this -> 50 or like this -> 0.50 ?
580
-            if ($percent_of_max > 1) {
581
-                // chnages 50 to 0.50
582
-                $percent_of_max = $percent_of_max / 100;
583
-            }
584
-            // make upload_mb a percentage of the max upload_mb
585
-            $upload_mb = $upload_mb * $percent_of_max;
586
-        }
587
-
588
-        return $upload_mb;
589
-    }
590
-
591
-
592
-    /**
593
-     * Drop   in replacement for PHP's fputcsv function - but this one works!!!
594
-     * @param resource $fh         - file handle - what we are writing to
595
-     * @param array    $row        - individual row of csv data
596
-     * @param string   $delimiter  - csv delimiter
597
-     * @param string   $enclosure  - csv enclosure
598
-     * @param string   $mysql_null - allows php NULL to be overridden with MySQl's insertable NULL value
599
-     * @return void
600
-     */
601
-    private function fputcsv2($fh, array $row, $delimiter = ',', $enclosure = '"', $mysql_null = false)
602
-    {
603
-        // Allow user to filter the csv delimiter and enclosure for other countries csv standards
604
-        $delimiter = apply_filters('FHEE__EE_CSV__fputcsv2__delimiter', $delimiter);
605
-        $enclosure = apply_filters('FHEE__EE_CSV__fputcsv2__enclosure', $enclosure);
606
-
607
-        $delimiter_esc = preg_quote($delimiter, '/');
608
-        $enclosure_esc = preg_quote($enclosure, '/');
609
-
610
-        $output = array();
611
-        foreach ($row as $field_value) {
612
-            if (is_object($field_value) || is_array($field_value)) {
613
-                $field_value = serialize($field_value);
614
-            }
615
-            if ($field_value === null && $mysql_null) {
616
-                $output[] = 'NULL';
617
-                continue;
618
-            }
619
-
620
-            $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field_value) ?
621
-                ($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field_value) . $enclosure)
622
-                : $field_value;
623
-        }
624
-
625
-        fwrite($fh, join($delimiter, $output) . PHP_EOL);
626
-    }
627
-
628
-
629
-    // /**
630
-    //  * CSV    Import / Export messages
631
-    //  * @return void
632
-    //  */
633
-    // public function csv_admin_notices()
634
-    // {
635
-    //
636
-    //     // We play both kinds of music here! Country AND Western! - err... I mean, cycle through both types of notices
637
-    //     foreach (array('updates', 'errors') as $type) {
638
-    //
639
-    //         // if particular notice type is not empty, then "You've got Mail"
640
-    //         if (! empty($this->_notices[ $type ])) {
641
-    //
642
-    //             // is it an update or an error ?
643
-    //             $msg_class = $type == 'updates' ? 'updated' : 'error';
644
-    //             echo '<div id="message" class="' . $msg_class . '">';
645
-    //             // display each notice, however many that may be
646
-    //             foreach ($this->_notices[ $type ] as $message) {
647
-    //                 echo '<p>' . $message . '</p>';
648
-    //             }
649
-    //             // wrap it up
650
-    //             echo '</div>';
651
-    //         }
652
-    //     }
653
-    // }
654
-
655
-    /**
656
-     * Gets the date format to use in teh csv. filterable
657
-     *
658
-     * @param string $current_format
659
-     * @return string
660
-     */
661
-    public function get_date_format_for_csv($current_format = null)
662
-    {
663
-        return apply_filters('FHEE__EE_CSV__get_date_format_for_csv__format', 'Y-m-d', $current_format);
664
-    }
665
-
666
-    /**
667
-     * Gets the time format we want to use in CSV reports. Filterable
668
-     *
669
-     * @param string $current_format
670
-     * @return string
671
-     */
672
-    public function get_time_format_for_csv($current_format = null)
673
-    {
674
-        return apply_filters('FHEE__EE_CSV__get_time_format_for_csv__format', 'H:i:s', $current_format);
675
-    }
16
+	// instance of the EE_CSV object
17
+	private static $_instance = null;
18
+
19
+
20
+	// multidimensional array to store update & error messages
21
+	// var $_notices = array( 'updates' => array(), 'errors' => array() );
22
+
23
+
24
+	private $_primary_keys;
25
+
26
+	/**
27
+	 * @var EE_Registry
28
+	 */
29
+	private $EE;
30
+	/**
31
+	 * string used for 1st cell in exports, which indicates that the following 2 rows will be metadata keys and values
32
+	 */
33
+	const metadata_header = 'Event Espresso Export Meta Data';
34
+
35
+	/**
36
+	 * private constructor to prevent direct creation
37
+	 *
38
+	 * @return void
39
+	 */
40
+	private function __construct()
41
+	{
42
+		global $wpdb;
43
+
44
+		$this->_primary_keys = array(
45
+			$wpdb->prefix . 'esp_answer'                  => array('ANS_ID'),
46
+			$wpdb->prefix . 'esp_attendee'                => array('ATT_ID'),
47
+			$wpdb->prefix . 'esp_datetime'                => array('DTT_ID'),
48
+			$wpdb->prefix . 'esp_event_question_group'    => array('EQG_ID'),
49
+			$wpdb->prefix . 'esp_message_template'        => array('MTP_ID'),
50
+			$wpdb->prefix . 'esp_payment'                 => array('PAY_ID'),
51
+			$wpdb->prefix . 'esp_price'                   => array('PRC_ID'),
52
+			$wpdb->prefix . 'esp_price_type'              => array('PRT_ID'),
53
+			$wpdb->prefix . 'esp_question'                => array('QST_ID'),
54
+			$wpdb->prefix . 'esp_question_group'          => array('QSG_ID'),
55
+			$wpdb->prefix . 'esp_question_group_question' => array('QGQ_ID'),
56
+			$wpdb->prefix . 'esp_question_option'         => array('QSO_ID'),
57
+			$wpdb->prefix . 'esp_registration'            => array('REG_ID'),
58
+			$wpdb->prefix . 'esp_status'                  => array('STS_ID'),
59
+			$wpdb->prefix . 'esp_transaction'             => array('TXN_ID'),
60
+			$wpdb->prefix . 'esp_transaction'             => array('TXN_ID'),
61
+			$wpdb->prefix . 'events_detail'               => array('id'),
62
+			$wpdb->prefix . 'events_category_detail'      => array('id'),
63
+			$wpdb->prefix . 'events_category_rel'         => array('id'),
64
+			$wpdb->prefix . 'events_venue'                => array('id'),
65
+			$wpdb->prefix . 'events_venue_rel'            => array('emeta_id'),
66
+			$wpdb->prefix . 'events_locale'               => array('id'),
67
+			$wpdb->prefix . 'events_locale_rel'           => array('id'),
68
+			$wpdb->prefix . 'events_personnel'            => array('id'),
69
+			$wpdb->prefix . 'events_personnel_rel'        => array('id'),
70
+		);
71
+	}
72
+
73
+
74
+	/**
75
+	 * singleton method used to instantiate class object
76
+	 *
77
+	 * @return EE_CSV
78
+	 */
79
+	public static function instance()
80
+	{
81
+		// check if class object is instantiated
82
+		if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_CSV)) {
83
+			self::$_instance = new self();
84
+		}
85
+		return self::$_instance;
86
+	}
87
+
88
+	/**
89
+	 * Opens a unicode or utf file (normal file_get_contents has difficulty reading ga unicode file)
90
+	 * @see http://stackoverflow.com/questions/15092764/how-to-read-unicode-text-file-in-php
91
+	 *
92
+	 * @param string $file_path
93
+	 * @return string
94
+	 * @throws EE_Error
95
+	 */
96
+	private function read_unicode_file($file_path)
97
+	{
98
+		$fc = "";
99
+		$fh = fopen($file_path, "rb");
100
+		if (! $fh) {
101
+			throw new EE_Error(sprintf(esc_html__("Cannot open file for read: %s<br>\n", 'event_espresso'), $file_path));
102
+		}
103
+		$flen = filesize($file_path);
104
+		$bc = fread($fh, $flen);
105
+		for ($i = 0; $i < $flen; $i++) {
106
+			$c = substr($bc, $i, 1);
107
+			if ((ord($c) != 0) && (ord($c) != 13)) {
108
+				$fc = $fc . $c;
109
+			}
110
+		}
111
+		if ((ord(substr($fc, 0, 1)) == 255) && (ord(substr($fc, 1, 1)) == 254)) {
112
+			$fc = substr($fc, 2);
113
+		}
114
+		return ($fc);
115
+	}
116
+
117
+
118
+	/**
119
+	 * Generic CSV-functionality to turn an entire CSV file into a single array that's
120
+	 * NOT in a specific format to EE. It's just a 2-level array, with top-level arrays
121
+	 * representing each row in the CSV file, and the second-level arrays being each column in that row
122
+	 *
123
+	 * @param string $path_to_file
124
+	 * @return array of arrays. Top-level array has rows, second-level array has each item
125
+	 */
126
+	public function import_csv_to_multi_dimensional_array($path_to_file)
127
+	{
128
+		// needed to deal with Mac line endings
129
+		ini_set('auto_detect_line_endings', true);
130
+
131
+		// because fgetcsv does not correctly deal with backslashed quotes such as \"
132
+		// we'll read the file into a string
133
+		$file_contents = $this->read_unicode_file($path_to_file);
134
+		// replace backslashed quotes with CSV enclosures
135
+		$file_contents = str_replace('\\"', '"""', $file_contents);
136
+		// HEY YOU! PUT THAT FILE BACK!!!
137
+		file_put_contents($path_to_file, $file_contents);
138
+
139
+		if (($file_handle = fopen($path_to_file, "r")) !== false) {
140
+			# Set the parent multidimensional array key to 0.
141
+			$nn = 0;
142
+			$csvarray = array();
143
+
144
+			// in PHP 5.3 fgetcsv accepts a 5th parameter, but the pre 5.3 versions of fgetcsv choke if passed more than 4 - is that crazy or what?
145
+			if (version_compare(PHP_VERSION, '5.3.0') < 0) {
146
+				//  PHP 5.2- version
147
+				// loop through each row of the file
148
+				while (($data = fgetcsv($file_handle, 0, ',', '"')) !== false) {
149
+					$csvarray[] = $data;
150
+				}
151
+			} else {
152
+				// loop through each row of the file
153
+				while (($data = fgetcsv($file_handle, 0, ',', '"', '\\')) !== false) {
154
+					$csvarray[] = $data;
155
+				}
156
+			}
157
+			# Close the File.
158
+			fclose($file_handle);
159
+			return $csvarray;
160
+		} else {
161
+			EE_Error::add_error(
162
+				sprintf(esc_html__("An error occurred - the file: %s could not opened.", "event_espresso"), $path_to_file),
163
+				__FILE__,
164
+				__FUNCTION__,
165
+				__LINE__
166
+			);
167
+			return false;
168
+		}
169
+	}
170
+
171
+
172
+	/**
173
+	 * Import contents of csv file and store values in an array to be manipulated by other functions
174
+	 * @param string  $path_to_file         - the csv file to be imported including the path to it's location.
175
+	 *                                      If $model_name is provided, assumes that each row in the CSV represents a
176
+	 *                                      model object for that model If $model_name ISN'T provided, assumes that
177
+	 *                                      before model object data, there is a row where the first entry is simply
178
+	 *                                      'MODEL', and next entry is the model's name, (untranslated) like Event, and
179
+	 *                                      then maybe a row of headers, and then the model data. Eg.
180
+	 *                                      '<br>MODEL,Event,<br>EVT_ID,EVT_name,...<br>1,Monkey
181
+	 *                                      Party,...<br>2,Llamarama,...<br>MODEL,Venue,<br>VNU_ID,VNU_name<br>1,The
182
+	 *                                      Forest
183
+	 * @param string  $model_name           model name if we know what model we're importing
184
+	 * @param boolean $first_row_is_headers - whether the first row of data is headers or not - TRUE = headers, FALSE =
185
+	 *                                      data
186
+	 * @return mixed - array on success - multi dimensional with headers as keys (if headers exist) OR string on fail -
187
+	 *               error message like the following array('Event'=>array( array('EVT_ID'=>1,'EVT_name'=>'bob
188
+	 *               party',...), array('EVT_ID'=>2,'EVT_name'=>'llamarama',...),
189
+	 *                                      ...
190
+	 *                                      )
191
+	 *                                      'Venue'=>array(
192
+	 *                                      array('VNU_ID'=>1,'VNU_name'=>'the shack',...),
193
+	 *                                      array('VNU_ID'=>2,'VNU_name'=>'tree house',...),
194
+	 *                                      ...
195
+	 *                                      )
196
+	 *                                      ...
197
+	 *                                      )
198
+	 */
199
+	public function import_csv_to_model_data_array($path_to_file, $model_name = false, $first_row_is_headers = true)
200
+	{
201
+		$multi_dimensional_array = $this->import_csv_to_multi_dimensional_array($path_to_file);
202
+		if (! $multi_dimensional_array) {
203
+			return false;
204
+		}
205
+		// gotta start somewhere
206
+		$row = 1;
207
+		// array to store csv data in
208
+		$ee_formatted_data = array();
209
+		// array to store headers (column names)
210
+		$headers = array();
211
+		foreach ($multi_dimensional_array as $data) {
212
+			// if first cell is MODEL, then second cell is the MODEL name
213
+			if ($data[0] == 'MODEL') {
214
+				$model_name = $data[1];
215
+				// don't bother looking for model data in this row. The rest of this
216
+				// row should be blank
217
+				// AND pretend this is the first row again
218
+				$row = 1;
219
+				// reset headers
220
+				$headers = array();
221
+				continue;
222
+			}
223
+			if (strpos($data[0], EE_CSV::metadata_header) !== false) {
224
+				$model_name = EE_CSV::metadata_header;
225
+				// store like model data, we just won't try importing it etc.
226
+				$row = 1;
227
+				continue;
228
+			}
229
+
230
+
231
+			// how many columns are there?
232
+			$columns = count($data);
233
+
234
+			$model_entry = array();
235
+			// loop through each column
236
+			for ($i = 0; $i < $columns; $i++) {
237
+				// replace csv_enclosures with backslashed quotes
238
+				$data[ $i ] = str_replace('"""', '\\"', $data[ $i ]);
239
+				// do we need to grab the column names?
240
+				if ($row === 1) {
241
+					if ($first_row_is_headers) {
242
+						// store the column names to use for keys
243
+						$column_name = $data[ $i ];
244
+						// check it's not blank... sometimes CSV editign programs adda bunch of empty columns onto the end...
245
+						if (! $column_name) {
246
+							continue;
247
+						}
248
+						$matches = array();
249
+						if ($model_name == EE_CSV::metadata_header) {
250
+							$headers[ $i ] = $column_name;
251
+						} else {
252
+							// now get the db table name from it (the part between square brackets)
253
+							$success = preg_match('~(.*)\[(.*)\]~', $column_name, $matches);
254
+							if (! $success) {
255
+								EE_Error::add_error(
256
+									sprintf(
257
+										esc_html__(
258
+											"The column titled %s is invalid for importing. It must be be in the format of 'Nice Name[model_field_name]' in row %s",
259
+											"event_espresso"
260
+										),
261
+										$column_name,
262
+										implode(",", $data)
263
+									),
264
+									__FILE__,
265
+									__FUNCTION__,
266
+									__LINE__
267
+								);
268
+								return false;
269
+							}
270
+							$headers[ $i ] = $matches[2];
271
+						}
272
+					} else {
273
+						// no column names means our final array will just use counters for keys
274
+						$model_entry[ $headers[ $i ] ] = $data[ $i ];
275
+						$headers[ $i ] = $i;
276
+					}
277
+					// and we need to store csv data
278
+				} else {
279
+					// this column isn' ta header, store it if there is a header for it
280
+					if (isset($headers[ $i ])) {
281
+						$model_entry[ $headers[ $i ] ] = $data[ $i ];
282
+					}
283
+				}
284
+			}
285
+			// save the row's data IF it's a non-header-row
286
+			if (! $first_row_is_headers || ($first_row_is_headers && $row > 1)) {
287
+				$ee_formatted_data[ $model_name ][] = $model_entry;
288
+			}
289
+			// advance to next row
290
+			$row++;
291
+		}
292
+
293
+		// delete the uploaded file
294
+		unlink($path_to_file);
295
+		// echo '<pre style="height:auto;border:2px solid lightblue;">' . print_r( $ee_formatted_data, TRUE ) . '</pre><br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>';
296
+		// die();
297
+
298
+		// it's good to give back
299
+		return $ee_formatted_data;
300
+	}
301
+
302
+
303
+	public function save_csv_to_db($csv_data_array, $model_name = false)
304
+	{
305
+		EE_Error::doing_it_wrong(
306
+			'save_csv_to_db',
307
+			esc_html__(
308
+				'Function moved to EE_Import and renamed to save_csv_data_array_to_db',
309
+				'event_espresso'
310
+			),
311
+			'4.6.7'
312
+		);
313
+		return EE_Import::instance()->save_csv_data_array_to_db($csv_data_array, $model_name);
314
+	}
315
+
316
+	/**
317
+	 * Sends HTTP headers to indicate that the browser should download a file,
318
+	 * and starts writing the file to PHP's output. Returns the file handle so other functions can
319
+	 * also write to it
320
+	 *
321
+	 * @param string $new_filename the name of the file that the user will download
322
+	 * @return resource, like the results of fopen(), which can be used for fwrite, fputcsv2, etc.
323
+	 */
324
+	public function begin_sending_csv($filename)
325
+	{
326
+		// grab file extension
327
+		$ext = substr(strrchr($filename, '.'), 1);
328
+		if ($ext == '.csv' or $ext == '.xls') {
329
+			str_replace($ext, '', $filename);
330
+		}
331
+		$filename .= '.csv';
332
+
333
+		// if somebody's been naughty and already started outputting stuff, trash it
334
+		// and start writing our stuff.
335
+		if (ob_get_length()) {
336
+			@ob_flush();
337
+			@flush();
338
+			@ob_end_flush();
339
+		}
340
+		@ob_start();
341
+		header("Pragma: public");
342
+		header("Expires: 0");
343
+		header("Pragma: no-cache");
344
+		header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
345
+		// header("Content-Type: application/force-download");
346
+		// header("Content-Type: application/octet-stream");
347
+		// header("Content-Type: application/download");
348
+		header('Content-disposition: attachment; filename=' . $filename);
349
+		header("Content-Type: text/csv; charset=utf-8");
350
+		do_action('AHEE__EE_CSV__begin_sending_csv__headers');
351
+		echo apply_filters(
352
+			'FHEE__EE_CSV__begin_sending_csv__start_writing',
353
+			"\xEF\xBB\xBF"
354
+		); // makes excel open it as UTF-8. UTF-8 BOM, see http://stackoverflow.com/a/4440143/2773835
355
+		$fh = fopen('php://output', 'w');
356
+		return $fh;
357
+	}
358
+
359
+	/**
360
+	 * Writes some meta data to the CSV as a bunch of columns. Initially we're only
361
+	 * mentioning the version and timezone
362
+	 *
363
+	 * @param resource $filehandle
364
+	 */
365
+	public function write_metadata_to_csv($filehandle)
366
+	{
367
+		$data_row = array(EE_CSV::metadata_header);// do NOT translate because this exact string is used when importing
368
+		$this->fputcsv2($filehandle, $data_row);
369
+		$meta_data = array(
370
+			0 => array(
371
+				'version'        => espresso_version(),
372
+				'timezone'       => EEH_DTT_Helper::get_timezone(),
373
+				'time_of_export' => current_time('mysql'),
374
+				'site_url'       => site_url(),
375
+			),
376
+		);
377
+		$this->write_data_array_to_csv($filehandle, $meta_data);
378
+	}
379
+
380
+
381
+	/**
382
+	 * Writes $data to the csv file open in $filehandle. uses the array indices of $data for column headers
383
+	 *
384
+	 * @param array   $data                 2D array, first numerically-indexed, and next-level-down preferably indexed
385
+	 *                                      by string
386
+	 * @param boolean $add_csv_column_names whether or not we should add the keys in the bottom-most array as a row for
387
+	 *                                      headers in the CSV. Eg, if $data looked like
388
+	 *                                      array(0=>array('EVT_ID'=>1,'EVT_name'=>'monkey'...), 1=>array(...),...))
389
+	 *                                      then the first row we'd write to the CSV would be "EVT_ID,EVT_name,..."
390
+	 * @return boolean if we successfully wrote to the CSV or not. If there's no $data, we consider that a success
391
+	 *                 (because we wrote everything there was...nothing)
392
+	 */
393
+	public function write_data_array_to_csv($filehandle, $data)
394
+	{
395
+
396
+
397
+		// determine if $data is actually a 2d array
398
+		if ($data && is_array($data) && is_array(EEH_Array::get_one_item_from_array($data))) {
399
+			// make sure top level is numerically indexed,
400
+
401
+			if (EEH_Array::is_associative_array($data)) {
402
+				throw new EE_Error(
403
+					sprintf(
404
+						esc_html__(
405
+							"top-level array must be numerically indexed. Does these look like numbers to you? %s",
406
+							"event_espresso"
407
+						),
408
+						implode(",", array_keys($data))
409
+					)
410
+				);
411
+			}
412
+			$item_in_top_level_array = EEH_Array::get_one_item_from_array($data);
413
+			// now, is the last item in the top-level array of $data an associative or numeric array?
414
+			if (EEH_Array::is_associative_array($item_in_top_level_array)) {
415
+				// its associative, so we want to output its keys as column headers
416
+				$keys = array_keys($item_in_top_level_array);
417
+				$this->fputcsv2($filehandle, $keys);
418
+			}
419
+			// start writing data
420
+			foreach ($data as $data_row) {
421
+				$this->fputcsv2($filehandle, $data_row);
422
+			}
423
+			return true;
424
+		} else {
425
+			// no data TO write... so we can assume that's a success
426
+			return true;
427
+		}
428
+		// //if 2nd level is indexed by strings, use those as csv column headers (ie, the first row)
429
+		//
430
+		//
431
+		// $no_table = TRUE;
432
+		//
433
+		// // loop through data and add each row to the file/stream as csv
434
+		// foreach ( $data as $model_name => $model_data ) {
435
+		// // test first row to see if it is data or a model name
436
+		// $model = EE_Registry::instance();->load_model($model_name);
437
+		// //if the model really exists,
438
+		// if ( $model ) {
439
+		//
440
+		// // we have a table name
441
+		// $no_table = FALSE;
442
+		//
443
+		// // put the tablename into an array cuz that's how fputcsv rolls
444
+		// $model_name_row = array( 'MODEL', $model_name );
445
+		//
446
+		// // add table name to csv output
447
+		// echo self::fputcsv2($filehandle, $model_name_row);
448
+		//
449
+		// // now get the rest of the data
450
+		// foreach ( $model_data as $row ) {
451
+		// // output the row
452
+		// echo self::fputcsv2($filehandle, $row);
453
+		// }
454
+		//
455
+		// }
456
+		//
457
+		// if ( $no_table ) {
458
+		// // no table so just put the data
459
+		// echo self::fputcsv2($filehandle, $model_data);
460
+		// }
461
+		//
462
+		// } // END OF foreach ( $data )
463
+	}
464
+
465
+	/**
466
+	 * Should be called after begin_sending_csv(), and one or more write_data_array_to_csv()s.
467
+	 * Calls exit to prevent polluting the CSV file with other junk
468
+	 *
469
+	 * @param resource $fh filehandle where we're writing the CSV to
470
+	 */
471
+	public function end_sending_csv($fh)
472
+	{
473
+		fclose($fh);
474
+		exit(0);
475
+	}
476
+
477
+	/**
478
+	 * Given an open file, writes all the model data to it in the format the importer expects.
479
+	 * Usually preceded by begin_sending_csv($filename), and followed by end_sending_csv($filehandle).
480
+	 *
481
+	 * @param resource $filehandle
482
+	 * @param array    $model_data_array is assumed to be a 3d array: 1st layer has keys of model names (eg 'Event'),
483
+	 *                                   next layer is numerically indexed to represent each model object (eg, each
484
+	 *                                   individual event), and the last layer has all the attributes o fthat model
485
+	 *                                   object (eg, the event's id, name, etc)
486
+	 * @return boolean success
487
+	 */
488
+	public function write_model_data_to_csv($filehandle, $model_data_array)
489
+	{
490
+		$this->write_metadata_to_csv($filehandle);
491
+		foreach ($model_data_array as $model_name => $model_instance_arrays) {
492
+			// first: output a special row stating the model
493
+			$this->fputcsv2($filehandle, array('MODEL', $model_name));
494
+			// if we have items to put in the CSV, do it normally
495
+
496
+			if (! empty($model_instance_arrays)) {
497
+				$this->write_data_array_to_csv($filehandle, $model_instance_arrays);
498
+			} else {
499
+				// echo "no data to write... so just write the headers";
500
+				// so there's actually NO model objects for that model.
501
+				// probably still want to show the columns
502
+				$model = EE_Registry::instance()->load_model($model_name);
503
+				$column_names = array();
504
+				foreach ($model->field_settings() as $field) {
505
+					$column_names[ $field->get_nicename() . "[" . $field->get_name() . "]" ] = null;
506
+				}
507
+				$this->write_data_array_to_csv($filehandle, array($column_names));
508
+			}
509
+		}
510
+	}
511
+
512
+	/**
513
+	 * Writes the CSV file to the output buffer, with rows corresponding to $model_data_array,
514
+	 * and dies (in order to avoid other plugins from messing up the csv output)
515
+	 *
516
+	 * @param string $filename         the filename you want to give the file
517
+	 * @param array  $model_data_array 3d array, as described in EE_CSV::write_model_data_to_csv()
518
+	 * @return bool | void writes CSV file to output and dies
519
+	 */
520
+	public function export_multiple_model_data_to_csv($filename, $model_data_array)
521
+	{
522
+		$filehandle = $this->begin_sending_csv($filename);
523
+		$this->write_model_data_to_csv($filehandle, $model_data_array);
524
+		$this->end_sending_csv($filehandle);
525
+	}
526
+
527
+	/**
528
+	 * Export contents of an array to csv file
529
+	 * @param array  $data     - the array of data to be converted to csv and exported
530
+	 * @param string $filename - name for newly created csv file
531
+	 * @return TRUE on success, FALSE on fail
532
+	 */
533
+	public function export_array_to_csv($data = false, $filename = false)
534
+	{
535
+
536
+		// no data file?? get outta here
537
+		if (! $data or ! is_array($data) or empty($data)) {
538
+			return false;
539
+		}
540
+
541
+		// no filename?? get outta here
542
+		if (! $filename) {
543
+			return false;
544
+		}
545
+
546
+
547
+		// somebody told me i might need this ???
548
+		global $wpdb;
549
+		$prefix = $wpdb->prefix;
550
+
551
+
552
+		$fh = $this->begin_sending_csv($filename);
553
+
554
+
555
+		$this->end_sending_csv($fh);
556
+	}
557
+
558
+
559
+	/**
560
+	 * Determine the maximum upload file size based on php.ini settings
561
+	 * @param int $percent_of_max - desired percentage of the max upload_mb
562
+	 * @return int KB
563
+	 */
564
+	public function get_max_upload_size($percent_of_max = false)
565
+	{
566
+
567
+		$max_upload = (int) (ini_get('upload_max_filesize'));
568
+		$max_post = (int) (ini_get('post_max_size'));
569
+		$memory_limit = (int) (ini_get('memory_limit'));
570
+
571
+		// determine the smallest of the three values from above
572
+		$upload_mb = min($max_upload, $max_post, $memory_limit);
573
+
574
+		// convert MB to KB
575
+		$upload_mb = $upload_mb * 1024;
576
+
577
+		// don't want the full monty? then reduce the max uplaod size
578
+		if ($percent_of_max) {
579
+			// is percent_of_max like this -> 50 or like this -> 0.50 ?
580
+			if ($percent_of_max > 1) {
581
+				// chnages 50 to 0.50
582
+				$percent_of_max = $percent_of_max / 100;
583
+			}
584
+			// make upload_mb a percentage of the max upload_mb
585
+			$upload_mb = $upload_mb * $percent_of_max;
586
+		}
587
+
588
+		return $upload_mb;
589
+	}
590
+
591
+
592
+	/**
593
+	 * Drop   in replacement for PHP's fputcsv function - but this one works!!!
594
+	 * @param resource $fh         - file handle - what we are writing to
595
+	 * @param array    $row        - individual row of csv data
596
+	 * @param string   $delimiter  - csv delimiter
597
+	 * @param string   $enclosure  - csv enclosure
598
+	 * @param string   $mysql_null - allows php NULL to be overridden with MySQl's insertable NULL value
599
+	 * @return void
600
+	 */
601
+	private function fputcsv2($fh, array $row, $delimiter = ',', $enclosure = '"', $mysql_null = false)
602
+	{
603
+		// Allow user to filter the csv delimiter and enclosure for other countries csv standards
604
+		$delimiter = apply_filters('FHEE__EE_CSV__fputcsv2__delimiter', $delimiter);
605
+		$enclosure = apply_filters('FHEE__EE_CSV__fputcsv2__enclosure', $enclosure);
606
+
607
+		$delimiter_esc = preg_quote($delimiter, '/');
608
+		$enclosure_esc = preg_quote($enclosure, '/');
609
+
610
+		$output = array();
611
+		foreach ($row as $field_value) {
612
+			if (is_object($field_value) || is_array($field_value)) {
613
+				$field_value = serialize($field_value);
614
+			}
615
+			if ($field_value === null && $mysql_null) {
616
+				$output[] = 'NULL';
617
+				continue;
618
+			}
619
+
620
+			$output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field_value) ?
621
+				($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field_value) . $enclosure)
622
+				: $field_value;
623
+		}
624
+
625
+		fwrite($fh, join($delimiter, $output) . PHP_EOL);
626
+	}
627
+
628
+
629
+	// /**
630
+	//  * CSV    Import / Export messages
631
+	//  * @return void
632
+	//  */
633
+	// public function csv_admin_notices()
634
+	// {
635
+	//
636
+	//     // We play both kinds of music here! Country AND Western! - err... I mean, cycle through both types of notices
637
+	//     foreach (array('updates', 'errors') as $type) {
638
+	//
639
+	//         // if particular notice type is not empty, then "You've got Mail"
640
+	//         if (! empty($this->_notices[ $type ])) {
641
+	//
642
+	//             // is it an update or an error ?
643
+	//             $msg_class = $type == 'updates' ? 'updated' : 'error';
644
+	//             echo '<div id="message" class="' . $msg_class . '">';
645
+	//             // display each notice, however many that may be
646
+	//             foreach ($this->_notices[ $type ] as $message) {
647
+	//                 echo '<p>' . $message . '</p>';
648
+	//             }
649
+	//             // wrap it up
650
+	//             echo '</div>';
651
+	//         }
652
+	//     }
653
+	// }
654
+
655
+	/**
656
+	 * Gets the date format to use in teh csv. filterable
657
+	 *
658
+	 * @param string $current_format
659
+	 * @return string
660
+	 */
661
+	public function get_date_format_for_csv($current_format = null)
662
+	{
663
+		return apply_filters('FHEE__EE_CSV__get_date_format_for_csv__format', 'Y-m-d', $current_format);
664
+	}
665
+
666
+	/**
667
+	 * Gets the time format we want to use in CSV reports. Filterable
668
+	 *
669
+	 * @param string $current_format
670
+	 * @return string
671
+	 */
672
+	public function get_time_format_for_csv($current_format = null)
673
+	{
674
+		return apply_filters('FHEE__EE_CSV__get_time_format_for_csv__format', 'H:i:s', $current_format);
675
+	}
676 676
 }
Please login to merge, or discard this patch.
core/EE_Capabilities.core.php 1 patch
Indentation   +1340 added lines, -1340 removed lines patch added patch discarded remove patch
@@ -14,967 +14,967 @@  discard block
 block discarded – undo
14 14
  */
15 15
 final class EE_Capabilities extends EE_Base
16 16
 {
17
-    const ROLE_ADMINISTRATOR = 'administrator';
18
-
19
-    const ROLE_EVENTS_ADMINISTRATOR = 'ee_events_administrator';
20
-
21
-
22
-    /**
23
-     * the name of the wp option used to store caps previously initialized
24
-     */
25
-    const option_name = 'ee_caps_initialized';
26
-
27
-    private static ?EE_Capabilities $_instance = null;
28
-
29
-
30
-    /**
31
-     * This is a map of caps that correspond to a default WP_Role.
32
-     * Array is indexed by Role and values are ee capabilities.
33
-     *
34
-     * @since 4.5.0
35
-     * @var array
36
-     */
37
-    private array $capabilities_map = [];
38
-
39
-    /**
40
-     * This used to hold an array of EE_Meta_Capability_Map objects
41
-     * that define the granular capabilities mapped to for a user depending on context.
42
-     *
43
-     * @var EE_Meta_Capability_Map[]
44
-     */
45
-    private array $_meta_caps = [];
46
-
47
-    /**
48
-     * The internal $capabilities_map needs to be initialized before it can be used.
49
-     * This flag tracks whether that has happened or not.
50
-     * But for this to work, we need three states to indicate:
51
-     *      initialization has not occurred at all
52
-     *      initialization has started but is not complete
53
-     *      initialization is complete
54
-     * The reason this is needed is because the addCaps() method
55
-     * normally requires the $capabilities_map to be initialized,
56
-     * but is also used during the initialization process.
57
-     * So:
58
-     *      If initialized === null, init_caps() will be called before any other methods will run.
59
-     *      If initialized === false, then init_caps() is in the process of running it's logic.
60
-     *      If initialized === true, then init_caps() has completed the initialization process.
61
-     *
62
-     * @var boolean|null $initialized
63
-     */
64
-    private ?bool $initialized = null;
65
-
66
-    /**
67
-     * @var boolean $reset
68
-     */
69
-    private bool $reset = false;
70
-
71
-
72
-    /**
73
-     * singleton method used to instantiate class object
74
-     *
75
-     * @return EE_Capabilities
76
-     * @since 4.5.0
77
-     */
78
-    public static function instance(): EE_Capabilities
79
-    {
80
-        // check if instantiated, and if not do so.
81
-        if (! self::$_instance instanceof EE_Capabilities) {
82
-            self::$_instance = new self();
83
-        }
84
-        return self::$_instance;
85
-    }
86
-
87
-
88
-    /**
89
-     * private constructor
90
-     *
91
-     * @since 4.5.0
92
-     */
93
-    private function __construct()
94
-    {
95
-    }
96
-
97
-
98
-    /**
99
-     * This delays the initialization of the capabilities class until EE_System core is loaded and ready.
100
-     *
101
-     * @param bool $reset allows for resetting the default capabilities saved on roles.  Note that this doesn't
102
-     *                    actually REMOVE any capabilities from existing roles, it just resaves defaults roles and
103
-     *                    ensures that they are up to date.
104
-     * @since 4.5.0
105
-     * @return bool
106
-     * @throws EE_Error
107
-     */
108
-    public function init_caps(?bool $reset = false): bool
109
-    {
110
-        if (DbStatus::isOffline()) {
111
-            return false;
112
-        }
113
-        $this->reset = filter_var($reset, FILTER_VALIDATE_BOOLEAN);
114
-        // if reset, then completely delete the cache option and clear the $capabilities_map property.
115
-        if ($this->reset) {
116
-            $this->initialized      = null;
117
-            $this->capabilities_map = [];
118
-            delete_option(self::option_name);
119
-        }
120
-        if ($this->initialized === null) {
121
-            $this->initialized = false;
122
-            do_action(
123
-                'AHEE__EE_Capabilities__init_caps__before_initialization',
124
-                $this->reset
125
-            );
126
-            $this->addCaps($this->_init_caps_map());
127
-            $this->_set_meta_caps();
128
-            do_action(
129
-                'AHEE__EE_Capabilities__init_caps__after_initialization',
130
-                $this->capabilities_map
131
-            );
132
-            $this->initialized = true;
133
-        }
134
-        // reset $this->reset so that it's not stuck on true if init_caps() gets called again
135
-        $this->reset = false;
136
-        return true;
137
-    }
138
-
139
-
140
-    /**
141
-     * This sets the meta caps property.
142
-     *
143
-     * @return void
144
-     * @throws EE_Error
145
-     * @since 4.5.0
146
-     */
147
-    private function _set_meta_caps()
148
-    {
149
-        // get default meta caps and filter the returned array
150
-        $this->_meta_caps = apply_filters(
151
-            'FHEE__EE_Capabilities___set_meta_caps__meta_caps',
152
-            $this->_get_default_meta_caps_array()
153
-        );
154
-        // add filter for map_meta_caps but only if models can query.
155
-        if (! has_filter('map_meta_cap', [$this, 'map_meta_caps'])) {
156
-            add_filter('map_meta_cap', [$this, 'map_meta_caps'], 10, 4);
157
-        }
158
-    }
159
-
160
-
161
-    /**
162
-     * This builds and returns the default meta_caps array only once.
163
-     *
164
-     * @return array
165
-     * @throws EE_Error
166
-     * @since  4.8.28.rc.012
167
-     */
168
-    private function _get_default_meta_caps_array(): array
169
-    {
170
-        static $default_meta_caps = [];
171
-        // make sure we're only ever initializing the default _meta_caps array once if it's empty.
172
-        if (empty($default_meta_caps)) {
173
-            $default_meta_caps = [
174
-                // edits
175
-                new EE_Meta_Capability_Map_Edit(
176
-                    'ee_edit_event',
177
-                    ['Event', 'ee_edit_published_events', 'ee_edit_others_events', 'ee_edit_private_events']
178
-                ),
179
-                new EE_Meta_Capability_Map_Edit(
180
-                    'ee_edit_venue',
181
-                    ['Venue', 'ee_edit_published_venues', 'ee_edit_others_venues', 'ee_edit_private_venues']
182
-                ),
183
-                new EE_Meta_Capability_Map_Edit(
184
-                    'ee_edit_registration',
185
-                    ['Registration', '', 'ee_edit_others_registrations', '']
186
-                ),
187
-                new EE_Meta_Capability_Map_Edit(
188
-                    'ee_edit_checkin',
189
-                    ['Registration', '', 'ee_edit_others_checkins', '']
190
-                ),
191
-                new EE_Meta_Capability_Map_Messages_Cap(
192
-                    'ee_edit_message',
193
-                    ['Message_Template_Group', '', 'ee_edit_others_messages', 'ee_edit_global_messages']
194
-                ),
195
-                new EE_Meta_Capability_Map_Edit(
196
-                    'ee_edit_default_ticket',
197
-                    ['Ticket', '', 'ee_edit_others_default_tickets', '']
198
-                ),
199
-                new EE_Meta_Capability_Map_Registration_Form_Cap(
200
-                    'ee_edit_question',
201
-                    ['Question', '', '', 'ee_edit_system_questions']
202
-                ),
203
-                new EE_Meta_Capability_Map_Registration_Form_Cap(
204
-                    'ee_edit_question_group',
205
-                    ['Question_Group', '', '', 'ee_edit_system_question_groups']
206
-                ),
207
-                new EE_Meta_Capability_Map_Edit(
208
-                    'ee_edit_payment_method',
209
-                    ['Payment_Method', '', 'ee_edit_others_payment_methods', '']
210
-                ),
211
-                // reads
212
-                new EE_Meta_Capability_Map_Read(
213
-                    'ee_read_event',
214
-                    ['Event', '', 'ee_read_others_events', 'ee_read_private_events']
215
-                ),
216
-                new EE_Meta_Capability_Map_Read(
217
-                    'ee_read_venue',
218
-                    ['Venue', '', 'ee_read_others_venues', 'ee_read_private_venues']
219
-                ),
220
-                new EE_Meta_Capability_Map_Read(
221
-                    'ee_read_registration',
222
-                    ['Registration', '', 'ee_read_others_registrations', '']
223
-                ),
224
-                new EE_Meta_Capability_Map_Read(
225
-                    'ee_read_checkin',
226
-                    ['Registration', '', 'ee_read_others_checkins', '']
227
-                ),
228
-                new EE_Meta_Capability_Map_Messages_Cap(
229
-                    'ee_read_message',
230
-                    ['Message_Template_Group', '', 'ee_read_others_messages', 'ee_read_global_messages']
231
-                ),
232
-                new EE_Meta_Capability_Map_Read(
233
-                    'ee_read_default_ticket',
234
-                    ['Ticket', '', 'ee_read_others_default_tickets', '']
235
-                ),
236
-                new EE_Meta_Capability_Map_Read(
237
-                    'ee_read_payment_method',
238
-                    ['Payment_Method', '', 'ee_read_others_payment_methods', '']
239
-                ),
240
-                // deletes
241
-                new EE_Meta_Capability_Map_Delete(
242
-                    'ee_delete_event',
243
-                    [
244
-                        'Event',
245
-                        'ee_delete_published_events',
246
-                        'ee_delete_others_events',
247
-                        'ee_delete_private_events',
248
-                    ]
249
-                ),
250
-                new EE_Meta_Capability_Map_Delete(
251
-                    'ee_delete_venue',
252
-                    [
253
-                        'Venue',
254
-                        'ee_delete_published_venues',
255
-                        'ee_delete_others_venues',
256
-                        'ee_delete_private_venues',
257
-                    ]
258
-                ),
259
-                new EE_Meta_Capability_Map_Delete(
260
-                    'ee_delete_registration',
261
-                    ['Registration', '', 'ee_delete_others_registrations', '']
262
-                ),
263
-                new EE_Meta_Capability_Map_Delete(
264
-                    'ee_delete_checkin',
265
-                    ['Registration', '', 'ee_delete_others_checkins', '']
266
-                ),
267
-                new EE_Meta_Capability_Map_Messages_Cap(
268
-                    'ee_delete_message',
269
-                    ['Message_Template_Group', '', 'ee_delete_others_messages', 'ee_delete_global_messages']
270
-                ),
271
-                new EE_Meta_Capability_Map_Delete(
272
-                    'ee_delete_default_ticket',
273
-                    ['Ticket', '', 'ee_delete_others_default_tickets', '']
274
-                ),
275
-                new EE_Meta_Capability_Map_Registration_Form_Cap(
276
-                    'ee_delete_question',
277
-                    ['Question', '', '', 'delete_system_questions']
278
-                ),
279
-                new EE_Meta_Capability_Map_Registration_Form_Cap(
280
-                    'ee_delete_question_group',
281
-                    ['Question_Group', '', '', 'delete_system_question_groups']
282
-                ),
283
-                new EE_Meta_Capability_Map_Delete(
284
-                    'ee_delete_payment_method',
285
-                    ['Payment_Method', '', 'ee_delete_others_payment_methods', '']
286
-                ),
287
-            ];
288
-        }
289
-        return $default_meta_caps;
290
-    }
291
-
292
-
293
-    /**
294
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
295
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
296
-     * The actual logic is carried out by implementer classes in their definition of _map_meta_caps.
297
-     *
298
-     * @param array       $caps    actual users capabilities
299
-     * @param string|null $cap     initial capability name that is being checked (the "map" key)
300
-     * @param int         $user_id The user id
301
-     * @param array       $args    Adds context to the cap. Typically the object ID.
302
-     * @return array actual users capabilities
303
-     * @throws EE_Error
304
-     * @throws ReflectionException
305
-     * @since 4.5.0
306
-     * @see   wp-includes/capabilities.php
307
-     */
308
-    public function map_meta_caps(array $caps, ?string $cap, int $user_id, array $args): array
309
-    {
310
-        if (! $cap || ! did_action('AHEE__EE_System__load_espresso_addons__complete')) {
311
-            return $caps;
312
-        }
313
-        // loop through our _meta_caps array
314
-        foreach ($this->_meta_caps as $meta_map) {
315
-            if (! $meta_map instanceof EE_Meta_Capability_Map) {
316
-                continue;
317
-            }
318
-            // don't load models if there is no object ID in the args
319
-            if (! empty($args[0])) {
320
-                $meta_map->ensure_is_model();
321
-            }
322
-            $caps = $meta_map->map_meta_caps($caps, $cap, $user_id, $args);
323
-        }
324
-        return $caps;
325
-    }
326
-
327
-
328
-    /**
329
-     * This sets up and returns the initial capabilities map for Event Espresso
330
-     * Note this array is filtered.
331
-     * It is assumed that all available EE capabilities are assigned to the administrator role.
332
-     *
333
-     * @return array
334
-     * @since 4.5.0
335
-     */
336
-    private function _init_caps_map(): array
337
-    {
338
-        return apply_filters(
339
-            'FHEE__EE_Capabilities__init_caps_map__caps',
340
-            [
341
-                EE_Capabilities::ROLE_ADMINISTRATOR        => [
342
-                    // basic access
343
-                    'ee_read_ee',
344
-                    // gateways
345
-                    // note that with payment method capabilities, although we've implemented
346
-                    // capability mapping which will be used for accessing payment methods owned by
347
-                    // other users.  This is not fully implemented yet in the payment method ui.
348
-                    // Currently only the "plural" caps are in active use.
349
-                    // (Specific payment method caps are in use as well).
350
-                    'ee_manage_gateways',
351
-                    'ee_read_payment_methods',
352
-                    'ee_read_others_payment_methods',
353
-                    'ee_edit_payment_methods',
354
-                    'ee_edit_others_payment_methods',
355
-                    'ee_delete_payment_methods',
356
-                    // events
357
-                    'ee_publish_events',
358
-                    'ee_read_private_events',
359
-                    'ee_read_others_events',
360
-                    'ee_read_events',
361
-                    'ee_edit_events',
362
-                    'ee_edit_published_events',
363
-                    'ee_edit_others_events',
364
-                    'ee_edit_private_events',
365
-                    'ee_delete_published_events',
366
-                    'ee_delete_private_events',
367
-                    'ee_delete_events',
368
-                    'ee_delete_others_events',
369
-                    // event categories
370
-                    'ee_manage_event_categories',
371
-                    'ee_edit_event_category',
372
-                    'ee_delete_event_category',
373
-                    'ee_assign_event_category',
374
-                    // venues
375
-                    'ee_publish_venues',
376
-                    'ee_read_venues',
377
-                    'ee_read_others_venues',
378
-                    'ee_read_private_venues',
379
-                    'ee_edit_venues',
380
-                    'ee_edit_others_venues',
381
-                    'ee_edit_published_venues',
382
-                    'ee_edit_private_venues',
383
-                    'ee_delete_venues',
384
-                    'ee_delete_others_venues',
385
-                    'ee_delete_private_venues',
386
-                    'ee_delete_published_venues',
387
-                    // venue categories
388
-                    'ee_manage_venue_categories',
389
-                    'ee_edit_venue_category',
390
-                    'ee_delete_venue_category',
391
-                    'ee_assign_venue_category',
392
-                    // contacts
393
-                    'ee_read_contacts',
394
-                    'ee_edit_contacts',
395
-                    'ee_delete_contacts',
396
-                    // registrations
397
-                    'ee_read_registrations',
398
-                    'ee_read_others_registrations',
399
-                    'ee_edit_registrations',
400
-                    'ee_edit_others_registrations',
401
-                    'ee_delete_registrations',
402
-                    'ee_delete_others_registrations',
403
-                    // checkins
404
-                    'ee_read_others_checkins',
405
-                    'ee_read_checkins',
406
-                    'ee_edit_checkins',
407
-                    'ee_edit_others_checkins',
408
-                    'ee_delete_checkins',
409
-                    'ee_delete_others_checkins',
410
-                    // transactions && payments
411
-                    'ee_read_transaction',
412
-                    'ee_read_transactions',
413
-                    'ee_edit_payments',
414
-                    'ee_delete_payments',
415
-                    // messages
416
-                    'ee_read_messages',
417
-                    'ee_read_others_messages',
418
-                    'ee_read_global_messages',
419
-                    'ee_edit_global_messages',
420
-                    'ee_edit_messages',
421
-                    'ee_edit_others_messages',
422
-                    'ee_delete_messages',
423
-                    'ee_delete_others_messages',
424
-                    'ee_delete_global_messages',
425
-                    'ee_send_message',
426
-                    // tickets
427
-                    'ee_read_default_tickets',
428
-                    'ee_read_others_default_tickets',
429
-                    'ee_edit_default_tickets',
430
-                    'ee_edit_others_default_tickets',
431
-                    'ee_delete_default_tickets',
432
-                    'ee_delete_others_default_tickets',
433
-                    // prices
434
-                    'ee_edit_default_price',
435
-                    'ee_edit_default_prices',
436
-                    'ee_delete_default_price',
437
-                    'ee_delete_default_prices',
438
-                    'ee_edit_default_price_type',
439
-                    'ee_edit_default_price_types',
440
-                    'ee_delete_default_price_type',
441
-                    'ee_delete_default_price_types',
442
-                    'ee_read_default_prices',
443
-                    'ee_read_default_price_types',
444
-                    // registration form
445
-                    'ee_edit_questions',
446
-                    'ee_edit_system_questions',
447
-                    'ee_read_questions',
448
-                    'ee_delete_questions',
449
-                    'ee_edit_question_groups',
450
-                    'ee_read_question_groups',
451
-                    'ee_edit_system_question_groups',
452
-                    'ee_delete_question_groups',
453
-                    // event_type taxonomy
454
-                    'ee_assign_event_type',
455
-                    'ee_manage_event_types',
456
-                    'ee_edit_event_type',
457
-                    'ee_delete_event_type',
458
-                ],
459
-                EE_Capabilities::ROLE_EVENTS_ADMINISTRATOR => [
460
-                    // core wp caps
461
-                    'read',
462
-                    'read_private_pages',
463
-                    'read_private_posts',
464
-                    'edit_users',
465
-                    'edit_posts',
466
-                    'edit_pages',
467
-                    'edit_published_posts',
468
-                    'edit_published_pages',
469
-                    'edit_private_pages',
470
-                    'edit_private_posts',
471
-                    'edit_others_posts',
472
-                    'edit_others_pages',
473
-                    'publish_posts',
474
-                    'publish_pages',
475
-                    'delete_posts',
476
-                    'delete_pages',
477
-                    'delete_private_pages',
478
-                    'delete_private_posts',
479
-                    'delete_published_pages',
480
-                    'delete_published_posts',
481
-                    'delete_others_posts',
482
-                    'delete_others_pages',
483
-                    'manage_categories',
484
-                    'manage_links',
485
-                    'moderate_comments',
486
-                    'unfiltered_html',
487
-                    'upload_files',
488
-                    'export',
489
-                    'import',
490
-                    'list_users',
491
-                    'level_1', // required if user with this role shows up in author dropdowns
492
-                    // basic ee access
493
-                    'ee_read_ee',
494
-                    // events
495
-                    'ee_publish_events',
496
-                    'ee_read_private_events',
497
-                    'ee_read_others_events',
498
-                    'ee_read_event',
499
-                    'ee_read_events',
500
-                    'ee_edit_event',
501
-                    'ee_edit_events',
502
-                    'ee_edit_published_events',
503
-                    'ee_edit_others_events',
504
-                    'ee_edit_private_events',
505
-                    'ee_delete_published_events',
506
-                    'ee_delete_private_events',
507
-                    'ee_delete_event',
508
-                    'ee_delete_events',
509
-                    'ee_delete_others_events',
510
-                    // event categories
511
-                    'ee_manage_event_categories',
512
-                    'ee_edit_event_category',
513
-                    'ee_delete_event_category',
514
-                    'ee_assign_event_category',
515
-                    // venues
516
-                    'ee_publish_venues',
517
-                    'ee_read_venue',
518
-                    'ee_read_venues',
519
-                    'ee_read_others_venues',
520
-                    'ee_read_private_venues',
521
-                    'ee_edit_venue',
522
-                    'ee_edit_venues',
523
-                    'ee_edit_others_venues',
524
-                    'ee_edit_published_venues',
525
-                    'ee_edit_private_venues',
526
-                    'ee_delete_venue',
527
-                    'ee_delete_venues',
528
-                    'ee_delete_others_venues',
529
-                    'ee_delete_private_venues',
530
-                    'ee_delete_published_venues',
531
-                    // venue categories
532
-                    'ee_manage_venue_categories',
533
-                    'ee_edit_venue_category',
534
-                    'ee_delete_venue_category',
535
-                    'ee_assign_venue_category',
536
-                    // contacts
537
-                    'ee_read_contacts',
538
-                    'ee_edit_contacts',
539
-                    'ee_delete_contacts',
540
-                    // registrations
541
-                    'ee_read_registrations',
542
-                    'ee_read_others_registrations',
543
-                    'ee_edit_registration',
544
-                    'ee_edit_registrations',
545
-                    'ee_edit_others_registrations',
546
-                    'ee_delete_registration',
547
-                    'ee_delete_registrations',
548
-                    'ee_delete_others_registrations',
549
-                    // checkins
550
-                    'ee_read_others_checkins',
551
-                    'ee_read_checkins',
552
-                    'ee_edit_checkins',
553
-                    'ee_edit_others_checkins',
554
-                    'ee_delete_checkins',
555
-                    'ee_delete_others_checkins',
556
-                    // transactions && payments
557
-                    'ee_read_transaction',
558
-                    'ee_read_transactions',
559
-                    'ee_edit_payments',
560
-                    'ee_delete_payments',
561
-                    // messages
562
-                    'ee_read_messages',
563
-                    'ee_read_others_messages',
564
-                    'ee_read_global_messages',
565
-                    'ee_edit_global_messages',
566
-                    'ee_edit_messages',
567
-                    'ee_edit_others_messages',
568
-                    'ee_delete_messages',
569
-                    'ee_delete_others_messages',
570
-                    'ee_delete_global_messages',
571
-                    'ee_send_message',
572
-                    // tickets
573
-                    'ee_read_default_tickets',
574
-                    'ee_read_others_default_tickets',
575
-                    'ee_edit_default_tickets',
576
-                    'ee_edit_others_default_tickets',
577
-                    'ee_delete_default_tickets',
578
-                    'ee_delete_others_default_tickets',
579
-                    // prices
580
-                    'ee_edit_default_price',
581
-                    'ee_edit_default_prices',
582
-                    'ee_delete_default_price',
583
-                    'ee_delete_default_prices',
584
-                    'ee_edit_default_price_type',
585
-                    'ee_edit_default_price_types',
586
-                    'ee_delete_default_price_type',
587
-                    'ee_delete_default_price_types',
588
-                    'ee_read_default_prices',
589
-                    'ee_read_default_price_types',
590
-                    // registration form
591
-                    'ee_edit_questions',
592
-                    'ee_edit_system_questions',
593
-                    'ee_read_questions',
594
-                    'ee_delete_questions',
595
-                    'ee_edit_question_groups',
596
-                    'ee_read_question_groups',
597
-                    'ee_edit_system_question_groups',
598
-                    'ee_delete_question_groups',
599
-                    // event_type taxonomy
600
-                    'ee_assign_event_type',
601
-                    'ee_manage_event_types',
602
-                    'ee_edit_event_type',
603
-                    'ee_delete_event_type',
604
-                ],
605
-            ]
606
-        );
607
-    }
608
-
609
-
610
-    /**
611
-     * @return bool
612
-     * @throws EE_Error
613
-     */
614
-    private function setupCapabilitiesMap(): bool
615
-    {
616
-        // if the initialization process hasn't even started, then we need to call init_caps()
617
-        if ($this->initialized === null) {
618
-            return $this->init_caps();
619
-        }
620
-        // unless resetting, get caps from db if we haven't already
621
-        $this->capabilities_map = $this->reset || ! empty($this->capabilities_map)
622
-            ? $this->capabilities_map
623
-            : get_option(self::option_name, []);
624
-        return true;
625
-    }
626
-
627
-
628
-    /**
629
-     * @param bool $update
630
-     * @return bool
631
-     */
632
-    private function updateCapabilitiesMap(bool $update = true): bool
633
-    {
634
-        return $update && update_option(self::option_name, $this->capabilities_map);
635
-    }
636
-
637
-
638
-    /**
639
-     * Adds capabilities to roles.
640
-     *
641
-     * @param array $capabilities_to_add array of capabilities to add, indexed by roles.
642
-     *                                   Note that this should ONLY be called on activation hook
643
-     *                                   otherwise the caps will be added on every request.
644
-     * @return bool
645
-     * @throws EE_Error
646
-     * @since 4.9.42
647
-     */
648
-    public function addCaps(array $capabilities_to_add): bool
649
-    {
650
-        // don't do anything if the capabilities map can not be initialized
651
-        if (! $this->setupCapabilitiesMap()) {
652
-            return false;
653
-        }
654
-        // and filter the array so others can get in on the fun during resets
655
-        $capabilities_to_add     = apply_filters(
656
-            'FHEE__EE_Capabilities__addCaps__capabilities_to_add',
657
-            $capabilities_to_add,
658
-            $this->reset,
659
-            $this->capabilities_map
660
-        );
661
-        $update_capabilities_map = false;
662
-        // if not reset, see what caps are new for each role. if they're new, add them.
663
-        foreach ($capabilities_to_add as $role => $caps_for_role) {
664
-            if (is_array($caps_for_role)) {
665
-                foreach ($caps_for_role as $cap) {
666
-                    if (
667
-                        ! $this->capHasBeenAddedToRole($role, $cap)
668
-                        && $this->add_cap_to_role($role, $cap, true, false)
669
-                    ) {
670
-                        $update_capabilities_map = true;
671
-                    }
672
-                }
673
-            }
674
-        }
675
-        // now let's just save the cap that has been set but only if there's been a change.
676
-        $updated = $this->updateCapabilitiesMap($update_capabilities_map);
677
-        $this->flushWpUser($updated);
678
-        do_action('AHEE__EE_Capabilities__addCaps__complete', $this->capabilities_map, $updated);
679
-        return $updated;
680
-    }
681
-
682
-
683
-    /**
684
-     * Loops through the capabilities map and removes the role caps specified by the incoming array
685
-     *
686
-     * @param array $caps_map map of capabilities to be removed (indexed by roles)
687
-     * @return bool
688
-     * @throws EE_Error
689
-     */
690
-    public function removeCaps(array $caps_map): bool
691
-    {
692
-        // don't do anything if the capabilities map can not be initialized
693
-        if (! $this->setupCapabilitiesMap()) {
694
-            return false;
695
-        }
696
-        $update_capabilities_map = false;
697
-        foreach ($caps_map as $role => $caps_for_role) {
698
-            if (is_array($caps_for_role)) {
699
-                foreach ($caps_for_role as $cap) {
700
-                    if (
701
-                        $this->capHasBeenAddedToRole($role, $cap)
702
-                        && $this->remove_cap_from_role($role, $cap, false)
703
-                    ) {
704
-                        $update_capabilities_map = true;
705
-                    }
706
-                }
707
-            }
708
-        }
709
-        // maybe resave the caps
710
-        $updated = $this->updateCapabilitiesMap($update_capabilities_map);
711
-        $this->flushWpUser($updated);
712
-        return $updated;
713
-    }
714
-
715
-
716
-    /**
717
-     * This ensures that the WP User object cached on the $current_user global in WP has the latest capabilities from
718
-     * the roles on that user.
719
-     *
720
-     * @param bool $flush Default is to flush the WP_User object.  If false, then this method effectively does nothing.
721
-     */
722
-    private function flushWpUser(bool $flush = true)
723
-    {
724
-        if ($flush) {
725
-            $user = wp_get_current_user();
726
-            if ($user instanceof WP_User) {
727
-                $user->get_role_caps();
728
-            }
729
-        }
730
-    }
731
-
732
-
733
-    /**
734
-     * This method sets a capability on a role.  Note this should only be done on activation, or if you have something
735
-     * specific to prevent the cap from being added on every page load (adding caps are persistent to the db). Note.
736
-     * this is a wrapper for $wp_role->add_cap()
737
-     *
738
-     * @param string|WP_Role $role  A WordPress role the capability is being added to
739
-     * @param string         $cap   The capability being added to the role
740
-     * @param bool           $grant Whether to grant access to this cap on this role.
741
-     * @param bool           $update_capabilities_map
742
-     * @return bool
743
-     * @throws EE_Error
744
-     * @see   wp-includes/capabilities.php
745
-     * @since 4.5.0
746
-     */
747
-    public function add_cap_to_role(
748
-        $role,
749
-        string $cap,
750
-        bool $grant = true,
751
-        bool $update_capabilities_map = true
752
-    ): bool {
753
-        // capture incoming value for $role because we may need it to create a new WP_Role
754
-        $orig_role = $role;
755
-        $role      = $role instanceof WP_Role ? $role : get_role($role);
756
-        // if the role isn't available then we create it.
757
-        if (! $role instanceof WP_Role) {
758
-            // if a plugin wants to create a specific role name then they should create the role before
759
-            // EE_Capabilities does.  Otherwise this function will create the role name from the slug:
760
-            // - removes any `ee_` namespacing from the start of the slug.
761
-            // - replaces `_` with ` ` (empty space).
762
-            // - sentence case on the resulting string.
763
-            $role_label = ucwords(str_replace(['ee_', '_'], ['', ' '], $orig_role));
764
-            $role       = add_role($orig_role, $role_label);
765
-        }
766
-        if ($role instanceof WP_Role) {
767
-            // don't do anything if the capabilities map can not be initialized
768
-            if (! $this->setupCapabilitiesMap()) {
769
-                return false;
770
-            }
771
-            if (! $this->capHasBeenAddedToRole($role->name, $cap)) {
772
-                $role->add_cap($cap, $grant);
773
-                $this->capabilities_map[ $role->name ][] = $cap;
774
-                $this->updateCapabilitiesMap($update_capabilities_map);
775
-                return true;
776
-            }
777
-        }
778
-        return false;
779
-    }
780
-
781
-
782
-    /**
783
-     * Functions similarly to add_cap_to_role except removes cap from given role.
784
-     * Wrapper for $wp_role->remove_cap()
785
-     *
786
-     * @param string|WP_Role $role A WordPress role the capability is being removed from.
787
-     * @param string         $cap  The capability being removed
788
-     * @param bool           $update_capabilities_map
789
-     * @return bool
790
-     * @throws EE_Error
791
-     * @since 4.5.0
792
-     * @see   wp-includes/capabilities.php
793
-     */
794
-    public function remove_cap_from_role($role, string $cap, bool $update_capabilities_map = true): bool
795
-    {
796
-        // don't do anything if the capabilities map can not be initialized
797
-        if (! $this->setupCapabilitiesMap()) {
798
-            return false;
799
-        }
800
-
801
-        $role = $role instanceof WP_Role ? $role : get_role($role);
802
-        if ($role instanceof WP_Role && $index = $this->capHasBeenAddedToRole($role->name, $cap, true)) {
803
-            $role->remove_cap($cap);
804
-            unset($this->capabilities_map[ $role->name ][ $index ]);
805
-            $this->updateCapabilitiesMap($update_capabilities_map);
806
-            return true;
807
-        }
808
-        return false;
809
-    }
810
-
811
-
812
-    /**
813
-     * @param string $role_name
814
-     * @param string $cap
815
-     * @param bool   $get_index
816
-     * @return bool|int|string
817
-     */
818
-    private function capHasBeenAddedToRole(string $role_name = '', string $cap = '', bool $get_index = false)
819
-    {
820
-        if (
821
-            isset($this->capabilities_map[ $role_name ])
822
-            && ($index = array_search($cap, $this->capabilities_map[ $role_name ], true)) !== false
823
-        ) {
824
-            return $get_index ? $index : true;
825
-        }
826
-        return false;
827
-    }
828
-
829
-
830
-    /**
831
-     * Wrapper for the native WP current_user_can() method.
832
-     * This is provided as a handy method for a couple things:
833
-     * 1. Using the context string it allows for targeted filtering by addons for a specific check (without having to
834
-     * write those filters wherever current_user_can is called).
835
-     * 2. Explicit passing of $id from a given context ( useful in the cases of map_meta_cap filters )
836
-     *
837
-     * @param string     $cap     The cap being checked.
838
-     * @param string     $context The context where the current_user_can is being called from.
839
-     * @param int|string $id      [optional] ID for entity where current_user_can() is being called from
840
-     *                            (used in map_meta_cap() filters).
841
-     * @return bool  Whether user can or not.
842
-     * @since 4.5.0
843
-     */
844
-    public function current_user_can(string $cap, string $context, $id = 0): bool
845
-    {
846
-        // apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
847
-        $filtered_cap = apply_filters(
848
-            'FHEE__EE_Capabilities__current_user_can__cap',
849
-            apply_filters('FHEE__EE_Capabilities__current_user_can__cap__' . $context, $cap, $id),
850
-            $context,
851
-            $cap,
852
-            $id
853
-        );
854
-        return ! empty($id) ? current_user_can($filtered_cap, $id) : current_user_can($filtered_cap);
855
-    }
856
-
857
-
858
-    /**
859
-     * This is a wrapper for the WP user_can() function and follows the same style as the other wrappers in this class.
860
-     *
861
-     * @param int|WP_User $user    Either the user_id or a WP_User object
862
-     * @param string      $cap     The capability string being checked
863
-     * @param string      $context The context where the user_can is being called from (used in filters).
864
-     * @param int         $id      Optional. Id for item where user_can is being called from ( used in map_meta_cap()
865
-     *                             filters)
866
-     * @return bool Whether user can or not.
867
-     */
868
-    public function user_can($user, string $cap, string $context, int $id = 0): bool
869
-    {
870
-        // apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
871
-        $filtered_cap = apply_filters('FHEE__EE_Capabilities__user_can__cap__' . $context, $cap, $user, $id);
872
-        $filtered_cap = apply_filters(
873
-            'FHEE__EE_Capabilities__user_can__cap',
874
-            $filtered_cap,
875
-            $context,
876
-            $cap,
877
-            $user,
878
-            $id
879
-        );
880
-        return ! empty($id) ? user_can($user, $filtered_cap, $id) : user_can($user, $filtered_cap);
881
-    }
882
-
883
-
884
-    /**
885
-     * Wrapper for the native WP current_user_can_for_blog() method.
886
-     * This is provided as a handy method for a couple things:
887
-     * 1. Using the context string it allows for targeted filtering by addons for a specific check (without having to
888
-     * write those filters wherever current_user_can is called).
889
-     * 2. Explicit passing of $id from a given context ( useful in the cases of map_meta_cap filters )
890
-     *
891
-     * @param int    $blog_id The blog id that is being checked for.
892
-     * @param string $cap     The cap being checked.
893
-     * @param string $context The context where the current_user_can is being called from.
894
-     * @param int    $id      Optional. Id for item where current_user_can is being called from (used in map_meta_cap()
895
-     *                        filters.
896
-     * @return bool  Whether user can or not.
897
-     * @since 4.5.0
898
-     */
899
-    public function current_user_can_for_blog(int $blog_id, string $cap, string $context, int $id = 0): bool
900
-    {
901
-        $user_can = ! empty($id) ? current_user_can_for_blog($blog_id, $cap, $id) : current_user_can($blog_id, $cap);
902
-        // apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
903
-        $user_can = apply_filters(
904
-            'FHEE__EE_Capabilities__current_user_can_for_blog__user_can__' . $context,
905
-            $user_can,
906
-            $blog_id,
907
-            $cap,
908
-            $id
909
-        );
910
-        return apply_filters(
911
-            'FHEE__EE_Capabilities__current_user_can_for_blog__user_can',
912
-            $user_can,
913
-            $context,
914
-            $blog_id,
915
-            $cap,
916
-            $id
917
-        );
918
-    }
919
-
920
-
921
-    /**
922
-     * This helper method just returns an array of registered EE capabilities.
923
-     *
924
-     * @param string|null $role If empty then the entire role/capability map is returned.
925
-     *                          Otherwise just the capabilities for the given role are returned.
926
-     * @return array
927
-     * @throws EE_Error
928
-     * @since 4.5.0
929
-     */
930
-    public function get_ee_capabilities(?string $role = EE_Capabilities::ROLE_ADMINISTRATOR): array
931
-    {
932
-        if (! $this->initialized) {
933
-            $this->init_caps();
934
-        }
935
-        if ($role === '') {
936
-            return $this->capabilities_map;
937
-        }
938
-        return $this->capabilities_map[ $role ] ?? [];
939
-    }
940
-
941
-
942
-    /**
943
-     * @param bool  $reset      If you need to reset Event Espresso's capabilities,
944
-     *                          then please use the init_caps() method with the "$reset" parameter set to "true"
945
-     * @param array $caps_map   Optional.
946
-     *                          Can be used to send a custom map of roles and capabilities for setting them up.
947
-     *                          Note that this should ONLY be called on activation hook or some other one-time
948
-     *                          task otherwise the caps will be added on every request.
949
-     * @return void
950
-     * @throws EE_Error
951
-     * @deprecated 4.9.42
952
-     */
953
-    public function init_role_caps(bool $reset = false, array $caps_map = [])
954
-    {
955
-        // If this method is called directly and reset is set as 'true',
956
-        // then display a doing it wrong notice, because we want resets to go through init_caps()
957
-        // to guarantee that everything is set up correctly.
958
-        // This prevents the capabilities map getting reset incorrectly by direct calls to this method.
959
-        if ($reset) {
960
-            EE_Error::doing_it_wrong(
961
-                __METHOD__,
962
-                sprintf(
963
-                    esc_html__(
964
-                        'The "%1$s" parameter for the "%2$s" method is deprecated. If you need to reset Event Espresso\'s capabilities, then please use the "%3$s" method with the "%1$s" parameter set to "%4$s".',
965
-                        'event_espresso'
966
-                    ),
967
-                    '$reset',
968
-                    __METHOD__ . '()',
969
-                    'EE_Capabilities::init_caps()',
970
-                    'true'
971
-                ),
972
-                '4.9.42',
973
-                '5.0.0'
974
-            );
975
-        }
976
-        $this->addCaps($caps_map);
977
-    }
17
+	const ROLE_ADMINISTRATOR = 'administrator';
18
+
19
+	const ROLE_EVENTS_ADMINISTRATOR = 'ee_events_administrator';
20
+
21
+
22
+	/**
23
+	 * the name of the wp option used to store caps previously initialized
24
+	 */
25
+	const option_name = 'ee_caps_initialized';
26
+
27
+	private static ?EE_Capabilities $_instance = null;
28
+
29
+
30
+	/**
31
+	 * This is a map of caps that correspond to a default WP_Role.
32
+	 * Array is indexed by Role and values are ee capabilities.
33
+	 *
34
+	 * @since 4.5.0
35
+	 * @var array
36
+	 */
37
+	private array $capabilities_map = [];
38
+
39
+	/**
40
+	 * This used to hold an array of EE_Meta_Capability_Map objects
41
+	 * that define the granular capabilities mapped to for a user depending on context.
42
+	 *
43
+	 * @var EE_Meta_Capability_Map[]
44
+	 */
45
+	private array $_meta_caps = [];
46
+
47
+	/**
48
+	 * The internal $capabilities_map needs to be initialized before it can be used.
49
+	 * This flag tracks whether that has happened or not.
50
+	 * But for this to work, we need three states to indicate:
51
+	 *      initialization has not occurred at all
52
+	 *      initialization has started but is not complete
53
+	 *      initialization is complete
54
+	 * The reason this is needed is because the addCaps() method
55
+	 * normally requires the $capabilities_map to be initialized,
56
+	 * but is also used during the initialization process.
57
+	 * So:
58
+	 *      If initialized === null, init_caps() will be called before any other methods will run.
59
+	 *      If initialized === false, then init_caps() is in the process of running it's logic.
60
+	 *      If initialized === true, then init_caps() has completed the initialization process.
61
+	 *
62
+	 * @var boolean|null $initialized
63
+	 */
64
+	private ?bool $initialized = null;
65
+
66
+	/**
67
+	 * @var boolean $reset
68
+	 */
69
+	private bool $reset = false;
70
+
71
+
72
+	/**
73
+	 * singleton method used to instantiate class object
74
+	 *
75
+	 * @return EE_Capabilities
76
+	 * @since 4.5.0
77
+	 */
78
+	public static function instance(): EE_Capabilities
79
+	{
80
+		// check if instantiated, and if not do so.
81
+		if (! self::$_instance instanceof EE_Capabilities) {
82
+			self::$_instance = new self();
83
+		}
84
+		return self::$_instance;
85
+	}
86
+
87
+
88
+	/**
89
+	 * private constructor
90
+	 *
91
+	 * @since 4.5.0
92
+	 */
93
+	private function __construct()
94
+	{
95
+	}
96
+
97
+
98
+	/**
99
+	 * This delays the initialization of the capabilities class until EE_System core is loaded and ready.
100
+	 *
101
+	 * @param bool $reset allows for resetting the default capabilities saved on roles.  Note that this doesn't
102
+	 *                    actually REMOVE any capabilities from existing roles, it just resaves defaults roles and
103
+	 *                    ensures that they are up to date.
104
+	 * @since 4.5.0
105
+	 * @return bool
106
+	 * @throws EE_Error
107
+	 */
108
+	public function init_caps(?bool $reset = false): bool
109
+	{
110
+		if (DbStatus::isOffline()) {
111
+			return false;
112
+		}
113
+		$this->reset = filter_var($reset, FILTER_VALIDATE_BOOLEAN);
114
+		// if reset, then completely delete the cache option and clear the $capabilities_map property.
115
+		if ($this->reset) {
116
+			$this->initialized      = null;
117
+			$this->capabilities_map = [];
118
+			delete_option(self::option_name);
119
+		}
120
+		if ($this->initialized === null) {
121
+			$this->initialized = false;
122
+			do_action(
123
+				'AHEE__EE_Capabilities__init_caps__before_initialization',
124
+				$this->reset
125
+			);
126
+			$this->addCaps($this->_init_caps_map());
127
+			$this->_set_meta_caps();
128
+			do_action(
129
+				'AHEE__EE_Capabilities__init_caps__after_initialization',
130
+				$this->capabilities_map
131
+			);
132
+			$this->initialized = true;
133
+		}
134
+		// reset $this->reset so that it's not stuck on true if init_caps() gets called again
135
+		$this->reset = false;
136
+		return true;
137
+	}
138
+
139
+
140
+	/**
141
+	 * This sets the meta caps property.
142
+	 *
143
+	 * @return void
144
+	 * @throws EE_Error
145
+	 * @since 4.5.0
146
+	 */
147
+	private function _set_meta_caps()
148
+	{
149
+		// get default meta caps and filter the returned array
150
+		$this->_meta_caps = apply_filters(
151
+			'FHEE__EE_Capabilities___set_meta_caps__meta_caps',
152
+			$this->_get_default_meta_caps_array()
153
+		);
154
+		// add filter for map_meta_caps but only if models can query.
155
+		if (! has_filter('map_meta_cap', [$this, 'map_meta_caps'])) {
156
+			add_filter('map_meta_cap', [$this, 'map_meta_caps'], 10, 4);
157
+		}
158
+	}
159
+
160
+
161
+	/**
162
+	 * This builds and returns the default meta_caps array only once.
163
+	 *
164
+	 * @return array
165
+	 * @throws EE_Error
166
+	 * @since  4.8.28.rc.012
167
+	 */
168
+	private function _get_default_meta_caps_array(): array
169
+	{
170
+		static $default_meta_caps = [];
171
+		// make sure we're only ever initializing the default _meta_caps array once if it's empty.
172
+		if (empty($default_meta_caps)) {
173
+			$default_meta_caps = [
174
+				// edits
175
+				new EE_Meta_Capability_Map_Edit(
176
+					'ee_edit_event',
177
+					['Event', 'ee_edit_published_events', 'ee_edit_others_events', 'ee_edit_private_events']
178
+				),
179
+				new EE_Meta_Capability_Map_Edit(
180
+					'ee_edit_venue',
181
+					['Venue', 'ee_edit_published_venues', 'ee_edit_others_venues', 'ee_edit_private_venues']
182
+				),
183
+				new EE_Meta_Capability_Map_Edit(
184
+					'ee_edit_registration',
185
+					['Registration', '', 'ee_edit_others_registrations', '']
186
+				),
187
+				new EE_Meta_Capability_Map_Edit(
188
+					'ee_edit_checkin',
189
+					['Registration', '', 'ee_edit_others_checkins', '']
190
+				),
191
+				new EE_Meta_Capability_Map_Messages_Cap(
192
+					'ee_edit_message',
193
+					['Message_Template_Group', '', 'ee_edit_others_messages', 'ee_edit_global_messages']
194
+				),
195
+				new EE_Meta_Capability_Map_Edit(
196
+					'ee_edit_default_ticket',
197
+					['Ticket', '', 'ee_edit_others_default_tickets', '']
198
+				),
199
+				new EE_Meta_Capability_Map_Registration_Form_Cap(
200
+					'ee_edit_question',
201
+					['Question', '', '', 'ee_edit_system_questions']
202
+				),
203
+				new EE_Meta_Capability_Map_Registration_Form_Cap(
204
+					'ee_edit_question_group',
205
+					['Question_Group', '', '', 'ee_edit_system_question_groups']
206
+				),
207
+				new EE_Meta_Capability_Map_Edit(
208
+					'ee_edit_payment_method',
209
+					['Payment_Method', '', 'ee_edit_others_payment_methods', '']
210
+				),
211
+				// reads
212
+				new EE_Meta_Capability_Map_Read(
213
+					'ee_read_event',
214
+					['Event', '', 'ee_read_others_events', 'ee_read_private_events']
215
+				),
216
+				new EE_Meta_Capability_Map_Read(
217
+					'ee_read_venue',
218
+					['Venue', '', 'ee_read_others_venues', 'ee_read_private_venues']
219
+				),
220
+				new EE_Meta_Capability_Map_Read(
221
+					'ee_read_registration',
222
+					['Registration', '', 'ee_read_others_registrations', '']
223
+				),
224
+				new EE_Meta_Capability_Map_Read(
225
+					'ee_read_checkin',
226
+					['Registration', '', 'ee_read_others_checkins', '']
227
+				),
228
+				new EE_Meta_Capability_Map_Messages_Cap(
229
+					'ee_read_message',
230
+					['Message_Template_Group', '', 'ee_read_others_messages', 'ee_read_global_messages']
231
+				),
232
+				new EE_Meta_Capability_Map_Read(
233
+					'ee_read_default_ticket',
234
+					['Ticket', '', 'ee_read_others_default_tickets', '']
235
+				),
236
+				new EE_Meta_Capability_Map_Read(
237
+					'ee_read_payment_method',
238
+					['Payment_Method', '', 'ee_read_others_payment_methods', '']
239
+				),
240
+				// deletes
241
+				new EE_Meta_Capability_Map_Delete(
242
+					'ee_delete_event',
243
+					[
244
+						'Event',
245
+						'ee_delete_published_events',
246
+						'ee_delete_others_events',
247
+						'ee_delete_private_events',
248
+					]
249
+				),
250
+				new EE_Meta_Capability_Map_Delete(
251
+					'ee_delete_venue',
252
+					[
253
+						'Venue',
254
+						'ee_delete_published_venues',
255
+						'ee_delete_others_venues',
256
+						'ee_delete_private_venues',
257
+					]
258
+				),
259
+				new EE_Meta_Capability_Map_Delete(
260
+					'ee_delete_registration',
261
+					['Registration', '', 'ee_delete_others_registrations', '']
262
+				),
263
+				new EE_Meta_Capability_Map_Delete(
264
+					'ee_delete_checkin',
265
+					['Registration', '', 'ee_delete_others_checkins', '']
266
+				),
267
+				new EE_Meta_Capability_Map_Messages_Cap(
268
+					'ee_delete_message',
269
+					['Message_Template_Group', '', 'ee_delete_others_messages', 'ee_delete_global_messages']
270
+				),
271
+				new EE_Meta_Capability_Map_Delete(
272
+					'ee_delete_default_ticket',
273
+					['Ticket', '', 'ee_delete_others_default_tickets', '']
274
+				),
275
+				new EE_Meta_Capability_Map_Registration_Form_Cap(
276
+					'ee_delete_question',
277
+					['Question', '', '', 'delete_system_questions']
278
+				),
279
+				new EE_Meta_Capability_Map_Registration_Form_Cap(
280
+					'ee_delete_question_group',
281
+					['Question_Group', '', '', 'delete_system_question_groups']
282
+				),
283
+				new EE_Meta_Capability_Map_Delete(
284
+					'ee_delete_payment_method',
285
+					['Payment_Method', '', 'ee_delete_others_payment_methods', '']
286
+				),
287
+			];
288
+		}
289
+		return $default_meta_caps;
290
+	}
291
+
292
+
293
+	/**
294
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
295
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
296
+	 * The actual logic is carried out by implementer classes in their definition of _map_meta_caps.
297
+	 *
298
+	 * @param array       $caps    actual users capabilities
299
+	 * @param string|null $cap     initial capability name that is being checked (the "map" key)
300
+	 * @param int         $user_id The user id
301
+	 * @param array       $args    Adds context to the cap. Typically the object ID.
302
+	 * @return array actual users capabilities
303
+	 * @throws EE_Error
304
+	 * @throws ReflectionException
305
+	 * @since 4.5.0
306
+	 * @see   wp-includes/capabilities.php
307
+	 */
308
+	public function map_meta_caps(array $caps, ?string $cap, int $user_id, array $args): array
309
+	{
310
+		if (! $cap || ! did_action('AHEE__EE_System__load_espresso_addons__complete')) {
311
+			return $caps;
312
+		}
313
+		// loop through our _meta_caps array
314
+		foreach ($this->_meta_caps as $meta_map) {
315
+			if (! $meta_map instanceof EE_Meta_Capability_Map) {
316
+				continue;
317
+			}
318
+			// don't load models if there is no object ID in the args
319
+			if (! empty($args[0])) {
320
+				$meta_map->ensure_is_model();
321
+			}
322
+			$caps = $meta_map->map_meta_caps($caps, $cap, $user_id, $args);
323
+		}
324
+		return $caps;
325
+	}
326
+
327
+
328
+	/**
329
+	 * This sets up and returns the initial capabilities map for Event Espresso
330
+	 * Note this array is filtered.
331
+	 * It is assumed that all available EE capabilities are assigned to the administrator role.
332
+	 *
333
+	 * @return array
334
+	 * @since 4.5.0
335
+	 */
336
+	private function _init_caps_map(): array
337
+	{
338
+		return apply_filters(
339
+			'FHEE__EE_Capabilities__init_caps_map__caps',
340
+			[
341
+				EE_Capabilities::ROLE_ADMINISTRATOR        => [
342
+					// basic access
343
+					'ee_read_ee',
344
+					// gateways
345
+					// note that with payment method capabilities, although we've implemented
346
+					// capability mapping which will be used for accessing payment methods owned by
347
+					// other users.  This is not fully implemented yet in the payment method ui.
348
+					// Currently only the "plural" caps are in active use.
349
+					// (Specific payment method caps are in use as well).
350
+					'ee_manage_gateways',
351
+					'ee_read_payment_methods',
352
+					'ee_read_others_payment_methods',
353
+					'ee_edit_payment_methods',
354
+					'ee_edit_others_payment_methods',
355
+					'ee_delete_payment_methods',
356
+					// events
357
+					'ee_publish_events',
358
+					'ee_read_private_events',
359
+					'ee_read_others_events',
360
+					'ee_read_events',
361
+					'ee_edit_events',
362
+					'ee_edit_published_events',
363
+					'ee_edit_others_events',
364
+					'ee_edit_private_events',
365
+					'ee_delete_published_events',
366
+					'ee_delete_private_events',
367
+					'ee_delete_events',
368
+					'ee_delete_others_events',
369
+					// event categories
370
+					'ee_manage_event_categories',
371
+					'ee_edit_event_category',
372
+					'ee_delete_event_category',
373
+					'ee_assign_event_category',
374
+					// venues
375
+					'ee_publish_venues',
376
+					'ee_read_venues',
377
+					'ee_read_others_venues',
378
+					'ee_read_private_venues',
379
+					'ee_edit_venues',
380
+					'ee_edit_others_venues',
381
+					'ee_edit_published_venues',
382
+					'ee_edit_private_venues',
383
+					'ee_delete_venues',
384
+					'ee_delete_others_venues',
385
+					'ee_delete_private_venues',
386
+					'ee_delete_published_venues',
387
+					// venue categories
388
+					'ee_manage_venue_categories',
389
+					'ee_edit_venue_category',
390
+					'ee_delete_venue_category',
391
+					'ee_assign_venue_category',
392
+					// contacts
393
+					'ee_read_contacts',
394
+					'ee_edit_contacts',
395
+					'ee_delete_contacts',
396
+					// registrations
397
+					'ee_read_registrations',
398
+					'ee_read_others_registrations',
399
+					'ee_edit_registrations',
400
+					'ee_edit_others_registrations',
401
+					'ee_delete_registrations',
402
+					'ee_delete_others_registrations',
403
+					// checkins
404
+					'ee_read_others_checkins',
405
+					'ee_read_checkins',
406
+					'ee_edit_checkins',
407
+					'ee_edit_others_checkins',
408
+					'ee_delete_checkins',
409
+					'ee_delete_others_checkins',
410
+					// transactions && payments
411
+					'ee_read_transaction',
412
+					'ee_read_transactions',
413
+					'ee_edit_payments',
414
+					'ee_delete_payments',
415
+					// messages
416
+					'ee_read_messages',
417
+					'ee_read_others_messages',
418
+					'ee_read_global_messages',
419
+					'ee_edit_global_messages',
420
+					'ee_edit_messages',
421
+					'ee_edit_others_messages',
422
+					'ee_delete_messages',
423
+					'ee_delete_others_messages',
424
+					'ee_delete_global_messages',
425
+					'ee_send_message',
426
+					// tickets
427
+					'ee_read_default_tickets',
428
+					'ee_read_others_default_tickets',
429
+					'ee_edit_default_tickets',
430
+					'ee_edit_others_default_tickets',
431
+					'ee_delete_default_tickets',
432
+					'ee_delete_others_default_tickets',
433
+					// prices
434
+					'ee_edit_default_price',
435
+					'ee_edit_default_prices',
436
+					'ee_delete_default_price',
437
+					'ee_delete_default_prices',
438
+					'ee_edit_default_price_type',
439
+					'ee_edit_default_price_types',
440
+					'ee_delete_default_price_type',
441
+					'ee_delete_default_price_types',
442
+					'ee_read_default_prices',
443
+					'ee_read_default_price_types',
444
+					// registration form
445
+					'ee_edit_questions',
446
+					'ee_edit_system_questions',
447
+					'ee_read_questions',
448
+					'ee_delete_questions',
449
+					'ee_edit_question_groups',
450
+					'ee_read_question_groups',
451
+					'ee_edit_system_question_groups',
452
+					'ee_delete_question_groups',
453
+					// event_type taxonomy
454
+					'ee_assign_event_type',
455
+					'ee_manage_event_types',
456
+					'ee_edit_event_type',
457
+					'ee_delete_event_type',
458
+				],
459
+				EE_Capabilities::ROLE_EVENTS_ADMINISTRATOR => [
460
+					// core wp caps
461
+					'read',
462
+					'read_private_pages',
463
+					'read_private_posts',
464
+					'edit_users',
465
+					'edit_posts',
466
+					'edit_pages',
467
+					'edit_published_posts',
468
+					'edit_published_pages',
469
+					'edit_private_pages',
470
+					'edit_private_posts',
471
+					'edit_others_posts',
472
+					'edit_others_pages',
473
+					'publish_posts',
474
+					'publish_pages',
475
+					'delete_posts',
476
+					'delete_pages',
477
+					'delete_private_pages',
478
+					'delete_private_posts',
479
+					'delete_published_pages',
480
+					'delete_published_posts',
481
+					'delete_others_posts',
482
+					'delete_others_pages',
483
+					'manage_categories',
484
+					'manage_links',
485
+					'moderate_comments',
486
+					'unfiltered_html',
487
+					'upload_files',
488
+					'export',
489
+					'import',
490
+					'list_users',
491
+					'level_1', // required if user with this role shows up in author dropdowns
492
+					// basic ee access
493
+					'ee_read_ee',
494
+					// events
495
+					'ee_publish_events',
496
+					'ee_read_private_events',
497
+					'ee_read_others_events',
498
+					'ee_read_event',
499
+					'ee_read_events',
500
+					'ee_edit_event',
501
+					'ee_edit_events',
502
+					'ee_edit_published_events',
503
+					'ee_edit_others_events',
504
+					'ee_edit_private_events',
505
+					'ee_delete_published_events',
506
+					'ee_delete_private_events',
507
+					'ee_delete_event',
508
+					'ee_delete_events',
509
+					'ee_delete_others_events',
510
+					// event categories
511
+					'ee_manage_event_categories',
512
+					'ee_edit_event_category',
513
+					'ee_delete_event_category',
514
+					'ee_assign_event_category',
515
+					// venues
516
+					'ee_publish_venues',
517
+					'ee_read_venue',
518
+					'ee_read_venues',
519
+					'ee_read_others_venues',
520
+					'ee_read_private_venues',
521
+					'ee_edit_venue',
522
+					'ee_edit_venues',
523
+					'ee_edit_others_venues',
524
+					'ee_edit_published_venues',
525
+					'ee_edit_private_venues',
526
+					'ee_delete_venue',
527
+					'ee_delete_venues',
528
+					'ee_delete_others_venues',
529
+					'ee_delete_private_venues',
530
+					'ee_delete_published_venues',
531
+					// venue categories
532
+					'ee_manage_venue_categories',
533
+					'ee_edit_venue_category',
534
+					'ee_delete_venue_category',
535
+					'ee_assign_venue_category',
536
+					// contacts
537
+					'ee_read_contacts',
538
+					'ee_edit_contacts',
539
+					'ee_delete_contacts',
540
+					// registrations
541
+					'ee_read_registrations',
542
+					'ee_read_others_registrations',
543
+					'ee_edit_registration',
544
+					'ee_edit_registrations',
545
+					'ee_edit_others_registrations',
546
+					'ee_delete_registration',
547
+					'ee_delete_registrations',
548
+					'ee_delete_others_registrations',
549
+					// checkins
550
+					'ee_read_others_checkins',
551
+					'ee_read_checkins',
552
+					'ee_edit_checkins',
553
+					'ee_edit_others_checkins',
554
+					'ee_delete_checkins',
555
+					'ee_delete_others_checkins',
556
+					// transactions && payments
557
+					'ee_read_transaction',
558
+					'ee_read_transactions',
559
+					'ee_edit_payments',
560
+					'ee_delete_payments',
561
+					// messages
562
+					'ee_read_messages',
563
+					'ee_read_others_messages',
564
+					'ee_read_global_messages',
565
+					'ee_edit_global_messages',
566
+					'ee_edit_messages',
567
+					'ee_edit_others_messages',
568
+					'ee_delete_messages',
569
+					'ee_delete_others_messages',
570
+					'ee_delete_global_messages',
571
+					'ee_send_message',
572
+					// tickets
573
+					'ee_read_default_tickets',
574
+					'ee_read_others_default_tickets',
575
+					'ee_edit_default_tickets',
576
+					'ee_edit_others_default_tickets',
577
+					'ee_delete_default_tickets',
578
+					'ee_delete_others_default_tickets',
579
+					// prices
580
+					'ee_edit_default_price',
581
+					'ee_edit_default_prices',
582
+					'ee_delete_default_price',
583
+					'ee_delete_default_prices',
584
+					'ee_edit_default_price_type',
585
+					'ee_edit_default_price_types',
586
+					'ee_delete_default_price_type',
587
+					'ee_delete_default_price_types',
588
+					'ee_read_default_prices',
589
+					'ee_read_default_price_types',
590
+					// registration form
591
+					'ee_edit_questions',
592
+					'ee_edit_system_questions',
593
+					'ee_read_questions',
594
+					'ee_delete_questions',
595
+					'ee_edit_question_groups',
596
+					'ee_read_question_groups',
597
+					'ee_edit_system_question_groups',
598
+					'ee_delete_question_groups',
599
+					// event_type taxonomy
600
+					'ee_assign_event_type',
601
+					'ee_manage_event_types',
602
+					'ee_edit_event_type',
603
+					'ee_delete_event_type',
604
+				],
605
+			]
606
+		);
607
+	}
608
+
609
+
610
+	/**
611
+	 * @return bool
612
+	 * @throws EE_Error
613
+	 */
614
+	private function setupCapabilitiesMap(): bool
615
+	{
616
+		// if the initialization process hasn't even started, then we need to call init_caps()
617
+		if ($this->initialized === null) {
618
+			return $this->init_caps();
619
+		}
620
+		// unless resetting, get caps from db if we haven't already
621
+		$this->capabilities_map = $this->reset || ! empty($this->capabilities_map)
622
+			? $this->capabilities_map
623
+			: get_option(self::option_name, []);
624
+		return true;
625
+	}
626
+
627
+
628
+	/**
629
+	 * @param bool $update
630
+	 * @return bool
631
+	 */
632
+	private function updateCapabilitiesMap(bool $update = true): bool
633
+	{
634
+		return $update && update_option(self::option_name, $this->capabilities_map);
635
+	}
636
+
637
+
638
+	/**
639
+	 * Adds capabilities to roles.
640
+	 *
641
+	 * @param array $capabilities_to_add array of capabilities to add, indexed by roles.
642
+	 *                                   Note that this should ONLY be called on activation hook
643
+	 *                                   otherwise the caps will be added on every request.
644
+	 * @return bool
645
+	 * @throws EE_Error
646
+	 * @since 4.9.42
647
+	 */
648
+	public function addCaps(array $capabilities_to_add): bool
649
+	{
650
+		// don't do anything if the capabilities map can not be initialized
651
+		if (! $this->setupCapabilitiesMap()) {
652
+			return false;
653
+		}
654
+		// and filter the array so others can get in on the fun during resets
655
+		$capabilities_to_add     = apply_filters(
656
+			'FHEE__EE_Capabilities__addCaps__capabilities_to_add',
657
+			$capabilities_to_add,
658
+			$this->reset,
659
+			$this->capabilities_map
660
+		);
661
+		$update_capabilities_map = false;
662
+		// if not reset, see what caps are new for each role. if they're new, add them.
663
+		foreach ($capabilities_to_add as $role => $caps_for_role) {
664
+			if (is_array($caps_for_role)) {
665
+				foreach ($caps_for_role as $cap) {
666
+					if (
667
+						! $this->capHasBeenAddedToRole($role, $cap)
668
+						&& $this->add_cap_to_role($role, $cap, true, false)
669
+					) {
670
+						$update_capabilities_map = true;
671
+					}
672
+				}
673
+			}
674
+		}
675
+		// now let's just save the cap that has been set but only if there's been a change.
676
+		$updated = $this->updateCapabilitiesMap($update_capabilities_map);
677
+		$this->flushWpUser($updated);
678
+		do_action('AHEE__EE_Capabilities__addCaps__complete', $this->capabilities_map, $updated);
679
+		return $updated;
680
+	}
681
+
682
+
683
+	/**
684
+	 * Loops through the capabilities map and removes the role caps specified by the incoming array
685
+	 *
686
+	 * @param array $caps_map map of capabilities to be removed (indexed by roles)
687
+	 * @return bool
688
+	 * @throws EE_Error
689
+	 */
690
+	public function removeCaps(array $caps_map): bool
691
+	{
692
+		// don't do anything if the capabilities map can not be initialized
693
+		if (! $this->setupCapabilitiesMap()) {
694
+			return false;
695
+		}
696
+		$update_capabilities_map = false;
697
+		foreach ($caps_map as $role => $caps_for_role) {
698
+			if (is_array($caps_for_role)) {
699
+				foreach ($caps_for_role as $cap) {
700
+					if (
701
+						$this->capHasBeenAddedToRole($role, $cap)
702
+						&& $this->remove_cap_from_role($role, $cap, false)
703
+					) {
704
+						$update_capabilities_map = true;
705
+					}
706
+				}
707
+			}
708
+		}
709
+		// maybe resave the caps
710
+		$updated = $this->updateCapabilitiesMap($update_capabilities_map);
711
+		$this->flushWpUser($updated);
712
+		return $updated;
713
+	}
714
+
715
+
716
+	/**
717
+	 * This ensures that the WP User object cached on the $current_user global in WP has the latest capabilities from
718
+	 * the roles on that user.
719
+	 *
720
+	 * @param bool $flush Default is to flush the WP_User object.  If false, then this method effectively does nothing.
721
+	 */
722
+	private function flushWpUser(bool $flush = true)
723
+	{
724
+		if ($flush) {
725
+			$user = wp_get_current_user();
726
+			if ($user instanceof WP_User) {
727
+				$user->get_role_caps();
728
+			}
729
+		}
730
+	}
731
+
732
+
733
+	/**
734
+	 * This method sets a capability on a role.  Note this should only be done on activation, or if you have something
735
+	 * specific to prevent the cap from being added on every page load (adding caps are persistent to the db). Note.
736
+	 * this is a wrapper for $wp_role->add_cap()
737
+	 *
738
+	 * @param string|WP_Role $role  A WordPress role the capability is being added to
739
+	 * @param string         $cap   The capability being added to the role
740
+	 * @param bool           $grant Whether to grant access to this cap on this role.
741
+	 * @param bool           $update_capabilities_map
742
+	 * @return bool
743
+	 * @throws EE_Error
744
+	 * @see   wp-includes/capabilities.php
745
+	 * @since 4.5.0
746
+	 */
747
+	public function add_cap_to_role(
748
+		$role,
749
+		string $cap,
750
+		bool $grant = true,
751
+		bool $update_capabilities_map = true
752
+	): bool {
753
+		// capture incoming value for $role because we may need it to create a new WP_Role
754
+		$orig_role = $role;
755
+		$role      = $role instanceof WP_Role ? $role : get_role($role);
756
+		// if the role isn't available then we create it.
757
+		if (! $role instanceof WP_Role) {
758
+			// if a plugin wants to create a specific role name then they should create the role before
759
+			// EE_Capabilities does.  Otherwise this function will create the role name from the slug:
760
+			// - removes any `ee_` namespacing from the start of the slug.
761
+			// - replaces `_` with ` ` (empty space).
762
+			// - sentence case on the resulting string.
763
+			$role_label = ucwords(str_replace(['ee_', '_'], ['', ' '], $orig_role));
764
+			$role       = add_role($orig_role, $role_label);
765
+		}
766
+		if ($role instanceof WP_Role) {
767
+			// don't do anything if the capabilities map can not be initialized
768
+			if (! $this->setupCapabilitiesMap()) {
769
+				return false;
770
+			}
771
+			if (! $this->capHasBeenAddedToRole($role->name, $cap)) {
772
+				$role->add_cap($cap, $grant);
773
+				$this->capabilities_map[ $role->name ][] = $cap;
774
+				$this->updateCapabilitiesMap($update_capabilities_map);
775
+				return true;
776
+			}
777
+		}
778
+		return false;
779
+	}
780
+
781
+
782
+	/**
783
+	 * Functions similarly to add_cap_to_role except removes cap from given role.
784
+	 * Wrapper for $wp_role->remove_cap()
785
+	 *
786
+	 * @param string|WP_Role $role A WordPress role the capability is being removed from.
787
+	 * @param string         $cap  The capability being removed
788
+	 * @param bool           $update_capabilities_map
789
+	 * @return bool
790
+	 * @throws EE_Error
791
+	 * @since 4.5.0
792
+	 * @see   wp-includes/capabilities.php
793
+	 */
794
+	public function remove_cap_from_role($role, string $cap, bool $update_capabilities_map = true): bool
795
+	{
796
+		// don't do anything if the capabilities map can not be initialized
797
+		if (! $this->setupCapabilitiesMap()) {
798
+			return false;
799
+		}
800
+
801
+		$role = $role instanceof WP_Role ? $role : get_role($role);
802
+		if ($role instanceof WP_Role && $index = $this->capHasBeenAddedToRole($role->name, $cap, true)) {
803
+			$role->remove_cap($cap);
804
+			unset($this->capabilities_map[ $role->name ][ $index ]);
805
+			$this->updateCapabilitiesMap($update_capabilities_map);
806
+			return true;
807
+		}
808
+		return false;
809
+	}
810
+
811
+
812
+	/**
813
+	 * @param string $role_name
814
+	 * @param string $cap
815
+	 * @param bool   $get_index
816
+	 * @return bool|int|string
817
+	 */
818
+	private function capHasBeenAddedToRole(string $role_name = '', string $cap = '', bool $get_index = false)
819
+	{
820
+		if (
821
+			isset($this->capabilities_map[ $role_name ])
822
+			&& ($index = array_search($cap, $this->capabilities_map[ $role_name ], true)) !== false
823
+		) {
824
+			return $get_index ? $index : true;
825
+		}
826
+		return false;
827
+	}
828
+
829
+
830
+	/**
831
+	 * Wrapper for the native WP current_user_can() method.
832
+	 * This is provided as a handy method for a couple things:
833
+	 * 1. Using the context string it allows for targeted filtering by addons for a specific check (without having to
834
+	 * write those filters wherever current_user_can is called).
835
+	 * 2. Explicit passing of $id from a given context ( useful in the cases of map_meta_cap filters )
836
+	 *
837
+	 * @param string     $cap     The cap being checked.
838
+	 * @param string     $context The context where the current_user_can is being called from.
839
+	 * @param int|string $id      [optional] ID for entity where current_user_can() is being called from
840
+	 *                            (used in map_meta_cap() filters).
841
+	 * @return bool  Whether user can or not.
842
+	 * @since 4.5.0
843
+	 */
844
+	public function current_user_can(string $cap, string $context, $id = 0): bool
845
+	{
846
+		// apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
847
+		$filtered_cap = apply_filters(
848
+			'FHEE__EE_Capabilities__current_user_can__cap',
849
+			apply_filters('FHEE__EE_Capabilities__current_user_can__cap__' . $context, $cap, $id),
850
+			$context,
851
+			$cap,
852
+			$id
853
+		);
854
+		return ! empty($id) ? current_user_can($filtered_cap, $id) : current_user_can($filtered_cap);
855
+	}
856
+
857
+
858
+	/**
859
+	 * This is a wrapper for the WP user_can() function and follows the same style as the other wrappers in this class.
860
+	 *
861
+	 * @param int|WP_User $user    Either the user_id or a WP_User object
862
+	 * @param string      $cap     The capability string being checked
863
+	 * @param string      $context The context where the user_can is being called from (used in filters).
864
+	 * @param int         $id      Optional. Id for item where user_can is being called from ( used in map_meta_cap()
865
+	 *                             filters)
866
+	 * @return bool Whether user can or not.
867
+	 */
868
+	public function user_can($user, string $cap, string $context, int $id = 0): bool
869
+	{
870
+		// apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
871
+		$filtered_cap = apply_filters('FHEE__EE_Capabilities__user_can__cap__' . $context, $cap, $user, $id);
872
+		$filtered_cap = apply_filters(
873
+			'FHEE__EE_Capabilities__user_can__cap',
874
+			$filtered_cap,
875
+			$context,
876
+			$cap,
877
+			$user,
878
+			$id
879
+		);
880
+		return ! empty($id) ? user_can($user, $filtered_cap, $id) : user_can($user, $filtered_cap);
881
+	}
882
+
883
+
884
+	/**
885
+	 * Wrapper for the native WP current_user_can_for_blog() method.
886
+	 * This is provided as a handy method for a couple things:
887
+	 * 1. Using the context string it allows for targeted filtering by addons for a specific check (without having to
888
+	 * write those filters wherever current_user_can is called).
889
+	 * 2. Explicit passing of $id from a given context ( useful in the cases of map_meta_cap filters )
890
+	 *
891
+	 * @param int    $blog_id The blog id that is being checked for.
892
+	 * @param string $cap     The cap being checked.
893
+	 * @param string $context The context where the current_user_can is being called from.
894
+	 * @param int    $id      Optional. Id for item where current_user_can is being called from (used in map_meta_cap()
895
+	 *                        filters.
896
+	 * @return bool  Whether user can or not.
897
+	 * @since 4.5.0
898
+	 */
899
+	public function current_user_can_for_blog(int $blog_id, string $cap, string $context, int $id = 0): bool
900
+	{
901
+		$user_can = ! empty($id) ? current_user_can_for_blog($blog_id, $cap, $id) : current_user_can($blog_id, $cap);
902
+		// apply filters (both a global on just the cap, and context specific.  Global overrides context specific)
903
+		$user_can = apply_filters(
904
+			'FHEE__EE_Capabilities__current_user_can_for_blog__user_can__' . $context,
905
+			$user_can,
906
+			$blog_id,
907
+			$cap,
908
+			$id
909
+		);
910
+		return apply_filters(
911
+			'FHEE__EE_Capabilities__current_user_can_for_blog__user_can',
912
+			$user_can,
913
+			$context,
914
+			$blog_id,
915
+			$cap,
916
+			$id
917
+		);
918
+	}
919
+
920
+
921
+	/**
922
+	 * This helper method just returns an array of registered EE capabilities.
923
+	 *
924
+	 * @param string|null $role If empty then the entire role/capability map is returned.
925
+	 *                          Otherwise just the capabilities for the given role are returned.
926
+	 * @return array
927
+	 * @throws EE_Error
928
+	 * @since 4.5.0
929
+	 */
930
+	public function get_ee_capabilities(?string $role = EE_Capabilities::ROLE_ADMINISTRATOR): array
931
+	{
932
+		if (! $this->initialized) {
933
+			$this->init_caps();
934
+		}
935
+		if ($role === '') {
936
+			return $this->capabilities_map;
937
+		}
938
+		return $this->capabilities_map[ $role ] ?? [];
939
+	}
940
+
941
+
942
+	/**
943
+	 * @param bool  $reset      If you need to reset Event Espresso's capabilities,
944
+	 *                          then please use the init_caps() method with the "$reset" parameter set to "true"
945
+	 * @param array $caps_map   Optional.
946
+	 *                          Can be used to send a custom map of roles and capabilities for setting them up.
947
+	 *                          Note that this should ONLY be called on activation hook or some other one-time
948
+	 *                          task otherwise the caps will be added on every request.
949
+	 * @return void
950
+	 * @throws EE_Error
951
+	 * @deprecated 4.9.42
952
+	 */
953
+	public function init_role_caps(bool $reset = false, array $caps_map = [])
954
+	{
955
+		// If this method is called directly and reset is set as 'true',
956
+		// then display a doing it wrong notice, because we want resets to go through init_caps()
957
+		// to guarantee that everything is set up correctly.
958
+		// This prevents the capabilities map getting reset incorrectly by direct calls to this method.
959
+		if ($reset) {
960
+			EE_Error::doing_it_wrong(
961
+				__METHOD__,
962
+				sprintf(
963
+					esc_html__(
964
+						'The "%1$s" parameter for the "%2$s" method is deprecated. If you need to reset Event Espresso\'s capabilities, then please use the "%3$s" method with the "%1$s" parameter set to "%4$s".',
965
+						'event_espresso'
966
+					),
967
+					'$reset',
968
+					__METHOD__ . '()',
969
+					'EE_Capabilities::init_caps()',
970
+					'true'
971
+				),
972
+				'4.9.42',
973
+				'5.0.0'
974
+			);
975
+		}
976
+		$this->addCaps($caps_map);
977
+	}
978 978
 }
979 979
 
980 980
 
@@ -990,136 +990,136 @@  discard block
 block discarded – undo
990 990
  */
991 991
 abstract class EE_Meta_Capability_Map
992 992
 {
993
-    /**
994
-     * @var EEM_Base
995
-     */
996
-    protected $_model = null;
997
-
998
-    protected string $_model_name = '';
999
-
1000
-    public string $meta_cap = '';
1001
-
1002
-    public string $published_cap = '';
1003
-
1004
-    public string $others_cap = '';
1005
-
1006
-    public string $private_cap = '';
1007
-
1008
-
1009
-    /**
1010
-     * constructor.
1011
-     * Receives the setup arguments for the map.
1012
-     *
1013
-     * @param string $meta_cap       What meta capability is this mapping.
1014
-     * @param array  $map_values     array {
1015
-     *                               //array of values that MUST match a count of 4.  It's okay to send an empty string
1016
-     *                               for capabilities that don't get mapped to.
1017
-     * @type         $map_values     [0] string A string representing the model name. Required.  String's
1018
-     *                               should always be used when Menu Maps are registered via the
1019
-     *                               plugin API as models are not allowed to be instantiated when
1020
-     *                               in maintenance mode 2 (migrations).
1021
-     * @type         $map_values     [1] string represents the capability used for published. Optional.
1022
-     * @type         $map_values     [2] string represents the capability used for "others". Optional.
1023
-     * @type         $map_values     [3] string represents the capability used for private. Optional.
1024
-     *                               }
1025
-     * @throws EE_Error
1026
-     * @since                        4.5.0
1027
-     */
1028
-    public function __construct(string $meta_cap, array $map_values)
1029
-    {
1030
-        $this->meta_cap = $meta_cap;
1031
-        // verify there are four args in the $map_values array;
1032
-        if (count($map_values) !== 4) {
1033
-            throw new EE_Error(
1034
-                sprintf(
1035
-                    esc_html__(
1036
-                        'Incoming $map_values array should have a count of four values in it.  This is what was given: %s',
1037
-                        'event_espresso'
1038
-                    ),
1039
-                    '<br>' . print_r($map_values, true)
1040
-                )
1041
-            );
1042
-        }
1043
-        // set properties
1044
-        $this->_model        = null;
1045
-        $this->_model_name   = $map_values[0];
1046
-        $this->published_cap = (string) $map_values[1];
1047
-        $this->others_cap    = (string) $map_values[2];
1048
-        $this->private_cap   = (string) $map_values[3];
1049
-    }
1050
-
1051
-
1052
-    /**
1053
-     * Makes it so this object stops filtering caps
1054
-     */
1055
-    public function remove_filters()
1056
-    {
1057
-        remove_filter('map_meta_cap', [$this, 'map_meta_caps']);
1058
-    }
1059
-
1060
-
1061
-    /**
1062
-     * This method ensures that the $model property is converted from the model name string to a proper EEM_Base class
1063
-     *
1064
-     * @return void
1065
-     * @throws EE_Error
1066
-     * @throws ReflectionException
1067
-     * @since 4.5.0
1068
-     */
1069
-    public function ensure_is_model()
1070
-    {
1071
-        // is it already instantiated?
1072
-        if ($this->_model instanceof EEM_Base) {
1073
-            return;
1074
-        }
1075
-        // ensure model name is string
1076
-        $this->_model_name = (string) $this->_model_name;
1077
-        // error proof if the name has EEM in it
1078
-        $this->_model_name = str_replace('EEM', '', $this->_model_name);
1079
-        $this->_model      = EE_Registry::instance()->load_model($this->_model_name);
1080
-        if (! $this->_model instanceof EEM_Base) {
1081
-            throw new EE_Error(
1082
-                sprintf(
1083
-                    esc_html__(
1084
-                        'This string passed in to %s to represent a EEM_Base model class was not able to be used to instantiate the class.   Please ensure that the string is a match for the EEM_Base model name (not including the EEM_ part). This was given: %s',
1085
-                        'event_espresso'
1086
-                    ),
1087
-                    get_class($this),
1088
-                    $this->_model
1089
-                )
1090
-            );
1091
-        }
1092
-    }
1093
-
1094
-
1095
-    /**
1096
-     * @param array       $caps    actual users capabilities
1097
-     * @param string|null $cap     initial capability name that is being checked (the "map" key)
1098
-     * @param int         $user_id The user id
1099
-     * @param array       $args    Adds context to the cap. Typically the object ID.
1100
-     * @return array
1101
-     * @since 4.6.x
1102
-     * @see   EE_Meta_Capability_Map::_map_meta_caps() for docs on params.
1103
-     */
1104
-    public function map_meta_caps(array $caps, ?string $cap, int $user_id, array $args): array
1105
-    {
1106
-        return $this->_map_meta_caps($caps, $cap, $user_id, $args);
1107
-    }
1108
-
1109
-
1110
-    /**
1111
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1112
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1113
-     *
1114
-     * @param array  $caps    actual users capabilities
1115
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1116
-     * @param int    $user_id The user id
1117
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1118
-     * @return array   actual users capabilities
1119
-     * @see   wp-includes/capabilities.php
1120
-     * @since 4.5.0
1121
-     */
1122
-    abstract protected function _map_meta_caps(array $caps, string $cap, int $user_id, array $args): array;
993
+	/**
994
+	 * @var EEM_Base
995
+	 */
996
+	protected $_model = null;
997
+
998
+	protected string $_model_name = '';
999
+
1000
+	public string $meta_cap = '';
1001
+
1002
+	public string $published_cap = '';
1003
+
1004
+	public string $others_cap = '';
1005
+
1006
+	public string $private_cap = '';
1007
+
1008
+
1009
+	/**
1010
+	 * constructor.
1011
+	 * Receives the setup arguments for the map.
1012
+	 *
1013
+	 * @param string $meta_cap       What meta capability is this mapping.
1014
+	 * @param array  $map_values     array {
1015
+	 *                               //array of values that MUST match a count of 4.  It's okay to send an empty string
1016
+	 *                               for capabilities that don't get mapped to.
1017
+	 * @type         $map_values     [0] string A string representing the model name. Required.  String's
1018
+	 *                               should always be used when Menu Maps are registered via the
1019
+	 *                               plugin API as models are not allowed to be instantiated when
1020
+	 *                               in maintenance mode 2 (migrations).
1021
+	 * @type         $map_values     [1] string represents the capability used for published. Optional.
1022
+	 * @type         $map_values     [2] string represents the capability used for "others". Optional.
1023
+	 * @type         $map_values     [3] string represents the capability used for private. Optional.
1024
+	 *                               }
1025
+	 * @throws EE_Error
1026
+	 * @since                        4.5.0
1027
+	 */
1028
+	public function __construct(string $meta_cap, array $map_values)
1029
+	{
1030
+		$this->meta_cap = $meta_cap;
1031
+		// verify there are four args in the $map_values array;
1032
+		if (count($map_values) !== 4) {
1033
+			throw new EE_Error(
1034
+				sprintf(
1035
+					esc_html__(
1036
+						'Incoming $map_values array should have a count of four values in it.  This is what was given: %s',
1037
+						'event_espresso'
1038
+					),
1039
+					'<br>' . print_r($map_values, true)
1040
+				)
1041
+			);
1042
+		}
1043
+		// set properties
1044
+		$this->_model        = null;
1045
+		$this->_model_name   = $map_values[0];
1046
+		$this->published_cap = (string) $map_values[1];
1047
+		$this->others_cap    = (string) $map_values[2];
1048
+		$this->private_cap   = (string) $map_values[3];
1049
+	}
1050
+
1051
+
1052
+	/**
1053
+	 * Makes it so this object stops filtering caps
1054
+	 */
1055
+	public function remove_filters()
1056
+	{
1057
+		remove_filter('map_meta_cap', [$this, 'map_meta_caps']);
1058
+	}
1059
+
1060
+
1061
+	/**
1062
+	 * This method ensures that the $model property is converted from the model name string to a proper EEM_Base class
1063
+	 *
1064
+	 * @return void
1065
+	 * @throws EE_Error
1066
+	 * @throws ReflectionException
1067
+	 * @since 4.5.0
1068
+	 */
1069
+	public function ensure_is_model()
1070
+	{
1071
+		// is it already instantiated?
1072
+		if ($this->_model instanceof EEM_Base) {
1073
+			return;
1074
+		}
1075
+		// ensure model name is string
1076
+		$this->_model_name = (string) $this->_model_name;
1077
+		// error proof if the name has EEM in it
1078
+		$this->_model_name = str_replace('EEM', '', $this->_model_name);
1079
+		$this->_model      = EE_Registry::instance()->load_model($this->_model_name);
1080
+		if (! $this->_model instanceof EEM_Base) {
1081
+			throw new EE_Error(
1082
+				sprintf(
1083
+					esc_html__(
1084
+						'This string passed in to %s to represent a EEM_Base model class was not able to be used to instantiate the class.   Please ensure that the string is a match for the EEM_Base model name (not including the EEM_ part). This was given: %s',
1085
+						'event_espresso'
1086
+					),
1087
+					get_class($this),
1088
+					$this->_model
1089
+				)
1090
+			);
1091
+		}
1092
+	}
1093
+
1094
+
1095
+	/**
1096
+	 * @param array       $caps    actual users capabilities
1097
+	 * @param string|null $cap     initial capability name that is being checked (the "map" key)
1098
+	 * @param int         $user_id The user id
1099
+	 * @param array       $args    Adds context to the cap. Typically the object ID.
1100
+	 * @return array
1101
+	 * @since 4.6.x
1102
+	 * @see   EE_Meta_Capability_Map::_map_meta_caps() for docs on params.
1103
+	 */
1104
+	public function map_meta_caps(array $caps, ?string $cap, int $user_id, array $args): array
1105
+	{
1106
+		return $this->_map_meta_caps($caps, $cap, $user_id, $args);
1107
+	}
1108
+
1109
+
1110
+	/**
1111
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1112
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1113
+	 *
1114
+	 * @param array  $caps    actual users capabilities
1115
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1116
+	 * @param int    $user_id The user id
1117
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1118
+	 * @return array   actual users capabilities
1119
+	 * @see   wp-includes/capabilities.php
1120
+	 * @since 4.5.0
1121
+	 */
1122
+	abstract protected function _map_meta_caps(array $caps, string $cap, int $user_id, array $args): array;
1123 1123
 }
1124 1124
 
1125 1125
 
@@ -1134,78 +1134,78 @@  discard block
 block discarded – undo
1134 1134
  */
1135 1135
 class EE_Meta_Capability_Map_Edit extends EE_Meta_Capability_Map
1136 1136
 {
1137
-    /**
1138
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1139
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1140
-     *
1141
-     * @param array  $caps    actual users capabilities
1142
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1143
-     * @param int    $user_id The user id
1144
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1145
-     * @return array   actual users capabilities
1146
-     * @throws EE_Error
1147
-     * @throws ReflectionException
1148
-     * @since 4.5.0
1149
-     * @see   wp-includes/capabilities.php
1150
-     */
1151
-    protected function _map_meta_caps(array $caps, string $cap, int $user_id, array $args): array
1152
-    {
1153
-        // only process if we're checking our mapped_cap
1154
-        if ($cap !== $this->meta_cap) {
1155
-            return $caps;
1156
-        }
1157
-
1158
-        // okay it is a meta cap so let's first remove that cap from the $caps array.
1159
-        if (($key = array_search($cap, $caps)) !== false) {
1160
-            unset($caps[ $key ]);
1161
-        }
1162
-
1163
-        /** @var EE_Base_Class $obj */
1164
-        $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1165
-        // if no obj then let's just do cap
1166
-        if (! $obj instanceof EE_Base_Class) {
1167
-            $caps[] = 'do_not_allow';
1168
-            return $caps;
1169
-        }
1170
-        $caps[] = $cap . 's';
1171
-        if ($obj instanceof EE_CPT_Base) {
1172
-            // if the item author is set and the user is the author...
1173
-            if ($obj->wp_user() && $user_id === $obj->wp_user()) {
1174
-                // if obj is published...
1175
-                if ($obj->status() === 'publish') {
1176
-                    $caps[] = $this->published_cap;
1177
-                }
1178
-            } else {
1179
-                // the user is trying to edit someone else's obj
1180
-                if (! empty($this->others_cap)) {
1181
-                    $caps[] = $this->others_cap;
1182
-                }
1183
-                if (! empty($this->published_cap) && $obj->status() === 'publish') {
1184
-                    $caps[] = $this->published_cap;
1185
-                } elseif (! empty($this->private_cap) && $obj->status() === 'private') {
1186
-                    $caps[] = $this->private_cap;
1187
-                }
1188
-            }
1189
-        } else {
1190
-            // not a cpt object so handled differently
1191
-            $has_cap = false;
1192
-            try {
1193
-                $has_cap = method_exists($obj, 'wp_user')
1194
-                           && $obj->wp_user()
1195
-                           && $obj->wp_user() === $user_id;
1196
-            } catch (Exception $e) {
1197
-                if (WP_DEBUG) {
1198
-                    EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1199
-                }
1200
-            }
1201
-            if (! $has_cap) {
1202
-                if (! empty($this->others_cap)) {
1203
-                    $caps[] = $this->others_cap;
1204
-                }
1205
-            }
1206
-        }
1207
-        return $caps;
1208
-    }
1137
+	/**
1138
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1139
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1140
+	 *
1141
+	 * @param array  $caps    actual users capabilities
1142
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1143
+	 * @param int    $user_id The user id
1144
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1145
+	 * @return array   actual users capabilities
1146
+	 * @throws EE_Error
1147
+	 * @throws ReflectionException
1148
+	 * @since 4.5.0
1149
+	 * @see   wp-includes/capabilities.php
1150
+	 */
1151
+	protected function _map_meta_caps(array $caps, string $cap, int $user_id, array $args): array
1152
+	{
1153
+		// only process if we're checking our mapped_cap
1154
+		if ($cap !== $this->meta_cap) {
1155
+			return $caps;
1156
+		}
1157
+
1158
+		// okay it is a meta cap so let's first remove that cap from the $caps array.
1159
+		if (($key = array_search($cap, $caps)) !== false) {
1160
+			unset($caps[ $key ]);
1161
+		}
1162
+
1163
+		/** @var EE_Base_Class $obj */
1164
+		$obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1165
+		// if no obj then let's just do cap
1166
+		if (! $obj instanceof EE_Base_Class) {
1167
+			$caps[] = 'do_not_allow';
1168
+			return $caps;
1169
+		}
1170
+		$caps[] = $cap . 's';
1171
+		if ($obj instanceof EE_CPT_Base) {
1172
+			// if the item author is set and the user is the author...
1173
+			if ($obj->wp_user() && $user_id === $obj->wp_user()) {
1174
+				// if obj is published...
1175
+				if ($obj->status() === 'publish') {
1176
+					$caps[] = $this->published_cap;
1177
+				}
1178
+			} else {
1179
+				// the user is trying to edit someone else's obj
1180
+				if (! empty($this->others_cap)) {
1181
+					$caps[] = $this->others_cap;
1182
+				}
1183
+				if (! empty($this->published_cap) && $obj->status() === 'publish') {
1184
+					$caps[] = $this->published_cap;
1185
+				} elseif (! empty($this->private_cap) && $obj->status() === 'private') {
1186
+					$caps[] = $this->private_cap;
1187
+				}
1188
+			}
1189
+		} else {
1190
+			// not a cpt object so handled differently
1191
+			$has_cap = false;
1192
+			try {
1193
+				$has_cap = method_exists($obj, 'wp_user')
1194
+						   && $obj->wp_user()
1195
+						   && $obj->wp_user() === $user_id;
1196
+			} catch (Exception $e) {
1197
+				if (WP_DEBUG) {
1198
+					EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1199
+				}
1200
+			}
1201
+			if (! $has_cap) {
1202
+				if (! empty($this->others_cap)) {
1203
+					$caps[] = $this->others_cap;
1204
+				}
1205
+			}
1206
+		}
1207
+		return $caps;
1208
+	}
1209 1209
 }
1210 1210
 
1211 1211
 
@@ -1221,24 +1221,24 @@  discard block
 block discarded – undo
1221 1221
  */
1222 1222
 class EE_Meta_Capability_Map_Delete extends EE_Meta_Capability_Map_Edit
1223 1223
 {
1224
-    /**
1225
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1226
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1227
-     *
1228
-     * @param array  $caps    actual users capabilities
1229
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1230
-     * @param int    $user_id The user id
1231
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1232
-     * @return array   actual users capabilities
1233
-     * @throws EE_Error
1234
-     * @throws ReflectionException
1235
-     * @since 4.5.0
1236
-     * @see   wp-includes/capabilities.php
1237
-     */
1238
-    protected function _map_meta_caps(array $caps, string $cap, int $user_id, array $args): array
1239
-    {
1240
-        return parent::_map_meta_caps($caps, $cap, $user_id, $args);
1241
-    }
1224
+	/**
1225
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1226
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1227
+	 *
1228
+	 * @param array  $caps    actual users capabilities
1229
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1230
+	 * @param int    $user_id The user id
1231
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1232
+	 * @return array   actual users capabilities
1233
+	 * @throws EE_Error
1234
+	 * @throws ReflectionException
1235
+	 * @since 4.5.0
1236
+	 * @see   wp-includes/capabilities.php
1237
+	 */
1238
+	protected function _map_meta_caps(array $caps, string $cap, int $user_id, array $args): array
1239
+	{
1240
+		return parent::_map_meta_caps($caps, $cap, $user_id, $args);
1241
+	}
1242 1242
 }
1243 1243
 
1244 1244
 
@@ -1253,79 +1253,79 @@  discard block
 block discarded – undo
1253 1253
  */
1254 1254
 class EE_Meta_Capability_Map_Read extends EE_Meta_Capability_Map
1255 1255
 {
1256
-    /**
1257
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1258
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1259
-     *
1260
-     * @param array  $caps    actual users capabilities
1261
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1262
-     * @param int    $user_id The user id
1263
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1264
-     * @return array   actual users capabilities
1265
-     * @throws EE_Error
1266
-     * @throws ReflectionException
1267
-     * @since 4.5.0
1268
-     * @see   wp-includes/capabilities.php
1269
-     */
1270
-    protected function _map_meta_caps(array $caps, string $cap, int $user_id, array $args): array
1271
-    {
1272
-        // only process if we're checking our mapped cap;
1273
-        if ($cap !== $this->meta_cap) {
1274
-            return $caps;
1275
-        }
1276
-
1277
-        // okay it is a meta cap so let's first remove that cap from the $caps array.
1278
-        if (($key = array_search($cap, $caps)) !== false) {
1279
-            unset($caps[ $key ]);
1280
-        }
1281
-
1282
-        $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1283
-        // if no obj then let's just do cap
1284
-        if (! $obj instanceof EE_Base_Class) {
1285
-            $caps[] = 'do_not_allow';
1286
-            return $caps;
1287
-        }
1288
-
1289
-        $caps[] = $cap . 's';
1290
-        if ($obj instanceof EE_CPT_Base) {
1291
-            $status_obj = get_post_status_object($obj->status());
1292
-            if ($status_obj->public) {
1293
-                return $caps;
1294
-            }
1295
-            // if the item author is set and the user is not the author...
1296
-            if ($obj->wp_user() && $obj->wp_user() !== $user_id) {
1297
-                if (! empty($this->others_cap)) {
1298
-                    $caps[] = $this->others_cap;
1299
-                }
1300
-            }
1301
-            // yes this means that if users created the private post, they are able to see it regardless of private cap.
1302
-            if ($status_obj->private && ! empty($this->private_cap) && $obj->wp_user() !== $user_id) {
1303
-                // the user is trying to view a private object for an object they don't own.
1304
-                $caps[] = $this->private_cap;
1305
-            }
1306
-        } else {
1307
-            // not a cpt object so handled differently
1308
-            $has_cap = false;
1309
-            try {
1310
-                $has_cap = method_exists($obj, 'wp_user')
1311
-                           && $obj->wp_user()
1312
-                           && $obj->wp_user() === $user_id;
1313
-            } catch (Exception $e) {
1314
-                if (WP_DEBUG) {
1315
-                    EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1316
-                }
1317
-            }
1318
-            if (! $has_cap) {
1319
-                if (! empty($this->private_cap)) {
1320
-                    $caps[] = $this->private_cap;
1321
-                }
1322
-                if (! empty($this->others_cap)) {
1323
-                    $caps[] = $this->others_cap;
1324
-                }
1325
-            }
1326
-        }
1327
-        return $caps;
1328
-    }
1256
+	/**
1257
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1258
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1259
+	 *
1260
+	 * @param array  $caps    actual users capabilities
1261
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1262
+	 * @param int    $user_id The user id
1263
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1264
+	 * @return array   actual users capabilities
1265
+	 * @throws EE_Error
1266
+	 * @throws ReflectionException
1267
+	 * @since 4.5.0
1268
+	 * @see   wp-includes/capabilities.php
1269
+	 */
1270
+	protected function _map_meta_caps(array $caps, string $cap, int $user_id, array $args): array
1271
+	{
1272
+		// only process if we're checking our mapped cap;
1273
+		if ($cap !== $this->meta_cap) {
1274
+			return $caps;
1275
+		}
1276
+
1277
+		// okay it is a meta cap so let's first remove that cap from the $caps array.
1278
+		if (($key = array_search($cap, $caps)) !== false) {
1279
+			unset($caps[ $key ]);
1280
+		}
1281
+
1282
+		$obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1283
+		// if no obj then let's just do cap
1284
+		if (! $obj instanceof EE_Base_Class) {
1285
+			$caps[] = 'do_not_allow';
1286
+			return $caps;
1287
+		}
1288
+
1289
+		$caps[] = $cap . 's';
1290
+		if ($obj instanceof EE_CPT_Base) {
1291
+			$status_obj = get_post_status_object($obj->status());
1292
+			if ($status_obj->public) {
1293
+				return $caps;
1294
+			}
1295
+			// if the item author is set and the user is not the author...
1296
+			if ($obj->wp_user() && $obj->wp_user() !== $user_id) {
1297
+				if (! empty($this->others_cap)) {
1298
+					$caps[] = $this->others_cap;
1299
+				}
1300
+			}
1301
+			// yes this means that if users created the private post, they are able to see it regardless of private cap.
1302
+			if ($status_obj->private && ! empty($this->private_cap) && $obj->wp_user() !== $user_id) {
1303
+				// the user is trying to view a private object for an object they don't own.
1304
+				$caps[] = $this->private_cap;
1305
+			}
1306
+		} else {
1307
+			// not a cpt object so handled differently
1308
+			$has_cap = false;
1309
+			try {
1310
+				$has_cap = method_exists($obj, 'wp_user')
1311
+						   && $obj->wp_user()
1312
+						   && $obj->wp_user() === $user_id;
1313
+			} catch (Exception $e) {
1314
+				if (WP_DEBUG) {
1315
+					EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1316
+				}
1317
+			}
1318
+			if (! $has_cap) {
1319
+				if (! empty($this->private_cap)) {
1320
+					$caps[] = $this->private_cap;
1321
+				}
1322
+				if (! empty($this->others_cap)) {
1323
+					$caps[] = $this->others_cap;
1324
+				}
1325
+			}
1326
+		}
1327
+		return $caps;
1328
+	}
1329 1329
 }
1330 1330
 
1331 1331
 
@@ -1341,53 +1341,53 @@  discard block
 block discarded – undo
1341 1341
  */
1342 1342
 class EE_Meta_Capability_Map_Messages_Cap extends EE_Meta_Capability_Map
1343 1343
 {
1344
-    /**
1345
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1346
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1347
-     *
1348
-     * @param array  $caps    actual users capabilities
1349
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1350
-     * @param int    $user_id The user id
1351
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1352
-     * @return array   actual users capabilities
1353
-     * @throws EE_Error
1354
-     * @throws ReflectionException
1355
-     * @since 4.5.0
1356
-     * @see   wp-includes/capabilities.php
1357
-     */
1358
-    protected function _map_meta_caps(array $caps, string $cap, int $user_id, array $args): array
1359
-    {
1360
-        // only process if we're checking our mapped_cap
1361
-        if ($cap !== $this->meta_cap) {
1362
-            return $caps;
1363
-        }
1364
-
1365
-        // okay it is a meta cap so let's first remove that cap from the $caps array.
1366
-        if (($key = array_search($cap, $caps)) !== false) {
1367
-            unset($caps[ $key ]);
1368
-        }
1369
-
1370
-        $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1371
-        // if no obj then let's just do cap
1372
-        if (! $obj instanceof EE_Message_Template_Group) {
1373
-            $caps[] = 'do_not_allow';
1374
-            return $caps;
1375
-        }
1376
-        $caps[]    = $cap . 's';
1377
-        $is_global = $obj->is_global();
1378
-        if ($obj->wp_user() && $obj->wp_user() === $user_id) {
1379
-            if ($is_global) {
1380
-                $caps[] = $this->private_cap;
1381
-            }
1382
-        } else {
1383
-            if ($is_global) {
1384
-                $caps[] = $this->private_cap;
1385
-            } else {
1386
-                $caps[] = $this->others_cap;
1387
-            }
1388
-        }
1389
-        return $caps;
1390
-    }
1344
+	/**
1345
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1346
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1347
+	 *
1348
+	 * @param array  $caps    actual users capabilities
1349
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1350
+	 * @param int    $user_id The user id
1351
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1352
+	 * @return array   actual users capabilities
1353
+	 * @throws EE_Error
1354
+	 * @throws ReflectionException
1355
+	 * @since 4.5.0
1356
+	 * @see   wp-includes/capabilities.php
1357
+	 */
1358
+	protected function _map_meta_caps(array $caps, string $cap, int $user_id, array $args): array
1359
+	{
1360
+		// only process if we're checking our mapped_cap
1361
+		if ($cap !== $this->meta_cap) {
1362
+			return $caps;
1363
+		}
1364
+
1365
+		// okay it is a meta cap so let's first remove that cap from the $caps array.
1366
+		if (($key = array_search($cap, $caps)) !== false) {
1367
+			unset($caps[ $key ]);
1368
+		}
1369
+
1370
+		$obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1371
+		// if no obj then let's just do cap
1372
+		if (! $obj instanceof EE_Message_Template_Group) {
1373
+			$caps[] = 'do_not_allow';
1374
+			return $caps;
1375
+		}
1376
+		$caps[]    = $cap . 's';
1377
+		$is_global = $obj->is_global();
1378
+		if ($obj->wp_user() && $obj->wp_user() === $user_id) {
1379
+			if ($is_global) {
1380
+				$caps[] = $this->private_cap;
1381
+			}
1382
+		} else {
1383
+			if ($is_global) {
1384
+				$caps[] = $this->private_cap;
1385
+			} else {
1386
+				$caps[] = $this->others_cap;
1387
+			}
1388
+		}
1389
+		return $caps;
1390
+	}
1391 1391
 }
1392 1392
 
1393 1393
 
@@ -1403,43 +1403,43 @@  discard block
 block discarded – undo
1403 1403
  */
1404 1404
 class EE_Meta_Capability_Map_Registration_Form_Cap extends EE_Meta_Capability_Map
1405 1405
 {
1406
-    /**
1407
-     * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1408
-     * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1409
-     *
1410
-     * @param array  $caps    actual users capabilities
1411
-     * @param string $cap     initial capability name that is being checked (the "map" key)
1412
-     * @param int    $user_id The user id
1413
-     * @param array  $args    Adds context to the cap. Typically the object ID.
1414
-     * @return array   actual users capabilities
1415
-     * @throws EE_Error
1416
-     * @throws EE_Error
1417
-     * @throws ReflectionException
1418
-     * @since 4.5.0
1419
-     * @see   wp-includes/capabilities.php
1420
-     */
1421
-    protected function _map_meta_caps(array $caps, string $cap, int $user_id, array $args): array
1422
-    {
1423
-        // only process if we're checking our mapped_cap
1424
-        if ($cap !== $this->meta_cap) {
1425
-            return $caps;
1426
-        }
1427
-        // okay it is a meta cap so let's first remove that cap from the $caps array.
1428
-        if (($key = array_search($cap, $caps)) !== false) {
1429
-            unset($caps[ $key ]);
1430
-        }
1431
-        $obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1432
-        // if no obj then let's just do cap
1433
-        if (! $obj instanceof EE_Base_Class) {
1434
-            $caps[] = 'do_not_allow';
1435
-            return $caps;
1436
-        }
1437
-        $caps[]    = $cap . 's';
1438
-        $is_system = $obj instanceof EE_Question_Group ? $obj->system_group() : false;
1439
-        $is_system = $obj instanceof EE_Question ? $obj->is_system_question() : $is_system;
1440
-        if ($is_system) {
1441
-            $caps[] = $this->private_cap;
1442
-        }
1443
-        return $caps;
1444
-    }
1406
+	/**
1407
+	 * This is the callback for the wp map_meta_caps() function which allows for ensuring certain caps that act as a
1408
+	 * "meta" for other caps ( i.e. ee_edit_event is a meta for ee_edit_others_events ) work as expected.
1409
+	 *
1410
+	 * @param array  $caps    actual users capabilities
1411
+	 * @param string $cap     initial capability name that is being checked (the "map" key)
1412
+	 * @param int    $user_id The user id
1413
+	 * @param array  $args    Adds context to the cap. Typically the object ID.
1414
+	 * @return array   actual users capabilities
1415
+	 * @throws EE_Error
1416
+	 * @throws EE_Error
1417
+	 * @throws ReflectionException
1418
+	 * @since 4.5.0
1419
+	 * @see   wp-includes/capabilities.php
1420
+	 */
1421
+	protected function _map_meta_caps(array $caps, string $cap, int $user_id, array $args): array
1422
+	{
1423
+		// only process if we're checking our mapped_cap
1424
+		if ($cap !== $this->meta_cap) {
1425
+			return $caps;
1426
+		}
1427
+		// okay it is a meta cap so let's first remove that cap from the $caps array.
1428
+		if (($key = array_search($cap, $caps)) !== false) {
1429
+			unset($caps[ $key ]);
1430
+		}
1431
+		$obj = ! empty($args[0]) ? $this->_model->get_one_by_ID($args[0]) : null;
1432
+		// if no obj then let's just do cap
1433
+		if (! $obj instanceof EE_Base_Class) {
1434
+			$caps[] = 'do_not_allow';
1435
+			return $caps;
1436
+		}
1437
+		$caps[]    = $cap . 's';
1438
+		$is_system = $obj instanceof EE_Question_Group ? $obj->system_group() : false;
1439
+		$is_system = $obj instanceof EE_Question ? $obj->is_system_question() : $is_system;
1440
+		if ($is_system) {
1441
+			$caps[] = $this->private_cap;
1442
+		}
1443
+		return $caps;
1444
+	}
1445 1445
 }
Please login to merge, or discard this patch.
payment_methods/Bank/EE_PMT_Bank.pm.php 1 patch
Indentation   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -9,129 +9,129 @@
 block discarded – undo
9 9
  */
10 10
 class EE_PMT_Bank extends EE_PMT_Base
11 11
 {
12
-    /**
13
-     * @param EE_Payment_Method|null $pm_instance
14
-     * @throws ReflectionException
15
-     * @throws EE_Error
16
-     */
17
-    public function __construct($pm_instance = null)
18
-    {
19
-        $this->_pretty_name = esc_html__("Bank", 'event_espresso');
20
-        parent::__construct($pm_instance);
21
-        $this->_default_button_url  = $this->file_url() . 'lib/bank-logo.png';
22
-        $this->_default_description = esc_html__(
23
-            'Make payment using an electronic funds transfer from your bank.',
24
-            'event_espresso'
25
-        );
26
-    }
12
+	/**
13
+	 * @param EE_Payment_Method|null $pm_instance
14
+	 * @throws ReflectionException
15
+	 * @throws EE_Error
16
+	 */
17
+	public function __construct($pm_instance = null)
18
+	{
19
+		$this->_pretty_name = esc_html__("Bank", 'event_espresso');
20
+		parent::__construct($pm_instance);
21
+		$this->_default_button_url  = $this->file_url() . 'lib/bank-logo.png';
22
+		$this->_default_description = esc_html__(
23
+			'Make payment using an electronic funds transfer from your bank.',
24
+			'event_espresso'
25
+		);
26
+	}
27 27
 
28 28
 
29
-    /**
30
-     * Creates the billing form for this payment method type
31
-     *
32
-     * @param EE_Transaction|null $transaction
33
-     * @return EE_Billing_Info_Form|null
34
-     * @throws EE_Error
35
-     * @throws ReflectionException
36
-     */
37
-    public function generate_new_billing_form(EE_Transaction $transaction = null)
38
-    {
39
-    return null;
40
-    }
29
+	/**
30
+	 * Creates the billing form for this payment method type
31
+	 *
32
+	 * @param EE_Transaction|null $transaction
33
+	 * @return EE_Billing_Info_Form|null
34
+	 * @throws EE_Error
35
+	 * @throws ReflectionException
36
+	 */
37
+	public function generate_new_billing_form(EE_Transaction $transaction = null)
38
+	{
39
+	return null;
40
+	}
41 41
 
42 42
 
43
-    /**
44
-     * Gets the form for all the settings related to this payment method type
45
-     *
46
-     * @return EE_Payment_Method_Form
47
-     * @throws EE_Error
48
-     * @throws ReflectionException
49
-     */
50
-    public function generate_new_settings_form()
51
-    {
52
-        return new EE_Payment_Method_Form(
53
-            [
54
-                'extra_meta_inputs' => [
55
-                    'page_title'           => new EE_Text_Input(
56
-                        [
57
-                            'html_label_text' => sprintf(
58
-                                esc_html__("Title %s", "event_espresso"),
59
-                                $this->get_help_tab_link()
60
-                            ),
61
-                            'default'         => esc_html__("Electronic Funds Transfers", 'event_espresso'),
62
-                        ]
63
-                    ),
64
-                    'payment_instructions' => new EE_Text_Area_Input(
65
-                        [
66
-                            'html_label_text'       => sprintf(
67
-                                esc_html__("Payment Instructions %s", "event_espresso"),
68
-                                $this->get_help_tab_link()
69
-                            ),
70
-                            'html_help_text'        => esc_html__(
71
-                                'Provide instructions on how registrants can send the bank draft payment. Eg, mention your account name, bank account number, bank name, bank routing code, and bank address, etc.',
72
-                                'event_espresso'
73
-                            ),
74
-                            'default'               => sprintf(
75
-                                esc_html__(
76
-                                    'Please initiate an electronic payment using the following bank information: %1$sAccount Owner: Luke Skywalker%1$sBank Account # 1234567890%1$sBank Name: Rebellion Bank%1$sRouting Number: 12345%1$sBank Address: 12345 Wookie Rd., Planet Corellian.%1$sPayment must be received within 48 hours of event date.',
77
-                                    'event_espresso'
78
-                                ),
79
-                                "\n"
80
-                            ),
81
-                            'validation_strategies' => [
82
-                                new EE_Full_HTML_Validation_Strategy(),
83
-                            ],
84
-                        ]
85
-                    ),
86
-                ],
87
-                'exclude'           => ['PMD_debug_mode'],
88
-            ]
89
-        );
90
-    }
43
+	/**
44
+	 * Gets the form for all the settings related to this payment method type
45
+	 *
46
+	 * @return EE_Payment_Method_Form
47
+	 * @throws EE_Error
48
+	 * @throws ReflectionException
49
+	 */
50
+	public function generate_new_settings_form()
51
+	{
52
+		return new EE_Payment_Method_Form(
53
+			[
54
+				'extra_meta_inputs' => [
55
+					'page_title'           => new EE_Text_Input(
56
+						[
57
+							'html_label_text' => sprintf(
58
+								esc_html__("Title %s", "event_espresso"),
59
+								$this->get_help_tab_link()
60
+							),
61
+							'default'         => esc_html__("Electronic Funds Transfers", 'event_espresso'),
62
+						]
63
+					),
64
+					'payment_instructions' => new EE_Text_Area_Input(
65
+						[
66
+							'html_label_text'       => sprintf(
67
+								esc_html__("Payment Instructions %s", "event_espresso"),
68
+								$this->get_help_tab_link()
69
+							),
70
+							'html_help_text'        => esc_html__(
71
+								'Provide instructions on how registrants can send the bank draft payment. Eg, mention your account name, bank account number, bank name, bank routing code, and bank address, etc.',
72
+								'event_espresso'
73
+							),
74
+							'default'               => sprintf(
75
+								esc_html__(
76
+									'Please initiate an electronic payment using the following bank information: %1$sAccount Owner: Luke Skywalker%1$sBank Account # 1234567890%1$sBank Name: Rebellion Bank%1$sRouting Number: 12345%1$sBank Address: 12345 Wookie Rd., Planet Corellian.%1$sPayment must be received within 48 hours of event date.',
77
+									'event_espresso'
78
+								),
79
+								"\n"
80
+							),
81
+							'validation_strategies' => [
82
+								new EE_Full_HTML_Validation_Strategy(),
83
+							],
84
+						]
85
+					),
86
+				],
87
+				'exclude'           => ['PMD_debug_mode'],
88
+			]
89
+		);
90
+	}
91 91
 
92 92
 
93
-    /**
94
-     * Adds the help tab
95
-     *
96
-     * @return array
97
-     * @see EE_PMT_Base::help_tabs_config()
98
-     */
99
-    public function help_tabs_config()
100
-    {
101
-        return [
102
-            $this->get_help_tab_name() => [
103
-                'title'    => esc_html__('Bank Draft Settings', 'event_espresso'),
104
-                'filename' => 'payment_methods_overview_bank_draft',
105
-            ],
106
-        ];
107
-    }
93
+	/**
94
+	 * Adds the help tab
95
+	 *
96
+	 * @return array
97
+	 * @see EE_PMT_Base::help_tabs_config()
98
+	 */
99
+	public function help_tabs_config()
100
+	{
101
+		return [
102
+			$this->get_help_tab_name() => [
103
+				'title'    => esc_html__('Bank Draft Settings', 'event_espresso'),
104
+				'filename' => 'payment_methods_overview_bank_draft',
105
+			],
106
+		];
107
+	}
108 108
 
109 109
 
110
-    /**
111
-     * For adding any html output ab ove the payment overview.
112
-     * Many gateways won't want ot display anything, so this function just returns an empty string.
113
-     * Other gateways may want to override this, such as offline gateways.
114
-     *
115
-     * @param EE_Payment $payment
116
-     * @return string
117
-     * @throws EE_Error
118
-     * @throws ReflectionException
119
-     */
120
-    public function payment_overview_content(EE_Payment $payment)
121
-    {
122
-        $extra_meta_for_payment_method = $this->_pm_instance->all_extra_meta_array();
123
-        $template_vars                 = array_merge(
124
-            [
125
-                'payment_method'       => $this->_pm_instance,
126
-                'payment'              => $payment,
127
-                'page_title'           => '',
128
-                'payment_instructions' => '',
129
-            ],
130
-            $extra_meta_for_payment_method
131
-        );
132
-        return EEH_Template::locate_template(
133
-            'payment_methods/Bank/templates/bank_payment_details_content.template.php',
134
-            $template_vars
135
-        );
136
-    }
110
+	/**
111
+	 * For adding any html output ab ove the payment overview.
112
+	 * Many gateways won't want ot display anything, so this function just returns an empty string.
113
+	 * Other gateways may want to override this, such as offline gateways.
114
+	 *
115
+	 * @param EE_Payment $payment
116
+	 * @return string
117
+	 * @throws EE_Error
118
+	 * @throws ReflectionException
119
+	 */
120
+	public function payment_overview_content(EE_Payment $payment)
121
+	{
122
+		$extra_meta_for_payment_method = $this->_pm_instance->all_extra_meta_array();
123
+		$template_vars                 = array_merge(
124
+			[
125
+				'payment_method'       => $this->_pm_instance,
126
+				'payment'              => $payment,
127
+				'page_title'           => '',
128
+				'payment_instructions' => '',
129
+			],
130
+			$extra_meta_for_payment_method
131
+		);
132
+		return EEH_Template::locate_template(
133
+			'payment_methods/Bank/templates/bank_payment_details_content.template.php',
134
+			$template_vars
135
+		);
136
+	}
137 137
 }
Please login to merge, or discard this patch.
payment_methods/Invoice/EE_PMT_Invoice.pm.php 1 patch
Indentation   +128 added lines, -128 removed lines patch added patch discarded remove patch
@@ -24,144 +24,144 @@
 block discarded – undo
24 24
  */
25 25
 class EE_PMT_Invoice extends EE_PMT_Base
26 26
 {
27
-    /**
28
-     * @param EE_Payment_Method|null $pm_instance
29
-     * @throws ReflectionException
30
-     * @throws EE_Error
31
-     */
32
-    public function __construct($pm_instance = null)
33
-    {
34
-        $this->_pretty_name = esc_html__("Invoice", 'event_espresso');
35
-        $this->_default_description = sprintf(
36
-            esc_html__('After clicking "Finalize Registration", you will be given instructions on how to access your invoice and complete your payment.%sPlease note that event spaces will not be reserved until payment is received in full, and any remaining tickets could be sold to others in the meantime.', 'event_espresso'),
37
-            '<br />'
38
-        );
39
-        parent::__construct($pm_instance);
40
-        $this->_default_button_url = $this->file_url() . 'lib/invoice-logo.png';
41
-    }
27
+	/**
28
+	 * @param EE_Payment_Method|null $pm_instance
29
+	 * @throws ReflectionException
30
+	 * @throws EE_Error
31
+	 */
32
+	public function __construct($pm_instance = null)
33
+	{
34
+		$this->_pretty_name = esc_html__("Invoice", 'event_espresso');
35
+		$this->_default_description = sprintf(
36
+			esc_html__('After clicking "Finalize Registration", you will be given instructions on how to access your invoice and complete your payment.%sPlease note that event spaces will not be reserved until payment is received in full, and any remaining tickets could be sold to others in the meantime.', 'event_espresso'),
37
+			'<br />'
38
+		);
39
+		parent::__construct($pm_instance);
40
+		$this->_default_button_url = $this->file_url() . 'lib/invoice-logo.png';
41
+	}
42 42
 
43 43
 
44 44
 
45
-    /**
46
-     * Creates the billing form for this payment method type
47
-     * @param EE_Transaction|null $transaction
48
-     * @return EE_Billing_Info_Form|null
49
-     * @throws EE_Error
50
-     * @throws ReflectionException
51
-     */
52
-    public function generate_new_billing_form(EE_Transaction $transaction = null)
53
-    {
54
-    return null;
55
-    }
45
+	/**
46
+	 * Creates the billing form for this payment method type
47
+	 * @param EE_Transaction|null $transaction
48
+	 * @return EE_Billing_Info_Form|null
49
+	 * @throws EE_Error
50
+	 * @throws ReflectionException
51
+	 */
52
+	public function generate_new_billing_form(EE_Transaction $transaction = null)
53
+	{
54
+	return null;
55
+	}
56 56
 
57 57
 
58 58
 
59
-    /**
60
-     * Gets the form for all the settings related to this payment method type
61
-     *
62
-     * @return EE_Payment_Method_Form
63
-     * @throws EE_Error
64
-     * @throws ReflectionException
65
-     */
66
-    public function generate_new_settings_form()
67
-    {
68
-        $pdf_payee_input_name = 'pdf_payee_name';
69
-        $confirmation_text_input_name = 'page_confirmation_text';
70
-        $form =  new EE_Payment_Method_Form(array(
59
+	/**
60
+	 * Gets the form for all the settings related to this payment method type
61
+	 *
62
+	 * @return EE_Payment_Method_Form
63
+	 * @throws EE_Error
64
+	 * @throws ReflectionException
65
+	 */
66
+	public function generate_new_settings_form()
67
+	{
68
+		$pdf_payee_input_name = 'pdf_payee_name';
69
+		$confirmation_text_input_name = 'page_confirmation_text';
70
+		$form =  new EE_Payment_Method_Form(array(
71 71
 //              'payment_method_type' => $this,
72
-                'extra_meta_inputs' => array(
73
-                    $pdf_payee_input_name => new EE_Text_Input(array(
74
-                        'html_label_text' => sprintf(esc_html__('Payee Name %s', 'event_espresso'), $this->get_help_tab_link())
75
-                    )),
76
-                    'pdf_payee_email' => new EE_Email_Input(array(
77
-                        'html_label_text' => sprintf(esc_html__('Payee Email %s', 'event_espresso'), $this->get_help_tab_link()),
78
-                    )),
79
-                    'pdf_payee_tax_number' => new EE_Text_Input(array(
80
-                        'html_label_text' => sprintf(esc_html__('Payee Tax Number %s', 'event_espresso'), $this->get_help_tab_link()),
81
-                        )),
82
-                    'pdf_payee_address' => new EE_Text_Area_Input(array(
83
-                        'html_label_text' => sprintf(esc_html__('Payee Address %s', 'event_espresso'), $this->get_help_tab_link()),
84
-                        'validation_strategies' => array( new EE_Full_HTML_Validation_Strategy() ),
85
-                    )),
86
-                    'pdf_instructions' => new EE_Text_Area_Input(array(
87
-                        'html_label_text' =>  sprintf(esc_html__("Instructions %s", "event_espresso"), $this->get_help_tab_link()),
88
-                        'default' =>  esc_html__("Please send this invoice with payment attached to the address above, or use the payment link below. Payment must be received within 48 hours of event date.", 'event_espresso'),
89
-                        'validation_strategies' => array( new EE_Full_HTML_Validation_Strategy() ),
90
-                    )),
91
-                    'pdf_logo_image' => new EE_Admin_File_Uploader_Input(array(
92
-                        'html_label_text' =>  sprintf(esc_html__("Logo Image %s", "event_espresso"), $this->get_help_tab_link()),
93
-                        'default' =>  EE_Config::instance()->organization->logo_url,
94
-                        'html_help_text' =>  esc_html__("(Logo for the top left of the invoice)", 'event_espresso'),
95
-                    )),
96
-                    $confirmation_text_input_name => new EE_Text_Area_Input(array(
97
-                        'html_label_text' =>  sprintf(esc_html__("Confirmation Text %s", "event_espresso"), $this->get_help_tab_link()),
98
-                        'default' =>  esc_html__("Payment must be received within 48 hours of event date. Details about where to send the payment are included on the invoice.", 'event_espresso'),
99
-                        'validation_strategies' => array( new EE_Full_HTML_Validation_Strategy() ),
100
-                    )),
101
-                    'page_extra_info' => new EE_Text_Area_Input(array(
102
-                        'html_label_text' =>  sprintf(esc_html__("Extra Info %s", "event_espresso"), $this->get_help_tab_link()),
103
-                        'validation_strategies' => array( new EE_Full_HTML_Validation_Strategy() ),
104
-                    )),
105
-                ),
106
-                'include' => array(
107
-                    'PMD_ID', 'PMD_name','PMD_desc','PMD_admin_name','PMD_admin_desc', 'PMD_type','PMD_slug', 'PMD_open_by_default','PMD_button_url','PMD_scope','Currency','PMD_order',
108
-                    $pdf_payee_input_name, 'pdf_payee_email', 'pdf_payee_tax_number', 'pdf_payee_address', 'pdf_instructions','pdf_logo_image',
109
-                    $confirmation_text_input_name, 'page_extra_info'),
110
-            ));
111
-        $form->add_subsections(
112
-            array( 'header1' => new EE_Form_Section_HTML_From_Template('payment_methods/Invoice/templates/invoice_settings_header_display.template.php')),
113
-            $pdf_payee_input_name
114
-        );
115
-        $form->add_subsections(
116
-            array( 'header2' => new EE_Form_Section_HTML_From_Template('payment_methods/Invoice/templates/invoice_settings_header_gateway.template.php')),
117
-            $confirmation_text_input_name
118
-        );
119
-        return $form;
120
-    }
72
+				'extra_meta_inputs' => array(
73
+					$pdf_payee_input_name => new EE_Text_Input(array(
74
+						'html_label_text' => sprintf(esc_html__('Payee Name %s', 'event_espresso'), $this->get_help_tab_link())
75
+					)),
76
+					'pdf_payee_email' => new EE_Email_Input(array(
77
+						'html_label_text' => sprintf(esc_html__('Payee Email %s', 'event_espresso'), $this->get_help_tab_link()),
78
+					)),
79
+					'pdf_payee_tax_number' => new EE_Text_Input(array(
80
+						'html_label_text' => sprintf(esc_html__('Payee Tax Number %s', 'event_espresso'), $this->get_help_tab_link()),
81
+						)),
82
+					'pdf_payee_address' => new EE_Text_Area_Input(array(
83
+						'html_label_text' => sprintf(esc_html__('Payee Address %s', 'event_espresso'), $this->get_help_tab_link()),
84
+						'validation_strategies' => array( new EE_Full_HTML_Validation_Strategy() ),
85
+					)),
86
+					'pdf_instructions' => new EE_Text_Area_Input(array(
87
+						'html_label_text' =>  sprintf(esc_html__("Instructions %s", "event_espresso"), $this->get_help_tab_link()),
88
+						'default' =>  esc_html__("Please send this invoice with payment attached to the address above, or use the payment link below. Payment must be received within 48 hours of event date.", 'event_espresso'),
89
+						'validation_strategies' => array( new EE_Full_HTML_Validation_Strategy() ),
90
+					)),
91
+					'pdf_logo_image' => new EE_Admin_File_Uploader_Input(array(
92
+						'html_label_text' =>  sprintf(esc_html__("Logo Image %s", "event_espresso"), $this->get_help_tab_link()),
93
+						'default' =>  EE_Config::instance()->organization->logo_url,
94
+						'html_help_text' =>  esc_html__("(Logo for the top left of the invoice)", 'event_espresso'),
95
+					)),
96
+					$confirmation_text_input_name => new EE_Text_Area_Input(array(
97
+						'html_label_text' =>  sprintf(esc_html__("Confirmation Text %s", "event_espresso"), $this->get_help_tab_link()),
98
+						'default' =>  esc_html__("Payment must be received within 48 hours of event date. Details about where to send the payment are included on the invoice.", 'event_espresso'),
99
+						'validation_strategies' => array( new EE_Full_HTML_Validation_Strategy() ),
100
+					)),
101
+					'page_extra_info' => new EE_Text_Area_Input(array(
102
+						'html_label_text' =>  sprintf(esc_html__("Extra Info %s", "event_espresso"), $this->get_help_tab_link()),
103
+						'validation_strategies' => array( new EE_Full_HTML_Validation_Strategy() ),
104
+					)),
105
+				),
106
+				'include' => array(
107
+					'PMD_ID', 'PMD_name','PMD_desc','PMD_admin_name','PMD_admin_desc', 'PMD_type','PMD_slug', 'PMD_open_by_default','PMD_button_url','PMD_scope','Currency','PMD_order',
108
+					$pdf_payee_input_name, 'pdf_payee_email', 'pdf_payee_tax_number', 'pdf_payee_address', 'pdf_instructions','pdf_logo_image',
109
+					$confirmation_text_input_name, 'page_extra_info'),
110
+			));
111
+		$form->add_subsections(
112
+			array( 'header1' => new EE_Form_Section_HTML_From_Template('payment_methods/Invoice/templates/invoice_settings_header_display.template.php')),
113
+			$pdf_payee_input_name
114
+		);
115
+		$form->add_subsections(
116
+			array( 'header2' => new EE_Form_Section_HTML_From_Template('payment_methods/Invoice/templates/invoice_settings_header_gateway.template.php')),
117
+			$confirmation_text_input_name
118
+		);
119
+		return $form;
120
+	}
121 121
 
122 122
 
123 123
 
124
-    /**
125
-     * Adds the help tab
126
-     *
127
-     * @return array
128
-     * @see EE_PMT_Base::help_tabs_config()
129
-     */
130
-    public function help_tabs_config()
131
-    {
132
-        return array(
133
-            $this->get_help_tab_name() => array(
134
-                'title' => esc_html__('Invoice Settings', 'event_espresso'),
135
-                'filename' => 'payment_methods_overview_invoice'
136
-            ),
137
-        );
138
-    }
124
+	/**
125
+	 * Adds the help tab
126
+	 *
127
+	 * @return array
128
+	 * @see EE_PMT_Base::help_tabs_config()
129
+	 */
130
+	public function help_tabs_config()
131
+	{
132
+		return array(
133
+			$this->get_help_tab_name() => array(
134
+				'title' => esc_html__('Invoice Settings', 'event_espresso'),
135
+				'filename' => 'payment_methods_overview_invoice'
136
+			),
137
+		);
138
+	}
139 139
 
140 140
 
141
-    /**
142
-     * For adding any html output above the payment overview.
143
-     * Many gateways won't want ot display anything, so this function just returns an empty string.
144
-     * Other gateways may want to override this, such as offline gateways.
145
-     *
146
-     * @param EE_Payment $payment
147
-     * @return string
148
-     * @throws EE_Error
149
-     * @throws ReflectionException
150
-     */
151
-    public function payment_overview_content(EE_Payment $payment)
152
-    {
153
-        return EEH_Template::locate_template(
154
-            'payment_methods/Invoice/templates/invoice_payment_details_content.template.php',
155
-            array_merge(
156
-                array(
157
-                    'payment_method'            => $this->_pm_instance,
158
-                    'payment'                       => $payment,
159
-                    'page_confirmation_text'                    => '',
160
-                    'page_extra_info'   => '',
161
-                    'invoice_url'                   => $payment->transaction()->primary_registration()->invoice_url('html')
162
-                ),
163
-                $this->_pm_instance->all_extra_meta_array()
164
-            )
165
-        );
166
-    }
141
+	/**
142
+	 * For adding any html output above the payment overview.
143
+	 * Many gateways won't want ot display anything, so this function just returns an empty string.
144
+	 * Other gateways may want to override this, such as offline gateways.
145
+	 *
146
+	 * @param EE_Payment $payment
147
+	 * @return string
148
+	 * @throws EE_Error
149
+	 * @throws ReflectionException
150
+	 */
151
+	public function payment_overview_content(EE_Payment $payment)
152
+	{
153
+		return EEH_Template::locate_template(
154
+			'payment_methods/Invoice/templates/invoice_payment_details_content.template.php',
155
+			array_merge(
156
+				array(
157
+					'payment_method'            => $this->_pm_instance,
158
+					'payment'                       => $payment,
159
+					'page_confirmation_text'                    => '',
160
+					'page_extra_info'   => '',
161
+					'invoice_url'                   => $payment->transaction()->primary_registration()->invoice_url('html')
162
+				),
163
+				$this->_pm_instance->all_extra_meta_array()
164
+			)
165
+		);
166
+	}
167 167
 }
Please login to merge, or discard this patch.
payment_methods/Admin_Only/EE_PMT_Admin_Only.pm.php 1 patch
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -13,43 +13,43 @@
 block discarded – undo
13 13
  */
14 14
 class EE_PMT_Admin_Only extends EE_PMT_Base
15 15
 {
16
-    /**
17
-     * @param EE_Payment_Method|null $pm_instance
18
-     * @throws ReflectionException
19
-     * @throws EE_Error
20
-     */
21
-    public function __construct($pm_instance = null)
22
-    {
23
-        $this->_pretty_name = esc_html__("Admin Only", 'event_espresso');
24
-        $this->_default_button_url = '';
25
-        parent::__construct($pm_instance);
26
-    }
16
+	/**
17
+	 * @param EE_Payment_Method|null $pm_instance
18
+	 * @throws ReflectionException
19
+	 * @throws EE_Error
20
+	 */
21
+	public function __construct($pm_instance = null)
22
+	{
23
+		$this->_pretty_name = esc_html__("Admin Only", 'event_espresso');
24
+		$this->_default_button_url = '';
25
+		parent::__construct($pm_instance);
26
+	}
27 27
 
28 28
 
29 29
 
30
-    /**
31
-     * Creates the billing form for this payment method type
32
-     * @param EE_Transaction|null $transaction
33
-     * @return EE_Billing_Info_Form|null
34
-     * @throws EE_Error
35
-     * @throws ReflectionException
36
-     */
37
-    public function generate_new_billing_form(EE_Transaction $transaction = null)
38
-    {
39
-    return null;
40
-    }
30
+	/**
31
+	 * Creates the billing form for this payment method type
32
+	 * @param EE_Transaction|null $transaction
33
+	 * @return EE_Billing_Info_Form|null
34
+	 * @throws EE_Error
35
+	 * @throws ReflectionException
36
+	 */
37
+	public function generate_new_billing_form(EE_Transaction $transaction = null)
38
+	{
39
+	return null;
40
+	}
41 41
 
42 42
 
43 43
 
44
-    /**
45
-     * Gets the form for all the settings related to this payment method type
46
-     *
47
-     * @return EE_Payment_Method_Form
48
-     * @throws EE_Error
49
-     * @throws ReflectionException
50
-     */
51
-    public function generate_new_settings_form()
52
-    {
53
-        return new EE_Payment_Method_Form();
54
-    }
44
+	/**
45
+	 * Gets the form for all the settings related to this payment method type
46
+	 *
47
+	 * @return EE_Payment_Method_Form
48
+	 * @throws EE_Error
49
+	 * @throws ReflectionException
50
+	 */
51
+	public function generate_new_settings_form()
52
+	{
53
+		return new EE_Payment_Method_Form();
54
+	}
55 55
 }
Please login to merge, or discard this patch.
payment_methods/Check/EE_PMT_Check.pm.php 1 patch
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -13,132 +13,132 @@
 block discarded – undo
13 13
  */
14 14
 class EE_PMT_Check extends EE_PMT_Base
15 15
 {
16
-    /**
17
-     * @param EE_Payment_Method|null $pm_instance
18
-     * @throws ReflectionException
19
-     * @throws EE_Error
20
-     */
21
-    public function __construct($pm_instance = null)
22
-    {
23
-        $this->_pretty_name = esc_html__("Check", 'event_espresso');
24
-        $this->_default_description = esc_html__('After clicking "Finalize Registration", you will be given instructions on how to complete your payment.', 'event_espresso');
25
-        parent::__construct($pm_instance);
26
-        $this->_default_button_url = $this->file_url() . 'lib/check-logo.png';
27
-    }
16
+	/**
17
+	 * @param EE_Payment_Method|null $pm_instance
18
+	 * @throws ReflectionException
19
+	 * @throws EE_Error
20
+	 */
21
+	public function __construct($pm_instance = null)
22
+	{
23
+		$this->_pretty_name = esc_html__("Check", 'event_espresso');
24
+		$this->_default_description = esc_html__('After clicking "Finalize Registration", you will be given instructions on how to complete your payment.', 'event_espresso');
25
+		parent::__construct($pm_instance);
26
+		$this->_default_button_url = $this->file_url() . 'lib/check-logo.png';
27
+	}
28 28
 
29 29
 
30 30
 
31
-    /**
32
-     * Creates the billing form for this payment method type
33
-     * @param EE_Transaction|null $transaction
34
-     * @return EE_Billing_Info_Form|null
35
-     * @throws EE_Error
36
-     * @throws ReflectionException
37
-     */
38
-    public function generate_new_billing_form(EE_Transaction $transaction = null)
39
-    {
40
-    return null;
41
-    }
31
+	/**
32
+	 * Creates the billing form for this payment method type
33
+	 * @param EE_Transaction|null $transaction
34
+	 * @return EE_Billing_Info_Form|null
35
+	 * @throws EE_Error
36
+	 * @throws ReflectionException
37
+	 */
38
+	public function generate_new_billing_form(EE_Transaction $transaction = null)
39
+	{
40
+	return null;
41
+	}
42 42
 
43 43
 
44 44
 
45
-    /**
46
-     * Overrides parent to dynamically set some defaults, but only when the form is requested
47
-     *
48
-     * @return EE_Payment_Method_Form
49
-     * @throws EE_Error
50
-     * @throws ReflectionException
51
-     */
52
-    public function generate_new_settings_form()
53
-    {
54
-        if (MaintenanceStatus::isNotFullSite()) {
55
-            $organization = EE_Registry::instance()->CFG->organization;
56
-            $organization_name = $organization->get_pretty('name');
57
-            $default_address = $organization->address_1 != '' ? $organization->get_pretty('address_1') . '<br />' : '';
58
-            $default_address .= $organization->address_2 != '' ? $organization->get_pretty('address_2') . '<br />' : '';
59
-            $default_address .= $organization->city != '' ? $organization->get_pretty('city') : '';
60
-            $default_address .= ( $organization->city != '' && $organization->STA_ID != '') ? ', ' : '<br />';
61
-            $state = EE_Registry::instance()->load_model('State')->get_one_by_ID($organization->STA_ID);
62
-            $country = EE_Registry::instance()->load_model('Country')->get_one_by_ID($organization->CNT_ISO) ;
63
-            $default_address .=  $state ? $state->name() . '<br />' : '';
64
-            $default_address .= $country ? $country->name() . '<br />' : '';
65
-            $default_address .= $organization->zip != '' ? $organization->get_pretty('zip') : '';
66
-        } else {
67
-            $default_address = 'unknown';
68
-            $organization_name = 'unknown';
69
-        }
70
-            return new EE_Payment_Method_Form(array(
71
-            'extra_meta_inputs' => array(
72
-                'check_title' => new EE_Text_Input(array(
73
-                    'html_label_text' =>  sprintf(esc_html__("Title %s", "event_espresso"), $this->get_help_tab_link()),
74
-                    'default' =>  esc_html__("Check/Money Order Payments", 'event_espresso'),
75
-                )),
76
-                'payment_instructions' => new EE_Text_Area_Input(array(
77
-                    'html_label_text' =>  sprintf(esc_html__("Instructions %s", "event_espresso"), $this->get_help_tab_link()),
78
-                    'default' => esc_html__("Please send Check/Money Order to the address below. Payment must be received within 48 hours of event date.", 'event_espresso'),
79
-                    'validation_strategies' => array( new EE_Full_HTML_Validation_Strategy() ),
80
-                )),
81
-                'payable_to' => new EE_Text_Input(array(
82
-                    'html_label_text' =>  sprintf(esc_html__("Payable To %s", "event_espresso"), $this->get_help_tab_link()),
83
-                    'default' => $organization_name
84
-                )),
85
-                'address_to_send_payment' => new EE_Text_Area_Input(array(
86
-                    'html_label_text' =>  sprintf(esc_html__("Address Payable %s", "event_espresso"), $this->get_help_tab_link()),
87
-                    'default' => $default_address,
88
-                    'validation_strategies' => array( new EE_Full_HTML_Validation_Strategy() ),
89
-                )),
90
-            ),
91
-            'exclude' => array('PMD_debug_mode')
92
-            ));
93
-    }
45
+	/**
46
+	 * Overrides parent to dynamically set some defaults, but only when the form is requested
47
+	 *
48
+	 * @return EE_Payment_Method_Form
49
+	 * @throws EE_Error
50
+	 * @throws ReflectionException
51
+	 */
52
+	public function generate_new_settings_form()
53
+	{
54
+		if (MaintenanceStatus::isNotFullSite()) {
55
+			$organization = EE_Registry::instance()->CFG->organization;
56
+			$organization_name = $organization->get_pretty('name');
57
+			$default_address = $organization->address_1 != '' ? $organization->get_pretty('address_1') . '<br />' : '';
58
+			$default_address .= $organization->address_2 != '' ? $organization->get_pretty('address_2') . '<br />' : '';
59
+			$default_address .= $organization->city != '' ? $organization->get_pretty('city') : '';
60
+			$default_address .= ( $organization->city != '' && $organization->STA_ID != '') ? ', ' : '<br />';
61
+			$state = EE_Registry::instance()->load_model('State')->get_one_by_ID($organization->STA_ID);
62
+			$country = EE_Registry::instance()->load_model('Country')->get_one_by_ID($organization->CNT_ISO) ;
63
+			$default_address .=  $state ? $state->name() . '<br />' : '';
64
+			$default_address .= $country ? $country->name() . '<br />' : '';
65
+			$default_address .= $organization->zip != '' ? $organization->get_pretty('zip') : '';
66
+		} else {
67
+			$default_address = 'unknown';
68
+			$organization_name = 'unknown';
69
+		}
70
+			return new EE_Payment_Method_Form(array(
71
+			'extra_meta_inputs' => array(
72
+				'check_title' => new EE_Text_Input(array(
73
+					'html_label_text' =>  sprintf(esc_html__("Title %s", "event_espresso"), $this->get_help_tab_link()),
74
+					'default' =>  esc_html__("Check/Money Order Payments", 'event_espresso'),
75
+				)),
76
+				'payment_instructions' => new EE_Text_Area_Input(array(
77
+					'html_label_text' =>  sprintf(esc_html__("Instructions %s", "event_espresso"), $this->get_help_tab_link()),
78
+					'default' => esc_html__("Please send Check/Money Order to the address below. Payment must be received within 48 hours of event date.", 'event_espresso'),
79
+					'validation_strategies' => array( new EE_Full_HTML_Validation_Strategy() ),
80
+				)),
81
+				'payable_to' => new EE_Text_Input(array(
82
+					'html_label_text' =>  sprintf(esc_html__("Payable To %s", "event_espresso"), $this->get_help_tab_link()),
83
+					'default' => $organization_name
84
+				)),
85
+				'address_to_send_payment' => new EE_Text_Area_Input(array(
86
+					'html_label_text' =>  sprintf(esc_html__("Address Payable %s", "event_espresso"), $this->get_help_tab_link()),
87
+					'default' => $default_address,
88
+					'validation_strategies' => array( new EE_Full_HTML_Validation_Strategy() ),
89
+				)),
90
+			),
91
+			'exclude' => array('PMD_debug_mode')
92
+			));
93
+	}
94 94
 
95 95
 
96 96
 
97
-    /**
98
-     * Adds the help tab
99
-     *
100
-     * @return array
101
-     * @see EE_PMT_Base::help_tabs_config()
102
-     */
103
-    public function help_tabs_config()
104
-    {
105
-        return array(
106
-            $this->get_help_tab_name() => array(
107
-                        'title' => esc_html__('Check Settings', 'event_espresso'),
108
-                        'filename' => 'payment_methods_overview_check'
109
-                        ),
110
-        );
111
-    }
97
+	/**
98
+	 * Adds the help tab
99
+	 *
100
+	 * @return array
101
+	 * @see EE_PMT_Base::help_tabs_config()
102
+	 */
103
+	public function help_tabs_config()
104
+	{
105
+		return array(
106
+			$this->get_help_tab_name() => array(
107
+						'title' => esc_html__('Check Settings', 'event_espresso'),
108
+						'filename' => 'payment_methods_overview_check'
109
+						),
110
+		);
111
+	}
112 112
 
113 113
 
114 114
 
115
-    /**
116
-     * For adding any html output ab ove the payment overview.
117
-     * Many gateways won't want ot display anything, so this function just returns an empty string.
118
-     * Other gateways may want to override this, such as offline gateways.
119
-     *
120
-     * @param EE_Payment $payment
121
-     * @return string
122
-     * @throws EE_Error
123
-     * @throws ReflectionException
124
-     */
125
-    public function payment_overview_content(EE_Payment $payment)
126
-    {
127
-        $extra_meta_for_payment_method = $this->_pm_instance->all_extra_meta_array();
128
-        $template_vars = array_merge(
129
-            array(
130
-                            'payment_method' => $this->_pm_instance,
131
-                            'payment' => $payment,
132
-                            'check_title' => '',
133
-                            'payment_instructions' => '',
134
-                            'payable_to' => '',
135
-                            'address_to_send_payment' => '',
136
-                            ),
137
-            $extra_meta_for_payment_method
138
-        );
139
-        return EEH_Template::locate_template(
140
-            'payment_methods/Check/templates/check_payment_details_content.template.php',
141
-            $template_vars
142
-        );
143
-    }
115
+	/**
116
+	 * For adding any html output ab ove the payment overview.
117
+	 * Many gateways won't want ot display anything, so this function just returns an empty string.
118
+	 * Other gateways may want to override this, such as offline gateways.
119
+	 *
120
+	 * @param EE_Payment $payment
121
+	 * @return string
122
+	 * @throws EE_Error
123
+	 * @throws ReflectionException
124
+	 */
125
+	public function payment_overview_content(EE_Payment $payment)
126
+	{
127
+		$extra_meta_for_payment_method = $this->_pm_instance->all_extra_meta_array();
128
+		$template_vars = array_merge(
129
+			array(
130
+							'payment_method' => $this->_pm_instance,
131
+							'payment' => $payment,
132
+							'check_title' => '',
133
+							'payment_instructions' => '',
134
+							'payable_to' => '',
135
+							'address_to_send_payment' => '',
136
+							),
137
+			$extra_meta_for_payment_method
138
+		);
139
+		return EEH_Template::locate_template(
140
+			'payment_methods/Check/templates/check_payment_details_content.template.php',
141
+			$template_vars
142
+		);
143
+	}
144 144
 }
Please login to merge, or discard this patch.