Completed
Branch fix/kses-13 (26cb73)
by
unknown
15:41 queued 13:09
created
core/db_classes/EE_Base_Class.class.php 1 patch
Indentation   +3337 added lines, -3337 removed lines patch added patch discarded remove patch
@@ -14,3353 +14,3353 @@
 block discarded – undo
14 14
 abstract class EE_Base_Class
15 15
 {
16 16
 
17
-    /**
18
-     * This is an array of the original properties and values provided during construction
19
-     * of this model object. (keys are model field names, values are their values).
20
-     * This list is important to remember so that when we are merging data from the db, we know
21
-     * which values to override and which to not override.
22
-     *
23
-     * @var array
24
-     */
25
-    protected $_props_n_values_provided_in_constructor;
26
-
27
-    /**
28
-     * Timezone
29
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
30
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
31
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
32
-     * access to it.
33
-     *
34
-     * @var string
35
-     */
36
-    protected $_timezone;
37
-
38
-    /**
39
-     * date format
40
-     * pattern or format for displaying dates
41
-     *
42
-     * @var string $_dt_frmt
43
-     */
44
-    protected $_dt_frmt;
45
-
46
-    /**
47
-     * time format
48
-     * pattern or format for displaying time
49
-     *
50
-     * @var string $_tm_frmt
51
-     */
52
-    protected $_tm_frmt;
53
-
54
-    /**
55
-     * This property is for holding a cached array of object properties indexed by property name as the key.
56
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
57
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
58
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
59
-     *
60
-     * @var array
61
-     */
62
-    protected $_cached_properties = array();
63
-
64
-    /**
65
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
66
-     * single
67
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
68
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
69
-     * all others have an array)
70
-     *
71
-     * @var array
72
-     */
73
-    protected $_model_relations = array();
74
-
75
-    /**
76
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
77
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
78
-     *
79
-     * @var array
80
-     */
81
-    protected $_fields = array();
82
-
83
-    /**
84
-     * @var boolean indicating whether or not this model object is intended to ever be saved
85
-     * For example, we might create model objects intended to only be used for the duration
86
-     * of this request and to be thrown away, and if they were accidentally saved
87
-     * it would be a bug.
88
-     */
89
-    protected $_allow_persist = true;
90
-
91
-    /**
92
-     * @var boolean indicating whether or not this model object's properties have changed since construction
93
-     */
94
-    protected $_has_changes = false;
95
-
96
-    /**
97
-     * @var EEM_Base
98
-     */
99
-    protected $_model;
100
-
101
-    /**
102
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
103
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
104
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
105
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
106
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
107
-     * array as:
108
-     * array(
109
-     *  'Registration_Count' => 24
110
-     * );
111
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
112
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
113
-     * info)
114
-     *
115
-     * @var array
116
-     */
117
-    protected $custom_selection_results = array();
118
-
119
-
120
-    /**
121
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
122
-     * play nice
123
-     *
124
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
125
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
126
-     *                                                         TXN_amount, QST_name, etc) and values are their values
127
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
128
-     *                                                         corresponding db model or not.
129
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
130
-     *                                                         be in when instantiating a EE_Base_Class object.
131
-     * @param array   $date_formats                            An array of date formats to set on construct where first
132
-     *                                                         value is the date_format and second value is the time
133
-     *                                                         format.
134
-     * @throws InvalidArgumentException
135
-     * @throws InvalidInterfaceException
136
-     * @throws InvalidDataTypeException
137
-     * @throws EE_Error
138
-     * @throws ReflectionException
139
-     */
140
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
141
-    {
142
-        $className = get_class($this);
143
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
144
-        $model = $this->get_model();
145
-        $model_fields = $model->field_settings(false);
146
-        // ensure $fieldValues is an array
147
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
148
-        // verify client code has not passed any invalid field names
149
-        foreach ($fieldValues as $field_name => $field_value) {
150
-            if (! isset($model_fields[ $field_name ])) {
151
-                throw new EE_Error(
152
-                    sprintf(
153
-                        esc_html__(
154
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
155
-                            'event_espresso'
156
-                        ),
157
-                        $field_name,
158
-                        get_class($this),
159
-                        implode(', ', array_keys($model_fields))
160
-                    )
161
-                );
162
-            }
163
-        }
164
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
165
-        if (! empty($date_formats) && is_array($date_formats)) {
166
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
167
-        } else {
168
-            // set default formats for date and time
169
-            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
170
-            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
171
-        }
172
-        // if db model is instantiating
173
-        if ($bydb) {
174
-            // client code has indicated these field values are from the database
175
-            foreach ($model_fields as $fieldName => $field) {
176
-                $this->set_from_db(
177
-                    $fieldName,
178
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
179
-                );
180
-            }
181
-        } else {
182
-            // we're constructing a brand
183
-            // new instance of the model object. Generally, this means we'll need to do more field validation
184
-            foreach ($model_fields as $fieldName => $field) {
185
-                $this->set(
186
-                    $fieldName,
187
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
188
-                    true
189
-                );
190
-            }
191
-        }
192
-        // remember what values were passed to this constructor
193
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
194
-        // remember in entity mapper
195
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
196
-            $model->add_to_entity_map($this);
197
-        }
198
-        // setup all the relations
199
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
-                $this->_model_relations[ $relation_name ] = null;
202
-            } else {
203
-                $this->_model_relations[ $relation_name ] = array();
204
-            }
205
-        }
206
-        /**
207
-         * Action done at the end of each model object construction
208
-         *
209
-         * @param EE_Base_Class $this the model object just created
210
-         */
211
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
-    }
213
-
214
-
215
-    /**
216
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
217
-     *
218
-     * @return boolean
219
-     */
220
-    public function allow_persist()
221
-    {
222
-        return $this->_allow_persist;
223
-    }
224
-
225
-
226
-    /**
227
-     * Sets whether or not this model object should be allowed to be saved to the DB.
228
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
229
-     * you got new information that somehow made you change your mind.
230
-     *
231
-     * @param boolean $allow_persist
232
-     * @return boolean
233
-     */
234
-    public function set_allow_persist($allow_persist)
235
-    {
236
-        return $this->_allow_persist = $allow_persist;
237
-    }
238
-
239
-
240
-    /**
241
-     * Gets the field's original value when this object was constructed during this request.
242
-     * This can be helpful when determining if a model object has changed or not
243
-     *
244
-     * @param string $field_name
245
-     * @return mixed|null
246
-     * @throws ReflectionException
247
-     * @throws InvalidArgumentException
248
-     * @throws InvalidInterfaceException
249
-     * @throws InvalidDataTypeException
250
-     * @throws EE_Error
251
-     */
252
-    public function get_original($field_name)
253
-    {
254
-        if (
255
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
256
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
257
-        ) {
258
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
259
-        }
260
-        return null;
261
-    }
262
-
263
-
264
-    /**
265
-     * @param EE_Base_Class $obj
266
-     * @return string
267
-     */
268
-    public function get_class($obj)
269
-    {
270
-        return get_class($obj);
271
-    }
272
-
273
-
274
-    /**
275
-     * Overrides parent because parent expects old models.
276
-     * This also doesn't do any validation, and won't work for serialized arrays
277
-     *
278
-     * @param    string $field_name
279
-     * @param    mixed  $field_value
280
-     * @param bool      $use_default
281
-     * @throws InvalidArgumentException
282
-     * @throws InvalidInterfaceException
283
-     * @throws InvalidDataTypeException
284
-     * @throws EE_Error
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     * @throws ReflectionException
288
-     */
289
-    public function set($field_name, $field_value, $use_default = false)
290
-    {
291
-        // if not using default and nothing has changed, and object has already been setup (has ID),
292
-        // then don't do anything
293
-        if (
294
-            ! $use_default
295
-            && $this->_fields[ $field_name ] === $field_value
296
-            && $this->ID()
297
-        ) {
298
-            return;
299
-        }
300
-        $model = $this->get_model();
301
-        $this->_has_changes = true;
302
-        $field_obj = $model->field_settings_for($field_name);
303
-        if ($field_obj instanceof EE_Model_Field_Base) {
304
-            // if ( method_exists( $field_obj, 'set_timezone' )) {
305
-            if ($field_obj instanceof EE_Datetime_Field) {
306
-                $field_obj->set_timezone($this->_timezone);
307
-                $field_obj->set_date_format($this->_dt_frmt);
308
-                $field_obj->set_time_format($this->_tm_frmt);
309
-            }
310
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
311
-            // should the value be null?
312
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
313
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
314
-                /**
315
-                 * To save having to refactor all the models, if a default value is used for a
316
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
317
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
318
-                 * object.
319
-                 *
320
-                 * @since 4.6.10+
321
-                 */
322
-                if (
323
-                    $field_obj instanceof EE_Datetime_Field
324
-                    && $this->_fields[ $field_name ] !== null
325
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
326
-                ) {
327
-                    empty($this->_fields[ $field_name ])
328
-                        ? $this->set($field_name, time())
329
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
330
-                }
331
-            } else {
332
-                $this->_fields[ $field_name ] = $holder_of_value;
333
-            }
334
-            // if we're not in the constructor...
335
-            // now check if what we set was a primary key
336
-            if (
17
+	/**
18
+	 * This is an array of the original properties and values provided during construction
19
+	 * of this model object. (keys are model field names, values are their values).
20
+	 * This list is important to remember so that when we are merging data from the db, we know
21
+	 * which values to override and which to not override.
22
+	 *
23
+	 * @var array
24
+	 */
25
+	protected $_props_n_values_provided_in_constructor;
26
+
27
+	/**
28
+	 * Timezone
29
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
30
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
31
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
32
+	 * access to it.
33
+	 *
34
+	 * @var string
35
+	 */
36
+	protected $_timezone;
37
+
38
+	/**
39
+	 * date format
40
+	 * pattern or format for displaying dates
41
+	 *
42
+	 * @var string $_dt_frmt
43
+	 */
44
+	protected $_dt_frmt;
45
+
46
+	/**
47
+	 * time format
48
+	 * pattern or format for displaying time
49
+	 *
50
+	 * @var string $_tm_frmt
51
+	 */
52
+	protected $_tm_frmt;
53
+
54
+	/**
55
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
56
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
57
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
58
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
59
+	 *
60
+	 * @var array
61
+	 */
62
+	protected $_cached_properties = array();
63
+
64
+	/**
65
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
66
+	 * single
67
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
68
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
69
+	 * all others have an array)
70
+	 *
71
+	 * @var array
72
+	 */
73
+	protected $_model_relations = array();
74
+
75
+	/**
76
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
77
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
78
+	 *
79
+	 * @var array
80
+	 */
81
+	protected $_fields = array();
82
+
83
+	/**
84
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
85
+	 * For example, we might create model objects intended to only be used for the duration
86
+	 * of this request and to be thrown away, and if they were accidentally saved
87
+	 * it would be a bug.
88
+	 */
89
+	protected $_allow_persist = true;
90
+
91
+	/**
92
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
93
+	 */
94
+	protected $_has_changes = false;
95
+
96
+	/**
97
+	 * @var EEM_Base
98
+	 */
99
+	protected $_model;
100
+
101
+	/**
102
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
103
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
104
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
105
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
106
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
107
+	 * array as:
108
+	 * array(
109
+	 *  'Registration_Count' => 24
110
+	 * );
111
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
112
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
113
+	 * info)
114
+	 *
115
+	 * @var array
116
+	 */
117
+	protected $custom_selection_results = array();
118
+
119
+
120
+	/**
121
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
122
+	 * play nice
123
+	 *
124
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
125
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
126
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
127
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
128
+	 *                                                         corresponding db model or not.
129
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
130
+	 *                                                         be in when instantiating a EE_Base_Class object.
131
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
132
+	 *                                                         value is the date_format and second value is the time
133
+	 *                                                         format.
134
+	 * @throws InvalidArgumentException
135
+	 * @throws InvalidInterfaceException
136
+	 * @throws InvalidDataTypeException
137
+	 * @throws EE_Error
138
+	 * @throws ReflectionException
139
+	 */
140
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
141
+	{
142
+		$className = get_class($this);
143
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
144
+		$model = $this->get_model();
145
+		$model_fields = $model->field_settings(false);
146
+		// ensure $fieldValues is an array
147
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
148
+		// verify client code has not passed any invalid field names
149
+		foreach ($fieldValues as $field_name => $field_value) {
150
+			if (! isset($model_fields[ $field_name ])) {
151
+				throw new EE_Error(
152
+					sprintf(
153
+						esc_html__(
154
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
155
+							'event_espresso'
156
+						),
157
+						$field_name,
158
+						get_class($this),
159
+						implode(', ', array_keys($model_fields))
160
+					)
161
+				);
162
+			}
163
+		}
164
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
165
+		if (! empty($date_formats) && is_array($date_formats)) {
166
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
167
+		} else {
168
+			// set default formats for date and time
169
+			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
170
+			$this->_tm_frmt = (string) get_option('time_format', 'g:i a');
171
+		}
172
+		// if db model is instantiating
173
+		if ($bydb) {
174
+			// client code has indicated these field values are from the database
175
+			foreach ($model_fields as $fieldName => $field) {
176
+				$this->set_from_db(
177
+					$fieldName,
178
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
179
+				);
180
+			}
181
+		} else {
182
+			// we're constructing a brand
183
+			// new instance of the model object. Generally, this means we'll need to do more field validation
184
+			foreach ($model_fields as $fieldName => $field) {
185
+				$this->set(
186
+					$fieldName,
187
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
188
+					true
189
+				);
190
+			}
191
+		}
192
+		// remember what values were passed to this constructor
193
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
194
+		// remember in entity mapper
195
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
196
+			$model->add_to_entity_map($this);
197
+		}
198
+		// setup all the relations
199
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
+				$this->_model_relations[ $relation_name ] = null;
202
+			} else {
203
+				$this->_model_relations[ $relation_name ] = array();
204
+			}
205
+		}
206
+		/**
207
+		 * Action done at the end of each model object construction
208
+		 *
209
+		 * @param EE_Base_Class $this the model object just created
210
+		 */
211
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
+	}
213
+
214
+
215
+	/**
216
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
217
+	 *
218
+	 * @return boolean
219
+	 */
220
+	public function allow_persist()
221
+	{
222
+		return $this->_allow_persist;
223
+	}
224
+
225
+
226
+	/**
227
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
228
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
229
+	 * you got new information that somehow made you change your mind.
230
+	 *
231
+	 * @param boolean $allow_persist
232
+	 * @return boolean
233
+	 */
234
+	public function set_allow_persist($allow_persist)
235
+	{
236
+		return $this->_allow_persist = $allow_persist;
237
+	}
238
+
239
+
240
+	/**
241
+	 * Gets the field's original value when this object was constructed during this request.
242
+	 * This can be helpful when determining if a model object has changed or not
243
+	 *
244
+	 * @param string $field_name
245
+	 * @return mixed|null
246
+	 * @throws ReflectionException
247
+	 * @throws InvalidArgumentException
248
+	 * @throws InvalidInterfaceException
249
+	 * @throws InvalidDataTypeException
250
+	 * @throws EE_Error
251
+	 */
252
+	public function get_original($field_name)
253
+	{
254
+		if (
255
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
256
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
257
+		) {
258
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
259
+		}
260
+		return null;
261
+	}
262
+
263
+
264
+	/**
265
+	 * @param EE_Base_Class $obj
266
+	 * @return string
267
+	 */
268
+	public function get_class($obj)
269
+	{
270
+		return get_class($obj);
271
+	}
272
+
273
+
274
+	/**
275
+	 * Overrides parent because parent expects old models.
276
+	 * This also doesn't do any validation, and won't work for serialized arrays
277
+	 *
278
+	 * @param    string $field_name
279
+	 * @param    mixed  $field_value
280
+	 * @param bool      $use_default
281
+	 * @throws InvalidArgumentException
282
+	 * @throws InvalidInterfaceException
283
+	 * @throws InvalidDataTypeException
284
+	 * @throws EE_Error
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 * @throws ReflectionException
288
+	 */
289
+	public function set($field_name, $field_value, $use_default = false)
290
+	{
291
+		// if not using default and nothing has changed, and object has already been setup (has ID),
292
+		// then don't do anything
293
+		if (
294
+			! $use_default
295
+			&& $this->_fields[ $field_name ] === $field_value
296
+			&& $this->ID()
297
+		) {
298
+			return;
299
+		}
300
+		$model = $this->get_model();
301
+		$this->_has_changes = true;
302
+		$field_obj = $model->field_settings_for($field_name);
303
+		if ($field_obj instanceof EE_Model_Field_Base) {
304
+			// if ( method_exists( $field_obj, 'set_timezone' )) {
305
+			if ($field_obj instanceof EE_Datetime_Field) {
306
+				$field_obj->set_timezone($this->_timezone);
307
+				$field_obj->set_date_format($this->_dt_frmt);
308
+				$field_obj->set_time_format($this->_tm_frmt);
309
+			}
310
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
311
+			// should the value be null?
312
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
313
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
314
+				/**
315
+				 * To save having to refactor all the models, if a default value is used for a
316
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
317
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
318
+				 * object.
319
+				 *
320
+				 * @since 4.6.10+
321
+				 */
322
+				if (
323
+					$field_obj instanceof EE_Datetime_Field
324
+					&& $this->_fields[ $field_name ] !== null
325
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
326
+				) {
327
+					empty($this->_fields[ $field_name ])
328
+						? $this->set($field_name, time())
329
+						: $this->set($field_name, $this->_fields[ $field_name ]);
330
+				}
331
+			} else {
332
+				$this->_fields[ $field_name ] = $holder_of_value;
333
+			}
334
+			// if we're not in the constructor...
335
+			// now check if what we set was a primary key
336
+			if (
337 337
 // note: props_n_values_provided_in_constructor is only set at the END of the constructor
338
-                $this->_props_n_values_provided_in_constructor
339
-                && $field_value
340
-                && $field_name === $model->primary_key_name()
341
-            ) {
342
-                // if so, we want all this object's fields to be filled either with
343
-                // what we've explicitly set on this model
344
-                // or what we have in the db
345
-                // echo "setting primary key!";
346
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
347
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
348
-                foreach ($fields_on_model as $field_obj) {
349
-                    if (
350
-                        ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
351
-                        && $field_obj->get_name() !== $field_name
352
-                    ) {
353
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
354
-                    }
355
-                }
356
-                // oh this model object has an ID? well make sure its in the entity mapper
357
-                $model->add_to_entity_map($this);
358
-            }
359
-            // let's unset any cache for this field_name from the $_cached_properties property.
360
-            $this->_clear_cached_property($field_name);
361
-        } else {
362
-            throw new EE_Error(
363
-                sprintf(
364
-                    esc_html__(
365
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
366
-                        'event_espresso'
367
-                    ),
368
-                    $field_name
369
-                )
370
-            );
371
-        }
372
-    }
373
-
374
-
375
-    /**
376
-     * Set custom select values for model.
377
-     *
378
-     * @param array $custom_select_values
379
-     */
380
-    public function setCustomSelectsValues(array $custom_select_values)
381
-    {
382
-        $this->custom_selection_results = $custom_select_values;
383
-    }
384
-
385
-
386
-    /**
387
-     * Returns the custom select value for the provided alias if its set.
388
-     * If not set, returns null.
389
-     *
390
-     * @param string $alias
391
-     * @return string|int|float|null
392
-     */
393
-    public function getCustomSelect($alias)
394
-    {
395
-        return isset($this->custom_selection_results[ $alias ])
396
-            ? $this->custom_selection_results[ $alias ]
397
-            : 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
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
406
-     * @param string $field_name  Must be the exact column name.
407
-     * @param mixed  $field_value The value to set.
408
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
409
-     * @throws InvalidArgumentException
410
-     * @throws InvalidInterfaceException
411
-     * @throws InvalidDataTypeException
412
-     * @throws EE_Error
413
-     * @throws ReflectionException
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
-     */
473
-    public function set_timezone($timezone = '')
474
-    {
475
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
476
-        // make sure we clear all cached properties because they won't be relevant now
477
-        $this->_clear_cached_properties();
478
-        // make sure we update field settings and the date for all EE_Datetime_Fields
479
-        $model_fields = $this->get_model()->field_settings(false);
480
-        foreach ($model_fields as $field_name => $field_obj) {
481
-            if ($field_obj instanceof EE_Datetime_Field) {
482
-                $field_obj->set_timezone($this->_timezone);
483
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
484
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
485
-                }
486
-            }
487
-        }
488
-    }
489
-
490
-
491
-    /**
492
-     * This just returns whatever is set for the current timezone.
493
-     *
494
-     * @access public
495
-     * @return string timezone string
496
-     */
497
-    public function get_timezone()
498
-    {
499
-        return $this->_timezone;
500
-    }
501
-
502
-
503
-    /**
504
-     * This sets the internal date format to what is sent in to be used as the new default for the class
505
-     * internally instead of wp set date format options
506
-     *
507
-     * @since 4.6
508
-     * @param string $format should be a format recognizable by PHP date() functions.
509
-     */
510
-    public function set_date_format($format)
511
-    {
512
-        $this->_dt_frmt = $format;
513
-        // clear cached_properties because they won't be relevant now.
514
-        $this->_clear_cached_properties();
515
-    }
516
-
517
-
518
-    /**
519
-     * This sets the internal time format string to what is sent in to be used as the new default for the
520
-     * class internally instead of wp set time format options.
521
-     *
522
-     * @since 4.6
523
-     * @param string $format should be a format recognizable by PHP date() functions.
524
-     */
525
-    public function set_time_format($format)
526
-    {
527
-        $this->_tm_frmt = $format;
528
-        // clear cached_properties because they won't be relevant now.
529
-        $this->_clear_cached_properties();
530
-    }
531
-
532
-
533
-    /**
534
-     * This returns the current internal set format for the date and time formats.
535
-     *
536
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
537
-     *                             where the first value is the date format and the second value is the time format.
538
-     * @return mixed string|array
539
-     */
540
-    public function get_format($full = true)
541
-    {
542
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
543
-    }
544
-
545
-
546
-    /**
547
-     * cache
548
-     * stores the passed model object on the current model object.
549
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
550
-     *
551
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
552
-     *                                       'Registration' associated with this model object
553
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
554
-     *                                       that could be a payment or a registration)
555
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
556
-     *                                       items which will be stored in an array on this object
557
-     * @throws ReflectionException
558
-     * @throws InvalidArgumentException
559
-     * @throws InvalidInterfaceException
560
-     * @throws InvalidDataTypeException
561
-     * @throws EE_Error
562
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
563
-     *                                       related thing, no array)
564
-     */
565
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
566
-    {
567
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
568
-        if (! $object_to_cache instanceof EE_Base_Class) {
569
-            return false;
570
-        }
571
-        // also get "how" the object is related, or throw an error
572
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
573
-            throw new EE_Error(
574
-                sprintf(
575
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
576
-                    $relationName,
577
-                    get_class($this)
578
-                )
579
-            );
580
-        }
581
-        // how many things are related ?
582
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
583
-            // if it's a "belongs to" relationship, then there's only one related model object
584
-            // eg, if this is a registration, there's only 1 attendee for it
585
-            // so for these model objects just set it to be cached
586
-            $this->_model_relations[ $relationName ] = $object_to_cache;
587
-            $return = true;
588
-        } else {
589
-            // otherwise, this is the "many" side of a one to many relationship,
590
-            // so we'll add the object to the array of related objects for that type.
591
-            // eg: if this is an event, there are many registrations for that event,
592
-            // so we cache the registrations in an array
593
-            if (! is_array($this->_model_relations[ $relationName ])) {
594
-                // if for some reason, the cached item is a model object,
595
-                // then stick that in the array, otherwise start with an empty array
596
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
597
-                                                           instanceof
598
-                                                           EE_Base_Class
599
-                    ? array($this->_model_relations[ $relationName ]) : array();
600
-            }
601
-            // first check for a cache_id which is normally empty
602
-            if (! empty($cache_id)) {
603
-                // if the cache_id exists, then it means we are purposely trying to cache this
604
-                // with a known key that can then be used to retrieve the object later on
605
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
606
-                $return = $cache_id;
607
-            } elseif ($object_to_cache->ID()) {
608
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
609
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
610
-                $return = $object_to_cache->ID();
611
-            } else {
612
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
613
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
614
-                // move the internal pointer to the end of the array
615
-                end($this->_model_relations[ $relationName ]);
616
-                // and grab the key so that we can return it
617
-                $return = key($this->_model_relations[ $relationName ]);
618
-            }
619
-        }
620
-        return $return;
621
-    }
622
-
623
-
624
-    /**
625
-     * For adding an item to the cached_properties property.
626
-     *
627
-     * @access protected
628
-     * @param string      $fieldname the property item the corresponding value is for.
629
-     * @param mixed       $value     The value we are caching.
630
-     * @param string|null $cache_type
631
-     * @return void
632
-     * @throws ReflectionException
633
-     * @throws InvalidArgumentException
634
-     * @throws InvalidInterfaceException
635
-     * @throws InvalidDataTypeException
636
-     * @throws EE_Error
637
-     */
638
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
639
-    {
640
-        // first make sure this property exists
641
-        $this->get_model()->field_settings_for($fieldname);
642
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
643
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
644
-    }
645
-
646
-
647
-    /**
648
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
649
-     * This also SETS the cache if we return the actual property!
650
-     *
651
-     * @param string $fieldname        the name of the property we're trying to retrieve
652
-     * @param bool   $pretty
653
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
654
-     *                                 (in cases where the same property may be used for different outputs
655
-     *                                 - i.e. datetime, money etc.)
656
-     *                                 It can also accept certain pre-defined "schema" strings
657
-     *                                 to define how to output the property.
658
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
659
-     * @return mixed                   whatever the value for the property is we're retrieving
660
-     * @throws ReflectionException
661
-     * @throws InvalidArgumentException
662
-     * @throws InvalidInterfaceException
663
-     * @throws InvalidDataTypeException
664
-     * @throws EE_Error
665
-     */
666
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
667
-    {
668
-        // verify the field exists
669
-        $model = $this->get_model();
670
-        $model->field_settings_for($fieldname);
671
-        $cache_type = $pretty ? 'pretty' : 'standard';
672
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
673
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
674
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
675
-        }
676
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
677
-        $this->_set_cached_property($fieldname, $value, $cache_type);
678
-        return $value;
679
-    }
680
-
681
-
682
-    /**
683
-     * If the cache didn't fetch the needed item, this fetches it.
684
-     *
685
-     * @param string $fieldname
686
-     * @param bool   $pretty
687
-     * @param string $extra_cache_ref
688
-     * @return mixed
689
-     * @throws InvalidArgumentException
690
-     * @throws InvalidInterfaceException
691
-     * @throws InvalidDataTypeException
692
-     * @throws EE_Error
693
-     * @throws ReflectionException
694
-     */
695
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
696
-    {
697
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
698
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
699
-        if ($field_obj instanceof EE_Datetime_Field) {
700
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
701
-        }
702
-        if (! isset($this->_fields[ $fieldname ])) {
703
-            $this->_fields[ $fieldname ] = null;
704
-        }
705
-        $value = $pretty
706
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
707
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
708
-        return $value;
709
-    }
710
-
711
-
712
-    /**
713
-     * set timezone, formats, and output for EE_Datetime_Field objects
714
-     *
715
-     * @param \EE_Datetime_Field $datetime_field
716
-     * @param bool               $pretty
717
-     * @param null               $date_or_time
718
-     * @return void
719
-     * @throws InvalidArgumentException
720
-     * @throws InvalidInterfaceException
721
-     * @throws InvalidDataTypeException
722
-     * @throws EE_Error
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 = array();
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 $relationName                         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
-     * @throws ReflectionException
807
-     * @throws InvalidArgumentException
808
-     * @throws InvalidInterfaceException
809
-     * @throws InvalidDataTypeException
810
-     * @throws EE_Error
811
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
812
-     *                                                     relation from all
813
-     */
814
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
815
-    {
816
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
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
-                    $relationName,
823
-                    get_class($this)
824
-                )
825
-            );
826
-        }
827
-        if ($clear_all) {
828
-            $obj_removed = true;
829
-            $this->_model_relations[ $relationName ] = null;
830
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
831
-            $obj_removed = $this->_model_relations[ $relationName ];
832
-            $this->_model_relations[ $relationName ] = 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[ $relationName ])
841
-                    && ! isset($this->_model_relations[ $relationName ][ $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[ $relationName ] 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($relationName) 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[ $relationName ][ $index_in_cache ])) {
880
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
881
-                unset($this->_model_relations[ $relationName ][ $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        $relationName       - 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
-        $relationName,
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_' . $relationName;
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($relationName);
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[ $relationName ] = $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[ $relationName ])
926
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
927
-            ) {
928
-                // then remove the current cached item
929
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
930
-                // and cache the newly saved object using it's new ID
931
-                $this->_model_relations[ $relationName ][ $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 $relationName
944
-     * @return EE_Base_Class
945
-     */
946
-    public function get_one_from_cache($relationName)
947
-    {
948
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
949
-            ? $this->_model_relations[ $relationName ]
950
-            : null;
951
-        if (is_array($cached_array_or_object)) {
952
-            return array_shift($cached_array_or_object);
953
-        }
954
-        return $cached_array_or_object;
955
-    }
956
-
957
-
958
-    /**
959
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
960
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
961
-     *
962
-     * @param string $relationName
963
-     * @throws ReflectionException
964
-     * @throws InvalidArgumentException
965
-     * @throws InvalidInterfaceException
966
-     * @throws InvalidDataTypeException
967
-     * @throws EE_Error
968
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
969
-     */
970
-    public function get_all_from_cache($relationName)
971
-    {
972
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
973
-        // if the result is not an array, but exists, make it an array
974
-        $objects = is_array($objects) ? $objects : array($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( $relationName )->get_one_by_ID( $result->ID() );
980
-        $model = EE_Registry::instance()->load_model($relationName);
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
-                        $relationName,
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 = array(), $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) ? $this->get($field) : null;
1027
-        if (empty($field) || empty($current_value)) {
1028
-            return array();
1029
-        }
1030
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1031
-    }
1032
-
1033
-
1034
-    /**
1035
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1036
-     * matching the given query conditions.
1037
-     *
1038
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1039
-     * @param int   $limit              How many objects to return.
1040
-     * @param array $query_params       Any additional conditions on the query.
1041
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1042
-     *                                  you can indicate just the columns you want returned
1043
-     * @return array|EE_Base_Class[]
1044
-     * @throws ReflectionException
1045
-     * @throws InvalidArgumentException
1046
-     * @throws InvalidInterfaceException
1047
-     * @throws InvalidDataTypeException
1048
-     * @throws EE_Error
1049
-     */
1050
-    public function previous_x(
1051
-        $field_to_order_by = null,
1052
-        $limit = 1,
1053
-        $query_params = array(),
1054
-        $columns_to_select = null
1055
-    ) {
1056
-        $model = $this->get_model();
1057
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1058
-            ? $model->get_primary_key_field()->get_name()
1059
-            : $field_to_order_by;
1060
-        $current_value = ! empty($field) ? $this->get($field) : null;
1061
-        if (empty($field) || empty($current_value)) {
1062
-            return array();
1063
-        }
1064
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1065
-    }
1066
-
1067
-
1068
-    /**
1069
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1070
-     * matching the given query conditions.
1071
-     *
1072
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1073
-     * @param array $query_params       Any additional conditions on the query.
1074
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1075
-     *                                  you can indicate just the columns you want returned
1076
-     * @return array|EE_Base_Class
1077
-     * @throws ReflectionException
1078
-     * @throws InvalidArgumentException
1079
-     * @throws InvalidInterfaceException
1080
-     * @throws InvalidDataTypeException
1081
-     * @throws EE_Error
1082
-     */
1083
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1084
-    {
1085
-        $model = $this->get_model();
1086
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1087
-            ? $model->get_primary_key_field()->get_name()
1088
-            : $field_to_order_by;
1089
-        $current_value = ! empty($field) ? $this->get($field) : null;
1090
-        if (empty($field) || empty($current_value)) {
1091
-            return array();
1092
-        }
1093
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1094
-    }
1095
-
1096
-
1097
-    /**
1098
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1099
-     * matching the given query conditions.
1100
-     *
1101
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1102
-     * @param array $query_params       Any additional conditions on the query.
1103
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1104
-     *                                  you can indicate just the column you want returned
1105
-     * @return array|EE_Base_Class
1106
-     * @throws ReflectionException
1107
-     * @throws InvalidArgumentException
1108
-     * @throws InvalidInterfaceException
1109
-     * @throws InvalidDataTypeException
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1113
-    {
1114
-        $model = $this->get_model();
1115
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1116
-            ? $model->get_primary_key_field()->get_name()
1117
-            : $field_to_order_by;
1118
-        $current_value = ! empty($field) ? $this->get($field) : null;
1119
-        if (empty($field) || empty($current_value)) {
1120
-            return array();
1121
-        }
1122
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1123
-    }
1124
-
1125
-
1126
-    /**
1127
-     * Overrides parent because parent expects old models.
1128
-     * This also doesn't do any validation, and won't work for serialized arrays
1129
-     *
1130
-     * @param string $field_name
1131
-     * @param mixed  $field_value_from_db
1132
-     * @throws ReflectionException
1133
-     * @throws InvalidArgumentException
1134
-     * @throws InvalidInterfaceException
1135
-     * @throws InvalidDataTypeException
1136
-     * @throws EE_Error
1137
-     */
1138
-    public function set_from_db($field_name, $field_value_from_db)
1139
-    {
1140
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1141
-        if ($field_obj instanceof EE_Model_Field_Base) {
1142
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
1143
-            // eg, a CPT model object could have an entry in the posts table, but no
1144
-            // entry in the meta table. Meaning that all its columns in the meta table
1145
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
1146
-            if ($field_value_from_db === null) {
1147
-                if ($field_obj->is_nullable()) {
1148
-                    // if the field allows nulls, then let it be null
1149
-                    $field_value = null;
1150
-                } else {
1151
-                    $field_value = $field_obj->get_default_value();
1152
-                }
1153
-            } else {
1154
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1155
-            }
1156
-            $this->_fields[ $field_name ] = $field_value;
1157
-            $this->_clear_cached_property($field_name);
1158
-        }
1159
-    }
1160
-
1161
-
1162
-    /**
1163
-     * verifies that the specified field is of the correct type
1164
-     *
1165
-     * @param string $field_name
1166
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1167
-     *                                (in cases where the same property may be used for different outputs
1168
-     *                                - i.e. datetime, money etc.)
1169
-     * @return mixed
1170
-     * @throws ReflectionException
1171
-     * @throws InvalidArgumentException
1172
-     * @throws InvalidInterfaceException
1173
-     * @throws InvalidDataTypeException
1174
-     * @throws EE_Error
1175
-     */
1176
-    public function get($field_name, $extra_cache_ref = null)
1177
-    {
1178
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1179
-    }
1180
-
1181
-
1182
-    /**
1183
-     * This method simply returns the RAW unprocessed value for the given property in this class
1184
-     *
1185
-     * @param  string $field_name A valid fieldname
1186
-     * @return mixed              Whatever the raw value stored on the property is.
1187
-     * @throws ReflectionException
1188
-     * @throws InvalidArgumentException
1189
-     * @throws InvalidInterfaceException
1190
-     * @throws InvalidDataTypeException
1191
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1192
-     */
1193
-    public function get_raw($field_name)
1194
-    {
1195
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1196
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1197
-            ? $this->_fields[ $field_name ]->format('U')
1198
-            : $this->_fields[ $field_name ];
1199
-    }
1200
-
1201
-
1202
-    /**
1203
-     * This is used to return the internal DateTime object used for a field that is a
1204
-     * EE_Datetime_Field.
1205
-     *
1206
-     * @param string $field_name               The field name retrieving the DateTime object.
1207
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1208
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1209
-     *                                         EE_Datetime_Field and but the field value is null, then
1210
-     *                                         just null is returned (because that indicates that likely
1211
-     *                                         this field is nullable).
1212
-     * @throws InvalidArgumentException
1213
-     * @throws InvalidDataTypeException
1214
-     * @throws InvalidInterfaceException
1215
-     * @throws ReflectionException
1216
-     */
1217
-    public function get_DateTime_object($field_name)
1218
-    {
1219
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1220
-        if (! $field_settings instanceof EE_Datetime_Field) {
1221
-            EE_Error::add_error(
1222
-                sprintf(
1223
-                    esc_html__(
1224
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1225
-                        'event_espresso'
1226
-                    ),
1227
-                    $field_name
1228
-                ),
1229
-                __FILE__,
1230
-                __FUNCTION__,
1231
-                __LINE__
1232
-            );
1233
-            return false;
1234
-        }
1235
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1236
-            ? clone $this->_fields[ $field_name ]
1237
-            : null;
1238
-    }
1239
-
1240
-
1241
-    /**
1242
-     * To be used in template to immediately echo out the value, and format it for output.
1243
-     * Eg, should call stripslashes and whatnot before echoing
1244
-     *
1245
-     * @param string $field_name      the name of the field as it appears in the DB
1246
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1247
-     *                                (in cases where the same property may be used for different outputs
1248
-     *                                - i.e. datetime, money etc.)
1249
-     * @return void
1250
-     * @throws ReflectionException
1251
-     * @throws InvalidArgumentException
1252
-     * @throws InvalidInterfaceException
1253
-     * @throws InvalidDataTypeException
1254
-     * @throws EE_Error
1255
-     */
1256
-    public function e($field_name, $extra_cache_ref = null)
1257
-    {
1258
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1259
-    }
1260
-
1261
-
1262
-    /**
1263
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1264
-     * can be easily used as the value of form input.
1265
-     *
1266
-     * @param string $field_name
1267
-     * @return void
1268
-     * @throws ReflectionException
1269
-     * @throws InvalidArgumentException
1270
-     * @throws InvalidInterfaceException
1271
-     * @throws InvalidDataTypeException
1272
-     * @throws EE_Error
1273
-     */
1274
-    public function f($field_name)
1275
-    {
1276
-        $this->e($field_name, 'form_input');
1277
-    }
1278
-
1279
-
1280
-    /**
1281
-     * Same as `f()` but just returns the value instead of echoing it
1282
-     *
1283
-     * @param string $field_name
1284
-     * @return string
1285
-     * @throws ReflectionException
1286
-     * @throws InvalidArgumentException
1287
-     * @throws InvalidInterfaceException
1288
-     * @throws InvalidDataTypeException
1289
-     * @throws EE_Error
1290
-     */
1291
-    public function get_f($field_name)
1292
-    {
1293
-        return (string) $this->get_pretty($field_name, 'form_input');
1294
-    }
1295
-
1296
-
1297
-    /**
1298
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1299
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1300
-     * to see what options are available.
1301
-     *
1302
-     * @param string $field_name
1303
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1304
-     *                                (in cases where the same property may be used for different outputs
1305
-     *                                - i.e. datetime, money etc.)
1306
-     * @return mixed
1307
-     * @throws ReflectionException
1308
-     * @throws InvalidArgumentException
1309
-     * @throws InvalidInterfaceException
1310
-     * @throws InvalidDataTypeException
1311
-     * @throws EE_Error
1312
-     */
1313
-    public function get_pretty($field_name, $extra_cache_ref = null)
1314
-    {
1315
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1316
-    }
1317
-
1318
-
1319
-    /**
1320
-     * This simply returns the datetime for the given field name
1321
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1322
-     * (and the equivalent e_date, e_time, e_datetime).
1323
-     *
1324
-     * @access   protected
1325
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1326
-     * @param string   $dt_frmt      valid datetime format used for date
1327
-     *                               (if '' then we just use the default on the field,
1328
-     *                               if NULL we use the last-used format)
1329
-     * @param string   $tm_frmt      Same as above except this is for time format
1330
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1331
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1332
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1333
-     *                               if field is not a valid dtt field, or void if echoing
1334
-     * @throws ReflectionException
1335
-     * @throws InvalidArgumentException
1336
-     * @throws InvalidInterfaceException
1337
-     * @throws InvalidDataTypeException
1338
-     * @throws EE_Error
1339
-     */
1340
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1341
-    {
1342
-        // clear cached property
1343
-        $this->_clear_cached_property($field_name);
1344
-        // reset format properties because they are used in get()
1345
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1346
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1347
-        if ($echo) {
1348
-            $this->e($field_name, $date_or_time);
1349
-            return '';
1350
-        }
1351
-        return $this->get($field_name, $date_or_time);
1352
-    }
1353
-
1354
-
1355
-    /**
1356
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1357
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1358
-     * other echoes the pretty value for dtt)
1359
-     *
1360
-     * @param  string $field_name name of model object datetime field holding the value
1361
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1362
-     * @return string            datetime value formatted
1363
-     * @throws ReflectionException
1364
-     * @throws InvalidArgumentException
1365
-     * @throws InvalidInterfaceException
1366
-     * @throws InvalidDataTypeException
1367
-     * @throws EE_Error
1368
-     */
1369
-    public function get_date($field_name, $format = '')
1370
-    {
1371
-        return $this->_get_datetime($field_name, $format, null, 'D');
1372
-    }
1373
-
1374
-
1375
-    /**
1376
-     * @param        $field_name
1377
-     * @param string $format
1378
-     * @throws ReflectionException
1379
-     * @throws InvalidArgumentException
1380
-     * @throws InvalidInterfaceException
1381
-     * @throws InvalidDataTypeException
1382
-     * @throws EE_Error
1383
-     */
1384
-    public function e_date($field_name, $format = '')
1385
-    {
1386
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1387
-    }
1388
-
1389
-
1390
-    /**
1391
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1392
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1393
-     * other echoes the pretty value for dtt)
1394
-     *
1395
-     * @param  string $field_name name of model object datetime field holding the value
1396
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1397
-     * @return string             datetime value formatted
1398
-     * @throws ReflectionException
1399
-     * @throws InvalidArgumentException
1400
-     * @throws InvalidInterfaceException
1401
-     * @throws InvalidDataTypeException
1402
-     * @throws EE_Error
1403
-     */
1404
-    public function get_time($field_name, $format = '')
1405
-    {
1406
-        return $this->_get_datetime($field_name, null, $format, 'T');
1407
-    }
1408
-
1409
-
1410
-    /**
1411
-     * @param        $field_name
1412
-     * @param string $format
1413
-     * @throws ReflectionException
1414
-     * @throws InvalidArgumentException
1415
-     * @throws InvalidInterfaceException
1416
-     * @throws InvalidDataTypeException
1417
-     * @throws EE_Error
1418
-     */
1419
-    public function e_time($field_name, $format = '')
1420
-    {
1421
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1422
-    }
1423
-
1424
-
1425
-    /**
1426
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1427
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1428
-     * other echoes the pretty value for dtt)
1429
-     *
1430
-     * @param  string $field_name name of model object datetime field holding the value
1431
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1432
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1433
-     * @return string             datetime value formatted
1434
-     * @throws ReflectionException
1435
-     * @throws InvalidArgumentException
1436
-     * @throws InvalidInterfaceException
1437
-     * @throws InvalidDataTypeException
1438
-     * @throws EE_Error
1439
-     */
1440
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1441
-    {
1442
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1443
-    }
1444
-
1445
-
1446
-    /**
1447
-     * @param string $field_name
1448
-     * @param string $dt_frmt
1449
-     * @param string $tm_frmt
1450
-     * @throws ReflectionException
1451
-     * @throws InvalidArgumentException
1452
-     * @throws InvalidInterfaceException
1453
-     * @throws InvalidDataTypeException
1454
-     * @throws EE_Error
1455
-     */
1456
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1457
-    {
1458
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1459
-    }
1460
-
1461
-
1462
-    /**
1463
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1464
-     *
1465
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1466
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1467
-     *                           on the object will be used.
1468
-     * @return string Date and time string in set locale or false if no field exists for the given
1469
-     * @throws ReflectionException
1470
-     * @throws InvalidArgumentException
1471
-     * @throws InvalidInterfaceException
1472
-     * @throws InvalidDataTypeException
1473
-     * @throws EE_Error
1474
-     *                           field name.
1475
-     */
1476
-    public function get_i18n_datetime($field_name, $format = '')
1477
-    {
1478
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1479
-        return date_i18n(
1480
-            $format,
1481
-            EEH_DTT_Helper::get_timestamp_with_offset(
1482
-                $this->get_raw($field_name),
1483
-                $this->_timezone
1484
-            )
1485
-        );
1486
-    }
1487
-
1488
-
1489
-    /**
1490
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1491
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1492
-     * thrown.
1493
-     *
1494
-     * @param  string $field_name The field name being checked
1495
-     * @throws ReflectionException
1496
-     * @throws InvalidArgumentException
1497
-     * @throws InvalidInterfaceException
1498
-     * @throws InvalidDataTypeException
1499
-     * @throws EE_Error
1500
-     * @return EE_Datetime_Field
1501
-     */
1502
-    protected function _get_dtt_field_settings($field_name)
1503
-    {
1504
-        $field = $this->get_model()->field_settings_for($field_name);
1505
-        // check if field is dtt
1506
-        if ($field instanceof EE_Datetime_Field) {
1507
-            return $field;
1508
-        }
1509
-        throw new EE_Error(
1510
-            sprintf(
1511
-                esc_html__(
1512
-                    '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',
1513
-                    'event_espresso'
1514
-                ),
1515
-                $field_name,
1516
-                self::_get_model_classname(get_class($this))
1517
-            )
1518
-        );
1519
-    }
1520
-
1521
-
1522
-
1523
-
1524
-    /**
1525
-     * NOTE ABOUT BELOW:
1526
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1527
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1528
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1529
-     * method and make sure you send the entire datetime value for setting.
1530
-     */
1531
-    /**
1532
-     * sets the time on a datetime property
1533
-     *
1534
-     * @access protected
1535
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1536
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1537
-     * @throws ReflectionException
1538
-     * @throws InvalidArgumentException
1539
-     * @throws InvalidInterfaceException
1540
-     * @throws InvalidDataTypeException
1541
-     * @throws EE_Error
1542
-     */
1543
-    protected function _set_time_for($time, $fieldname)
1544
-    {
1545
-        $this->_set_date_time('T', $time, $fieldname);
1546
-    }
1547
-
1548
-
1549
-    /**
1550
-     * sets the date on a datetime property
1551
-     *
1552
-     * @access protected
1553
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1554
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1555
-     * @throws ReflectionException
1556
-     * @throws InvalidArgumentException
1557
-     * @throws InvalidInterfaceException
1558
-     * @throws InvalidDataTypeException
1559
-     * @throws EE_Error
1560
-     */
1561
-    protected function _set_date_for($date, $fieldname)
1562
-    {
1563
-        $this->_set_date_time('D', $date, $fieldname);
1564
-    }
1565
-
1566
-
1567
-    /**
1568
-     * This takes care of setting a date or time independently on a given model object property. This method also
1569
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1570
-     *
1571
-     * @access protected
1572
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1573
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1574
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1575
-     *                                        EE_Datetime_Field property)
1576
-     * @throws ReflectionException
1577
-     * @throws InvalidArgumentException
1578
-     * @throws InvalidInterfaceException
1579
-     * @throws InvalidDataTypeException
1580
-     * @throws EE_Error
1581
-     */
1582
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1583
-    {
1584
-        $field = $this->_get_dtt_field_settings($fieldname);
1585
-        $field->set_timezone($this->_timezone);
1586
-        $field->set_date_format($this->_dt_frmt);
1587
-        $field->set_time_format($this->_tm_frmt);
1588
-        switch ($what) {
1589
-            case 'T':
1590
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1591
-                    $datetime_value,
1592
-                    $this->_fields[ $fieldname ]
1593
-                );
1594
-                $this->_has_changes = true;
1595
-                break;
1596
-            case 'D':
1597
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1598
-                    $datetime_value,
1599
-                    $this->_fields[ $fieldname ]
1600
-                );
1601
-                $this->_has_changes = true;
1602
-                break;
1603
-            case 'B':
1604
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1605
-                $this->_has_changes = true;
1606
-                break;
1607
-        }
1608
-        $this->_clear_cached_property($fieldname);
1609
-    }
1610
-
1611
-
1612
-    /**
1613
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1614
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1615
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1616
-     * that could lead to some unexpected results!
1617
-     *
1618
-     * @access public
1619
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1620
-     *                                         value being returned.
1621
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1622
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1623
-     * @param string $prepend                  You can include something to prepend on the timestamp
1624
-     * @param string $append                   You can include something to append on the timestamp
1625
-     * @throws ReflectionException
1626
-     * @throws InvalidArgumentException
1627
-     * @throws InvalidInterfaceException
1628
-     * @throws InvalidDataTypeException
1629
-     * @throws EE_Error
1630
-     * @return string timestamp
1631
-     */
1632
-    public function display_in_my_timezone(
1633
-        $field_name,
1634
-        $callback = 'get_datetime',
1635
-        $args = null,
1636
-        $prepend = '',
1637
-        $append = ''
1638
-    ) {
1639
-        $timezone = EEH_DTT_Helper::get_timezone();
1640
-        if ($timezone === $this->_timezone) {
1641
-            return '';
1642
-        }
1643
-        $original_timezone = $this->_timezone;
1644
-        $this->set_timezone($timezone);
1645
-        $fn = (array) $field_name;
1646
-        $args = array_merge($fn, (array) $args);
1647
-        if (! method_exists($this, $callback)) {
1648
-            throw new EE_Error(
1649
-                sprintf(
1650
-                    esc_html__(
1651
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1652
-                        'event_espresso'
1653
-                    ),
1654
-                    $callback
1655
-                )
1656
-            );
1657
-        }
1658
-        $args = (array) $args;
1659
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1660
-        $this->set_timezone($original_timezone);
1661
-        return $return;
1662
-    }
1663
-
1664
-
1665
-    /**
1666
-     * Deletes this model object.
1667
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1668
-     * override
1669
-     * `EE_Base_Class::_delete` NOT this class.
1670
-     *
1671
-     * @return boolean | int
1672
-     * @throws ReflectionException
1673
-     * @throws InvalidArgumentException
1674
-     * @throws InvalidInterfaceException
1675
-     * @throws InvalidDataTypeException
1676
-     * @throws EE_Error
1677
-     */
1678
-    public function delete()
1679
-    {
1680
-        /**
1681
-         * Called just before the `EE_Base_Class::_delete` method call.
1682
-         * Note:
1683
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1684
-         * should be aware that `_delete` may not always result in a permanent delete.
1685
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1686
-         * soft deletes (trash) the object and does not permanently delete it.
1687
-         *
1688
-         * @param EE_Base_Class $model_object about to be 'deleted'
1689
-         */
1690
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1691
-        $result = $this->_delete();
1692
-        /**
1693
-         * Called just after the `EE_Base_Class::_delete` method call.
1694
-         * Note:
1695
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1696
-         * should be aware that `_delete` may not always result in a permanent delete.
1697
-         * For example `EE_Soft_Base_Class::_delete`
1698
-         * soft deletes (trash) the object and does not permanently delete it.
1699
-         *
1700
-         * @param EE_Base_Class $model_object that was just 'deleted'
1701
-         * @param boolean       $result
1702
-         */
1703
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1704
-        return $result;
1705
-    }
1706
-
1707
-
1708
-    /**
1709
-     * Calls the specific delete method for the instantiated class.
1710
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1711
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1712
-     * `EE_Base_Class::delete`
1713
-     *
1714
-     * @return bool|int
1715
-     * @throws ReflectionException
1716
-     * @throws InvalidArgumentException
1717
-     * @throws InvalidInterfaceException
1718
-     * @throws InvalidDataTypeException
1719
-     * @throws EE_Error
1720
-     */
1721
-    protected function _delete()
1722
-    {
1723
-        return $this->delete_permanently();
1724
-    }
1725
-
1726
-
1727
-    /**
1728
-     * Deletes this model object permanently from db
1729
-     * (but keep in mind related models may block the delete and return an error)
1730
-     *
1731
-     * @return bool | int
1732
-     * @throws ReflectionException
1733
-     * @throws InvalidArgumentException
1734
-     * @throws InvalidInterfaceException
1735
-     * @throws InvalidDataTypeException
1736
-     * @throws EE_Error
1737
-     */
1738
-    public function delete_permanently()
1739
-    {
1740
-        /**
1741
-         * Called just before HARD deleting a model object
1742
-         *
1743
-         * @param EE_Base_Class $model_object about to be 'deleted'
1744
-         */
1745
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1746
-        $model = $this->get_model();
1747
-        $result = $model->delete_permanently_by_ID($this->ID());
1748
-        $this->refresh_cache_of_related_objects();
1749
-        /**
1750
-         * Called just after HARD deleting a model object
1751
-         *
1752
-         * @param EE_Base_Class $model_object that was just 'deleted'
1753
-         * @param boolean       $result
1754
-         */
1755
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1756
-        return $result;
1757
-    }
1758
-
1759
-
1760
-    /**
1761
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1762
-     * related model objects
1763
-     *
1764
-     * @throws ReflectionException
1765
-     * @throws InvalidArgumentException
1766
-     * @throws InvalidInterfaceException
1767
-     * @throws InvalidDataTypeException
1768
-     * @throws EE_Error
1769
-     */
1770
-    public function refresh_cache_of_related_objects()
1771
-    {
1772
-        $model = $this->get_model();
1773
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1774
-            if (! empty($this->_model_relations[ $relation_name ])) {
1775
-                $related_objects = $this->_model_relations[ $relation_name ];
1776
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1777
-                    // this relation only stores a single model object, not an array
1778
-                    // but let's make it consistent
1779
-                    $related_objects = array($related_objects);
1780
-                }
1781
-                foreach ($related_objects as $related_object) {
1782
-                    // only refresh their cache if they're in memory
1783
-                    if ($related_object instanceof EE_Base_Class) {
1784
-                        $related_object->clear_cache(
1785
-                            $model->get_this_model_name(),
1786
-                            $this
1787
-                        );
1788
-                    }
1789
-                }
1790
-            }
1791
-        }
1792
-    }
1793
-
1794
-
1795
-    /**
1796
-     *        Saves this object to the database. An array may be supplied to set some values on this
1797
-     * object just before saving.
1798
-     *
1799
-     * @access public
1800
-     * @param array $set_cols_n_values  keys are field names, values are their new values,
1801
-     *                                  if provided during the save() method
1802
-     *                                  (often client code will change the fields' values before calling save)
1803
-     * @return false|int|string         1 on a successful update;
1804
-     *                                  the ID of the new entry on insert;
1805
-     *                                  0 on failure, or if the model object isn't allowed to persist
1806
-     *                                  (as determined by EE_Base_Class::allow_persist())
1807
-     * @throws InvalidInterfaceException
1808
-     * @throws InvalidDataTypeException
1809
-     * @throws EE_Error
1810
-     * @throws InvalidArgumentException
1811
-     * @throws ReflectionException
1812
-     * @throws ReflectionException
1813
-     * @throws ReflectionException
1814
-     */
1815
-    public function save($set_cols_n_values = array())
1816
-    {
1817
-        $model = $this->get_model();
1818
-        /**
1819
-         * Filters the fields we're about to save on the model object
1820
-         *
1821
-         * @param array         $set_cols_n_values
1822
-         * @param EE_Base_Class $model_object
1823
-         */
1824
-        $set_cols_n_values = (array) apply_filters(
1825
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1826
-            $set_cols_n_values,
1827
-            $this
1828
-        );
1829
-        // set attributes as provided in $set_cols_n_values
1830
-        foreach ($set_cols_n_values as $column => $value) {
1831
-            $this->set($column, $value);
1832
-        }
1833
-        // no changes ? then don't do anything
1834
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1835
-            return 0;
1836
-        }
1837
-        /**
1838
-         * Saving a model object.
1839
-         * Before we perform a save, this action is fired.
1840
-         *
1841
-         * @param EE_Base_Class $model_object the model object about to be saved.
1842
-         */
1843
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1844
-        if (! $this->allow_persist()) {
1845
-            return 0;
1846
-        }
1847
-        // now get current attribute values
1848
-        $save_cols_n_values = $this->_fields;
1849
-        // if the object already has an ID, update it. Otherwise, insert it
1850
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1851
-        // They have been
1852
-        $old_assumption_concerning_value_preparation = $model
1853
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1854
-        $model->assume_values_already_prepared_by_model_object(true);
1855
-        // does this model have an autoincrement PK?
1856
-        if ($model->has_primary_key_field()) {
1857
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1858
-                // ok check if it's set, if so: update; if not, insert
1859
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1860
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1861
-                } else {
1862
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1863
-                    $results = $model->insert($save_cols_n_values);
1864
-                    if ($results) {
1865
-                        // if successful, set the primary key
1866
-                        // but don't use the normal SET method, because it will check if
1867
-                        // an item with the same ID exists in the mapper & db, then
1868
-                        // will find it in the db (because we just added it) and THAT object
1869
-                        // will get added to the mapper before we can add this one!
1870
-                        // but if we just avoid using the SET method, all that headache can be avoided
1871
-                        $pk_field_name = $model->primary_key_name();
1872
-                        $this->_fields[ $pk_field_name ] = $results;
1873
-                        $this->_clear_cached_property($pk_field_name);
1874
-                        $model->add_to_entity_map($this);
1875
-                        $this->_update_cached_related_model_objs_fks();
1876
-                    }
1877
-                }
1878
-            } else {// PK is NOT auto-increment
1879
-                // so check if one like it already exists in the db
1880
-                if ($model->exists_by_ID($this->ID())) {
1881
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1882
-                        throw new EE_Error(
1883
-                            sprintf(
1884
-                                esc_html__(
1885
-                                    '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',
1886
-                                    'event_espresso'
1887
-                                ),
1888
-                                get_class($this),
1889
-                                get_class($model) . '::instance()->add_to_entity_map()',
1890
-                                get_class($model) . '::instance()->get_one_by_ID()',
1891
-                                '<br />'
1892
-                            )
1893
-                        );
1894
-                    }
1895
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1896
-                } else {
1897
-                    $results = $model->insert($save_cols_n_values);
1898
-                    $this->_update_cached_related_model_objs_fks();
1899
-                }
1900
-            }
1901
-        } else {// there is NO primary key
1902
-            $already_in_db = false;
1903
-            foreach ($model->unique_indexes() as $index) {
1904
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1905
-                if ($model->exists(array($uniqueness_where_params))) {
1906
-                    $already_in_db = true;
1907
-                }
1908
-            }
1909
-            if ($already_in_db) {
1910
-                $combined_pk_fields_n_values = array_intersect_key(
1911
-                    $save_cols_n_values,
1912
-                    $model->get_combined_primary_key_fields()
1913
-                );
1914
-                $results = $model->update(
1915
-                    $save_cols_n_values,
1916
-                    $combined_pk_fields_n_values
1917
-                );
1918
-            } else {
1919
-                $results = $model->insert($save_cols_n_values);
1920
-            }
1921
-        }
1922
-        // restore the old assumption about values being prepared by the model object
1923
-        $model->assume_values_already_prepared_by_model_object(
1924
-            $old_assumption_concerning_value_preparation
1925
-        );
1926
-        /**
1927
-         * After saving the model object this action is called
1928
-         *
1929
-         * @param EE_Base_Class $model_object which was just saved
1930
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1931
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1932
-         */
1933
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1934
-        $this->_has_changes = false;
1935
-        return $results;
1936
-    }
1937
-
1938
-
1939
-    /**
1940
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1941
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1942
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1943
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1944
-     * 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
1945
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1946
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1947
-     *
1948
-     * @return void
1949
-     * @throws ReflectionException
1950
-     * @throws InvalidArgumentException
1951
-     * @throws InvalidInterfaceException
1952
-     * @throws InvalidDataTypeException
1953
-     * @throws EE_Error
1954
-     */
1955
-    protected function _update_cached_related_model_objs_fks()
1956
-    {
1957
-        $model = $this->get_model();
1958
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1959
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1960
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1961
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1962
-                        $model->get_this_model_name()
1963
-                    );
1964
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1965
-                    if ($related_model_obj_in_cache->ID()) {
1966
-                        $related_model_obj_in_cache->save();
1967
-                    }
1968
-                }
1969
-            }
1970
-        }
1971
-    }
1972
-
1973
-
1974
-    /**
1975
-     * Saves this model object and its NEW cached relations to the database.
1976
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1977
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1978
-     * because otherwise, there's a potential for infinite looping of saving
1979
-     * Saves the cached related model objects, and ensures the relation between them
1980
-     * and this object and properly setup
1981
-     *
1982
-     * @return int ID of new model object on save; 0 on failure+
1983
-     * @throws ReflectionException
1984
-     * @throws InvalidArgumentException
1985
-     * @throws InvalidInterfaceException
1986
-     * @throws InvalidDataTypeException
1987
-     * @throws EE_Error
1988
-     */
1989
-    public function save_new_cached_related_model_objs()
1990
-    {
1991
-        // make sure this has been saved
1992
-        if (! $this->ID()) {
1993
-            $id = $this->save();
1994
-        } else {
1995
-            $id = $this->ID();
1996
-        }
1997
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1998
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1999
-            if ($this->_model_relations[ $relationName ]) {
2000
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2001
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2002
-                /* @var $related_model_obj EE_Base_Class */
2003
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2004
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2005
-                    // but ONLY if it DOES NOT exist in the DB
2006
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2007
-                    // if( ! $related_model_obj->ID()){
2008
-                    $this->_add_relation_to($related_model_obj, $relationName);
2009
-                    $related_model_obj->save_new_cached_related_model_objs();
2010
-                    // }
2011
-                } else {
2012
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2013
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2014
-                        // but ONLY if it DOES NOT exist in the DB
2015
-                        // if( ! $related_model_obj->ID()){
2016
-                        $this->_add_relation_to($related_model_obj, $relationName);
2017
-                        $related_model_obj->save_new_cached_related_model_objs();
2018
-                        // }
2019
-                    }
2020
-                }
2021
-            }
2022
-        }
2023
-        return $id;
2024
-    }
2025
-
2026
-
2027
-    /**
2028
-     * for getting a model while instantiated.
2029
-     *
2030
-     * @return EEM_Base | EEM_CPT_Base
2031
-     * @throws ReflectionException
2032
-     * @throws InvalidArgumentException
2033
-     * @throws InvalidInterfaceException
2034
-     * @throws InvalidDataTypeException
2035
-     * @throws EE_Error
2036
-     */
2037
-    public function get_model()
2038
-    {
2039
-        if (! $this->_model) {
2040
-            $modelName = self::_get_model_classname(get_class($this));
2041
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2042
-        } else {
2043
-            $this->_model->set_timezone($this->_timezone);
2044
-        }
2045
-        return $this->_model;
2046
-    }
2047
-
2048
-
2049
-    /**
2050
-     * @param $props_n_values
2051
-     * @param $classname
2052
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2053
-     * @throws ReflectionException
2054
-     * @throws InvalidArgumentException
2055
-     * @throws InvalidInterfaceException
2056
-     * @throws InvalidDataTypeException
2057
-     * @throws EE_Error
2058
-     */
2059
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2060
-    {
2061
-        // TODO: will not work for Term_Relationships because they have no PK!
2062
-        $primary_id_ref = self::_get_primary_key_name($classname);
2063
-        if (
2064
-            array_key_exists($primary_id_ref, $props_n_values)
2065
-            && ! empty($props_n_values[ $primary_id_ref ])
2066
-        ) {
2067
-            $id = $props_n_values[ $primary_id_ref ];
2068
-            return self::_get_model($classname)->get_from_entity_map($id);
2069
-        }
2070
-        return false;
2071
-    }
2072
-
2073
-
2074
-    /**
2075
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2076
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2077
-     * 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
2078
-     * we return false.
2079
-     *
2080
-     * @param  array  $props_n_values   incoming array of properties and their values
2081
-     * @param  string $classname        the classname of the child class
2082
-     * @param null    $timezone
2083
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2084
-     *                                  date_format and the second value is the time format
2085
-     * @return mixed (EE_Base_Class|bool)
2086
-     * @throws InvalidArgumentException
2087
-     * @throws InvalidInterfaceException
2088
-     * @throws InvalidDataTypeException
2089
-     * @throws EE_Error
2090
-     * @throws ReflectionException
2091
-     * @throws ReflectionException
2092
-     * @throws ReflectionException
2093
-     */
2094
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2095
-    {
2096
-        $existing = null;
2097
-        $model = self::_get_model($classname, $timezone);
2098
-        if ($model->has_primary_key_field()) {
2099
-            $primary_id_ref = self::_get_primary_key_name($classname);
2100
-            if (
2101
-                array_key_exists($primary_id_ref, $props_n_values)
2102
-                && ! empty($props_n_values[ $primary_id_ref ])
2103
-            ) {
2104
-                $existing = $model->get_one_by_ID(
2105
-                    $props_n_values[ $primary_id_ref ]
2106
-                );
2107
-            }
2108
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2109
-            // no primary key on this model, but there's still a matching item in the DB
2110
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2111
-                self::_get_model($classname, $timezone)
2112
-                    ->get_index_primary_key_string($props_n_values)
2113
-            );
2114
-        }
2115
-        if ($existing) {
2116
-            // set date formats if present before setting values
2117
-            if (! empty($date_formats) && is_array($date_formats)) {
2118
-                $existing->set_date_format($date_formats[0]);
2119
-                $existing->set_time_format($date_formats[1]);
2120
-            } else {
2121
-                // set default formats for date and time
2122
-                $existing->set_date_format(get_option('date_format'));
2123
-                $existing->set_time_format(get_option('time_format'));
2124
-            }
2125
-            foreach ($props_n_values as $property => $field_value) {
2126
-                $existing->set($property, $field_value);
2127
-            }
2128
-            return $existing;
2129
-        }
2130
-        return false;
2131
-    }
2132
-
2133
-
2134
-    /**
2135
-     * Gets the EEM_*_Model for this class
2136
-     *
2137
-     * @access public now, as this is more convenient
2138
-     * @param      $classname
2139
-     * @param null $timezone
2140
-     * @throws ReflectionException
2141
-     * @throws InvalidArgumentException
2142
-     * @throws InvalidInterfaceException
2143
-     * @throws InvalidDataTypeException
2144
-     * @throws EE_Error
2145
-     * @return EEM_Base
2146
-     */
2147
-    protected static function _get_model($classname, $timezone = null)
2148
-    {
2149
-        // find model for this class
2150
-        if (! $classname) {
2151
-            throw new EE_Error(
2152
-                sprintf(
2153
-                    esc_html__(
2154
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2155
-                        'event_espresso'
2156
-                    ),
2157
-                    $classname
2158
-                )
2159
-            );
2160
-        }
2161
-        $modelName = self::_get_model_classname($classname);
2162
-        return self::_get_model_instance_with_name($modelName, $timezone);
2163
-    }
2164
-
2165
-
2166
-    /**
2167
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2168
-     *
2169
-     * @param string $model_classname
2170
-     * @param null   $timezone
2171
-     * @return EEM_Base
2172
-     * @throws ReflectionException
2173
-     * @throws InvalidArgumentException
2174
-     * @throws InvalidInterfaceException
2175
-     * @throws InvalidDataTypeException
2176
-     * @throws EE_Error
2177
-     */
2178
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2179
-    {
2180
-        $model_classname = str_replace('EEM_', '', $model_classname);
2181
-        $model = EE_Registry::instance()->load_model($model_classname);
2182
-        $model->set_timezone($timezone);
2183
-        return $model;
2184
-    }
2185
-
2186
-
2187
-    /**
2188
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2189
-     * Also works if a model class's classname is provided (eg EE_Registration).
2190
-     *
2191
-     * @param null $model_name
2192
-     * @return string like EEM_Attendee
2193
-     */
2194
-    private static function _get_model_classname($model_name = null)
2195
-    {
2196
-        if (strpos($model_name, 'EE_') === 0) {
2197
-            $model_classname = str_replace('EE_', 'EEM_', $model_name);
2198
-        } else {
2199
-            $model_classname = 'EEM_' . $model_name;
2200
-        }
2201
-        return $model_classname;
2202
-    }
2203
-
2204
-
2205
-    /**
2206
-     * returns the name of the primary key attribute
2207
-     *
2208
-     * @param null $classname
2209
-     * @throws ReflectionException
2210
-     * @throws InvalidArgumentException
2211
-     * @throws InvalidInterfaceException
2212
-     * @throws InvalidDataTypeException
2213
-     * @throws EE_Error
2214
-     * @return string
2215
-     */
2216
-    protected static function _get_primary_key_name($classname = null)
2217
-    {
2218
-        if (! $classname) {
2219
-            throw new EE_Error(
2220
-                sprintf(
2221
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2222
-                    $classname
2223
-                )
2224
-            );
2225
-        }
2226
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2227
-    }
2228
-
2229
-
2230
-    /**
2231
-     * Gets the value of the primary key.
2232
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2233
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2234
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2235
-     *
2236
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2237
-     * @throws ReflectionException
2238
-     * @throws InvalidArgumentException
2239
-     * @throws InvalidInterfaceException
2240
-     * @throws InvalidDataTypeException
2241
-     * @throws EE_Error
2242
-     */
2243
-    public function ID()
2244
-    {
2245
-        $model = $this->get_model();
2246
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2247
-        if ($model->has_primary_key_field()) {
2248
-            return $this->_fields[ $model->primary_key_name() ];
2249
-        }
2250
-        return $model->get_index_primary_key_string($this->_fields);
2251
-    }
2252
-
2253
-
2254
-    /**
2255
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2256
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2257
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2258
-     *
2259
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2260
-     * @param string $relationName                     eg 'Events','Question',etc.
2261
-     *                                                 an attendee to a group, you also want to specify which role they
2262
-     *                                                 will have in that group. So you would use this parameter to
2263
-     *                                                 specify array('role-column-name'=>'role-id')
2264
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2265
-     *                                                 allow you to further constrict the relation to being added.
2266
-     *                                                 However, keep in mind that the columns (keys) given must match a
2267
-     *                                                 column on the JOIN table and currently only the HABTM models
2268
-     *                                                 accept these additional conditions.  Also remember that if an
2269
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2270
-     *                                                 NEW row is created in the join table.
2271
-     * @param null   $cache_id
2272
-     * @throws ReflectionException
2273
-     * @throws InvalidArgumentException
2274
-     * @throws InvalidInterfaceException
2275
-     * @throws InvalidDataTypeException
2276
-     * @throws EE_Error
2277
-     * @return EE_Base_Class the object the relation was added to
2278
-     */
2279
-    public function _add_relation_to(
2280
-        $otherObjectModelObjectOrID,
2281
-        $relationName,
2282
-        $extra_join_model_fields_n_values = array(),
2283
-        $cache_id = null
2284
-    ) {
2285
-        $model = $this->get_model();
2286
-        // if this thing exists in the DB, save the relation to the DB
2287
-        if ($this->ID()) {
2288
-            $otherObject = $model->add_relationship_to(
2289
-                $this,
2290
-                $otherObjectModelObjectOrID,
2291
-                $relationName,
2292
-                $extra_join_model_fields_n_values
2293
-            );
2294
-            // clear cache so future get_many_related and get_first_related() return new results.
2295
-            $this->clear_cache($relationName, $otherObject, true);
2296
-            if ($otherObject instanceof EE_Base_Class) {
2297
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2298
-            }
2299
-        } else {
2300
-            // this thing doesn't exist in the DB,  so just cache it
2301
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2302
-                throw new EE_Error(
2303
-                    sprintf(
2304
-                        esc_html__(
2305
-                            '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',
2306
-                            'event_espresso'
2307
-                        ),
2308
-                        $otherObjectModelObjectOrID,
2309
-                        get_class($this)
2310
-                    )
2311
-                );
2312
-            }
2313
-            $otherObject = $otherObjectModelObjectOrID;
2314
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2315
-        }
2316
-        if ($otherObject instanceof EE_Base_Class) {
2317
-            // fix the reciprocal relation too
2318
-            if ($otherObject->ID()) {
2319
-                // its saved so assumed relations exist in the DB, so we can just
2320
-                // clear the cache so future queries use the updated info in the DB
2321
-                $otherObject->clear_cache(
2322
-                    $model->get_this_model_name(),
2323
-                    null,
2324
-                    true
2325
-                );
2326
-            } else {
2327
-                // it's not saved, so it caches relations like this
2328
-                $otherObject->cache($model->get_this_model_name(), $this);
2329
-            }
2330
-        }
2331
-        return $otherObject;
2332
-    }
2333
-
2334
-
2335
-    /**
2336
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2337
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2338
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2339
-     * from the cache
2340
-     *
2341
-     * @param mixed  $otherObjectModelObjectOrID
2342
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2343
-     *                to the DB yet
2344
-     * @param string $relationName
2345
-     * @param array  $where_query
2346
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2347
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2348
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2349
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2350
-     *                deleted.
2351
-     * @return EE_Base_Class the relation was removed from
2352
-     * @throws ReflectionException
2353
-     * @throws InvalidArgumentException
2354
-     * @throws InvalidInterfaceException
2355
-     * @throws InvalidDataTypeException
2356
-     * @throws EE_Error
2357
-     */
2358
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2359
-    {
2360
-        if ($this->ID()) {
2361
-            // if this exists in the DB, save the relation change to the DB too
2362
-            $otherObject = $this->get_model()->remove_relationship_to(
2363
-                $this,
2364
-                $otherObjectModelObjectOrID,
2365
-                $relationName,
2366
-                $where_query
2367
-            );
2368
-            $this->clear_cache(
2369
-                $relationName,
2370
-                $otherObject
2371
-            );
2372
-        } else {
2373
-            // this doesn't exist in the DB, just remove it from the cache
2374
-            $otherObject = $this->clear_cache(
2375
-                $relationName,
2376
-                $otherObjectModelObjectOrID
2377
-            );
2378
-        }
2379
-        if ($otherObject instanceof EE_Base_Class) {
2380
-            $otherObject->clear_cache(
2381
-                $this->get_model()->get_this_model_name(),
2382
-                $this
2383
-            );
2384
-        }
2385
-        return $otherObject;
2386
-    }
2387
-
2388
-
2389
-    /**
2390
-     * Removes ALL the related things for the $relationName.
2391
-     *
2392
-     * @param string $relationName
2393
-     * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2394
-     * @return EE_Base_Class
2395
-     * @throws ReflectionException
2396
-     * @throws InvalidArgumentException
2397
-     * @throws InvalidInterfaceException
2398
-     * @throws InvalidDataTypeException
2399
-     * @throws EE_Error
2400
-     */
2401
-    public function _remove_relations($relationName, $where_query_params = array())
2402
-    {
2403
-        if ($this->ID()) {
2404
-            // if this exists in the DB, save the relation change to the DB too
2405
-            $otherObjects = $this->get_model()->remove_relations(
2406
-                $this,
2407
-                $relationName,
2408
-                $where_query_params
2409
-            );
2410
-            $this->clear_cache(
2411
-                $relationName,
2412
-                null,
2413
-                true
2414
-            );
2415
-        } else {
2416
-            // this doesn't exist in the DB, just remove it from the cache
2417
-            $otherObjects = $this->clear_cache(
2418
-                $relationName,
2419
-                null,
2420
-                true
2421
-            );
2422
-        }
2423
-        if (is_array($otherObjects)) {
2424
-            foreach ($otherObjects as $otherObject) {
2425
-                $otherObject->clear_cache(
2426
-                    $this->get_model()->get_this_model_name(),
2427
-                    $this
2428
-                );
2429
-            }
2430
-        }
2431
-        return $otherObjects;
2432
-    }
2433
-
2434
-
2435
-    /**
2436
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2437
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2438
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2439
-     * because we want to get even deleted items etc.
2440
-     *
2441
-     * @param string $relationName key in the model's _model_relations array
2442
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2443
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2444
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2445
-     *                             results if you want IDs
2446
-     * @throws ReflectionException
2447
-     * @throws InvalidArgumentException
2448
-     * @throws InvalidInterfaceException
2449
-     * @throws InvalidDataTypeException
2450
-     * @throws EE_Error
2451
-     */
2452
-    public function get_many_related($relationName, $query_params = array())
2453
-    {
2454
-        if ($this->ID()) {
2455
-            // this exists in the DB, so get the related things from either the cache or the DB
2456
-            // if there are query parameters, forget about caching the related model objects.
2457
-            if ($query_params) {
2458
-                $related_model_objects = $this->get_model()->get_all_related(
2459
-                    $this,
2460
-                    $relationName,
2461
-                    $query_params
2462
-                );
2463
-            } else {
2464
-                // did we already cache the result of this query?
2465
-                $cached_results = $this->get_all_from_cache($relationName);
2466
-                if (! $cached_results) {
2467
-                    $related_model_objects = $this->get_model()->get_all_related(
2468
-                        $this,
2469
-                        $relationName,
2470
-                        $query_params
2471
-                    );
2472
-                    // if no query parameters were passed, then we got all the related model objects
2473
-                    // for that relation. We can cache them then.
2474
-                    foreach ($related_model_objects as $related_model_object) {
2475
-                        $this->cache($relationName, $related_model_object);
2476
-                    }
2477
-                } else {
2478
-                    $related_model_objects = $cached_results;
2479
-                }
2480
-            }
2481
-        } else {
2482
-            // this doesn't exist in the DB, so just get the related things from the cache
2483
-            $related_model_objects = $this->get_all_from_cache($relationName);
2484
-        }
2485
-        return $related_model_objects;
2486
-    }
2487
-
2488
-
2489
-    /**
2490
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2491
-     * unless otherwise specified in the $query_params
2492
-     *
2493
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2494
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2495
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2496
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2497
-     *                               that by the setting $distinct to TRUE;
2498
-     * @return int
2499
-     * @throws ReflectionException
2500
-     * @throws InvalidArgumentException
2501
-     * @throws InvalidInterfaceException
2502
-     * @throws InvalidDataTypeException
2503
-     * @throws EE_Error
2504
-     */
2505
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2506
-    {
2507
-        return $this->get_model()->count_related(
2508
-            $this,
2509
-            $relation_name,
2510
-            $query_params,
2511
-            $field_to_count,
2512
-            $distinct
2513
-        );
2514
-    }
2515
-
2516
-
2517
-    /**
2518
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2519
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2520
-     *
2521
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2522
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2523
-     * @param string $field_to_sum  name of field to count by.
2524
-     *                              By default, uses primary key
2525
-     *                              (which doesn't make much sense, so you should probably change it)
2526
-     * @return int
2527
-     * @throws ReflectionException
2528
-     * @throws InvalidArgumentException
2529
-     * @throws InvalidInterfaceException
2530
-     * @throws InvalidDataTypeException
2531
-     * @throws EE_Error
2532
-     */
2533
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2534
-    {
2535
-        return $this->get_model()->sum_related(
2536
-            $this,
2537
-            $relation_name,
2538
-            $query_params,
2539
-            $field_to_sum
2540
-        );
2541
-    }
2542
-
2543
-
2544
-    /**
2545
-     * Gets the first (ie, one) related model object of the specified type.
2546
-     *
2547
-     * @param string $relationName key in the model's _model_relations array
2548
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2549
-     * @return EE_Base_Class (not an array, a single object)
2550
-     * @throws ReflectionException
2551
-     * @throws InvalidArgumentException
2552
-     * @throws InvalidInterfaceException
2553
-     * @throws InvalidDataTypeException
2554
-     * @throws EE_Error
2555
-     */
2556
-    public function get_first_related($relationName, $query_params = array())
2557
-    {
2558
-        $model = $this->get_model();
2559
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2560
-            // if they've provided some query parameters, don't bother trying to cache the result
2561
-            // also make sure we're not caching the result of get_first_related
2562
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2563
-            if (
2564
-                $query_params
2565
-                || ! $model->related_settings_for($relationName)
2566
-                     instanceof
2567
-                     EE_Belongs_To_Relation
2568
-            ) {
2569
-                $related_model_object = $model->get_first_related(
2570
-                    $this,
2571
-                    $relationName,
2572
-                    $query_params
2573
-                );
2574
-            } else {
2575
-                // first, check if we've already cached the result of this query
2576
-                $cached_result = $this->get_one_from_cache($relationName);
2577
-                if (! $cached_result) {
2578
-                    $related_model_object = $model->get_first_related(
2579
-                        $this,
2580
-                        $relationName,
2581
-                        $query_params
2582
-                    );
2583
-                    $this->cache($relationName, $related_model_object);
2584
-                } else {
2585
-                    $related_model_object = $cached_result;
2586
-                }
2587
-            }
2588
-        } else {
2589
-            $related_model_object = null;
2590
-            // this doesn't exist in the Db,
2591
-            // but maybe the relation is of type belongs to, and so the related thing might
2592
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2593
-                $related_model_object = $model->get_first_related(
2594
-                    $this,
2595
-                    $relationName,
2596
-                    $query_params
2597
-                );
2598
-            }
2599
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2600
-            // just get what's cached on this object
2601
-            if (! $related_model_object) {
2602
-                $related_model_object = $this->get_one_from_cache($relationName);
2603
-            }
2604
-        }
2605
-        return $related_model_object;
2606
-    }
2607
-
2608
-
2609
-    /**
2610
-     * Does a delete on all related objects of type $relationName and removes
2611
-     * the current model object's relation to them. If they can't be deleted (because
2612
-     * of blocking related model objects) does nothing. If the related model objects are
2613
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2614
-     * If this model object doesn't exist yet in the DB, just removes its related things
2615
-     *
2616
-     * @param string $relationName
2617
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2618
-     * @return int how many deleted
2619
-     * @throws ReflectionException
2620
-     * @throws InvalidArgumentException
2621
-     * @throws InvalidInterfaceException
2622
-     * @throws InvalidDataTypeException
2623
-     * @throws EE_Error
2624
-     */
2625
-    public function delete_related($relationName, $query_params = array())
2626
-    {
2627
-        if ($this->ID()) {
2628
-            $count = $this->get_model()->delete_related(
2629
-                $this,
2630
-                $relationName,
2631
-                $query_params
2632
-            );
2633
-        } else {
2634
-            $count = count($this->get_all_from_cache($relationName));
2635
-            $this->clear_cache($relationName, null, true);
2636
-        }
2637
-        return $count;
2638
-    }
2639
-
2640
-
2641
-    /**
2642
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2643
-     * the current model object's relation to them. If they can't be deleted (because
2644
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2645
-     * If the related thing isn't a soft-deletable model object, this function is identical
2646
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2647
-     *
2648
-     * @param string $relationName
2649
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2650
-     * @return int how many deleted (including those soft deleted)
2651
-     * @throws ReflectionException
2652
-     * @throws InvalidArgumentException
2653
-     * @throws InvalidInterfaceException
2654
-     * @throws InvalidDataTypeException
2655
-     * @throws EE_Error
2656
-     */
2657
-    public function delete_related_permanently($relationName, $query_params = array())
2658
-    {
2659
-        if ($this->ID()) {
2660
-            $count = $this->get_model()->delete_related_permanently(
2661
-                $this,
2662
-                $relationName,
2663
-                $query_params
2664
-            );
2665
-        } else {
2666
-            $count = count($this->get_all_from_cache($relationName));
2667
-        }
2668
-        $this->clear_cache($relationName, null, true);
2669
-        return $count;
2670
-    }
2671
-
2672
-
2673
-    /**
2674
-     * is_set
2675
-     * Just a simple utility function children can use for checking if property exists
2676
-     *
2677
-     * @access  public
2678
-     * @param  string $field_name property to check
2679
-     * @return bool                              TRUE if existing,FALSE if not.
2680
-     */
2681
-    public function is_set($field_name)
2682
-    {
2683
-        return isset($this->_fields[ $field_name ]);
2684
-    }
2685
-
2686
-
2687
-    /**
2688
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2689
-     * EE_Error exception if they don't
2690
-     *
2691
-     * @param  mixed (string|array) $properties properties to check
2692
-     * @throws EE_Error
2693
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2694
-     */
2695
-    protected function _property_exists($properties)
2696
-    {
2697
-        foreach ((array) $properties as $property_name) {
2698
-            // first make sure this property exists
2699
-            if (! $this->_fields[ $property_name ]) {
2700
-                throw new EE_Error(
2701
-                    sprintf(
2702
-                        esc_html__(
2703
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2704
-                            'event_espresso'
2705
-                        ),
2706
-                        $property_name
2707
-                    )
2708
-                );
2709
-            }
2710
-        }
2711
-        return true;
2712
-    }
2713
-
2714
-
2715
-    /**
2716
-     * This simply returns an array of model fields for this object
2717
-     *
2718
-     * @return array
2719
-     * @throws ReflectionException
2720
-     * @throws InvalidArgumentException
2721
-     * @throws InvalidInterfaceException
2722
-     * @throws InvalidDataTypeException
2723
-     * @throws EE_Error
2724
-     */
2725
-    public function model_field_array()
2726
-    {
2727
-        $fields = $this->get_model()->field_settings(false);
2728
-        $properties = array();
2729
-        // remove prepended underscore
2730
-        foreach ($fields as $field_name => $settings) {
2731
-            $properties[ $field_name ] = $this->get($field_name);
2732
-        }
2733
-        return $properties;
2734
-    }
2735
-
2736
-
2737
-    /**
2738
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2739
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2740
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2741
-     * Instead of requiring a plugin to extend the EE_Base_Class
2742
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2743
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2744
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2745
-     * and accepts 2 arguments: the object on which the function was called,
2746
-     * and an array of the original arguments passed to the function.
2747
-     * Whatever their callback function returns will be returned by this function.
2748
-     *
2749
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2750
-     * @param array  $args       array of original arguments passed to the function
2751
-     * @throws EE_Error
2752
-     * @return mixed whatever the plugin which calls add_filter decides
2753
-     */
2754
-    public function __call($methodName, $args)
2755
-    {
2756
-        $className = get_class($this);
2757
-        $tagName = "FHEE__{$className}__{$methodName}";
2758
-        if (! has_filter($tagName)) {
2759
-            throw new EE_Error(
2760
-                sprintf(
2761
-                    esc_html__(
2762
-                        "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;}",
2763
-                        'event_espresso'
2764
-                    ),
2765
-                    $methodName,
2766
-                    $className,
2767
-                    $tagName
2768
-                )
2769
-            );
2770
-        }
2771
-        return apply_filters($tagName, null, $this, $args);
2772
-    }
2773
-
2774
-
2775
-    /**
2776
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2777
-     * A $previous_value can be specified in case there are many meta rows with the same key
2778
-     *
2779
-     * @param string $meta_key
2780
-     * @param mixed  $meta_value
2781
-     * @param mixed  $previous_value
2782
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2783
-     *                  NOTE: if the values haven't changed, returns 0
2784
-     * @throws InvalidArgumentException
2785
-     * @throws InvalidInterfaceException
2786
-     * @throws InvalidDataTypeException
2787
-     * @throws EE_Error
2788
-     * @throws ReflectionException
2789
-     */
2790
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2791
-    {
2792
-        $query_params = array(
2793
-            array(
2794
-                'EXM_key'  => $meta_key,
2795
-                'OBJ_ID'   => $this->ID(),
2796
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2797
-            ),
2798
-        );
2799
-        if ($previous_value !== null) {
2800
-            $query_params[0]['EXM_value'] = $meta_value;
2801
-        }
2802
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2803
-        if (! $existing_rows_like_that) {
2804
-            return $this->add_extra_meta($meta_key, $meta_value);
2805
-        }
2806
-        foreach ($existing_rows_like_that as $existing_row) {
2807
-            $existing_row->save(array('EXM_value' => $meta_value));
2808
-        }
2809
-        return count($existing_rows_like_that);
2810
-    }
2811
-
2812
-
2813
-    /**
2814
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2815
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2816
-     * extra meta row was entered, false if not
2817
-     *
2818
-     * @param string  $meta_key
2819
-     * @param mixed   $meta_value
2820
-     * @param boolean $unique
2821
-     * @return boolean
2822
-     * @throws InvalidArgumentException
2823
-     * @throws InvalidInterfaceException
2824
-     * @throws InvalidDataTypeException
2825
-     * @throws EE_Error
2826
-     * @throws ReflectionException
2827
-     * @throws ReflectionException
2828
-     */
2829
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2830
-    {
2831
-        if ($unique) {
2832
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2833
-                array(
2834
-                    array(
2835
-                        'EXM_key'  => $meta_key,
2836
-                        'OBJ_ID'   => $this->ID(),
2837
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2838
-                    ),
2839
-                )
2840
-            );
2841
-            if ($existing_extra_meta) {
2842
-                return false;
2843
-            }
2844
-        }
2845
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2846
-            array(
2847
-                'EXM_key'   => $meta_key,
2848
-                'EXM_value' => $meta_value,
2849
-                'OBJ_ID'    => $this->ID(),
2850
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2851
-            )
2852
-        );
2853
-        $new_extra_meta->save();
2854
-        return true;
2855
-    }
2856
-
2857
-
2858
-    /**
2859
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2860
-     * is specified, only deletes extra meta records with that value.
2861
-     *
2862
-     * @param string $meta_key
2863
-     * @param mixed  $meta_value
2864
-     * @return int number of extra meta rows deleted
2865
-     * @throws InvalidArgumentException
2866
-     * @throws InvalidInterfaceException
2867
-     * @throws InvalidDataTypeException
2868
-     * @throws EE_Error
2869
-     * @throws ReflectionException
2870
-     */
2871
-    public function delete_extra_meta($meta_key, $meta_value = null)
2872
-    {
2873
-        $query_params = array(
2874
-            array(
2875
-                'EXM_key'  => $meta_key,
2876
-                'OBJ_ID'   => $this->ID(),
2877
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2878
-            ),
2879
-        );
2880
-        if ($meta_value !== null) {
2881
-            $query_params[0]['EXM_value'] = $meta_value;
2882
-        }
2883
-        return EEM_Extra_Meta::instance()->delete($query_params);
2884
-    }
2885
-
2886
-
2887
-    /**
2888
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2889
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2890
-     * You can specify $default is case you haven't found the extra meta
2891
-     *
2892
-     * @param string  $meta_key
2893
-     * @param boolean $single
2894
-     * @param mixed   $default if we don't find anything, what should we return?
2895
-     * @return mixed single value if $single; array if ! $single
2896
-     * @throws ReflectionException
2897
-     * @throws InvalidArgumentException
2898
-     * @throws InvalidInterfaceException
2899
-     * @throws InvalidDataTypeException
2900
-     * @throws EE_Error
2901
-     */
2902
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2903
-    {
2904
-        if ($single) {
2905
-            $result = $this->get_first_related(
2906
-                'Extra_Meta',
2907
-                array(array('EXM_key' => $meta_key))
2908
-            );
2909
-            if ($result instanceof EE_Extra_Meta) {
2910
-                return $result->value();
2911
-            }
2912
-        } else {
2913
-            $results = $this->get_many_related(
2914
-                'Extra_Meta',
2915
-                array(array('EXM_key' => $meta_key))
2916
-            );
2917
-            if ($results) {
2918
-                $values = array();
2919
-                foreach ($results as $result) {
2920
-                    if ($result instanceof EE_Extra_Meta) {
2921
-                        $values[ $result->ID() ] = $result->value();
2922
-                    }
2923
-                }
2924
-                return $values;
2925
-            }
2926
-        }
2927
-        // if nothing discovered yet return default.
2928
-        return apply_filters(
2929
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2930
-            $default,
2931
-            $meta_key,
2932
-            $single,
2933
-            $this
2934
-        );
2935
-    }
2936
-
2937
-
2938
-    /**
2939
-     * Returns a simple array of all the extra meta associated with this model object.
2940
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2941
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2942
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2943
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2944
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2945
-     * finally the extra meta's value as each sub-value. (eg
2946
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2947
-     *
2948
-     * @param boolean $one_of_each_key
2949
-     * @return array
2950
-     * @throws ReflectionException
2951
-     * @throws InvalidArgumentException
2952
-     * @throws InvalidInterfaceException
2953
-     * @throws InvalidDataTypeException
2954
-     * @throws EE_Error
2955
-     */
2956
-    public function all_extra_meta_array($one_of_each_key = true)
2957
-    {
2958
-        $return_array = array();
2959
-        if ($one_of_each_key) {
2960
-            $extra_meta_objs = $this->get_many_related(
2961
-                'Extra_Meta',
2962
-                array('group_by' => 'EXM_key')
2963
-            );
2964
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2965
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2966
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2967
-                }
2968
-            }
2969
-        } else {
2970
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2971
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2972
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2973
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2974
-                        $return_array[ $extra_meta_obj->key() ] = array();
2975
-                    }
2976
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2977
-                }
2978
-            }
2979
-        }
2980
-        return $return_array;
2981
-    }
2982
-
2983
-
2984
-    /**
2985
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2986
-     *
2987
-     * @return string
2988
-     * @throws ReflectionException
2989
-     * @throws InvalidArgumentException
2990
-     * @throws InvalidInterfaceException
2991
-     * @throws InvalidDataTypeException
2992
-     * @throws EE_Error
2993
-     */
2994
-    public function name()
2995
-    {
2996
-        // find a field that's not a text field
2997
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2998
-        if ($field_we_can_use) {
2999
-            return $this->get($field_we_can_use->get_name());
3000
-        }
3001
-        $first_few_properties = $this->model_field_array();
3002
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3003
-        $name_parts = array();
3004
-        foreach ($first_few_properties as $name => $value) {
3005
-            $name_parts[] = "$name:$value";
3006
-        }
3007
-        return implode(',', $name_parts);
3008
-    }
3009
-
3010
-
3011
-    /**
3012
-     * in_entity_map
3013
-     * Checks if this model object has been proven to already be in the entity map
3014
-     *
3015
-     * @return boolean
3016
-     * @throws ReflectionException
3017
-     * @throws InvalidArgumentException
3018
-     * @throws InvalidInterfaceException
3019
-     * @throws InvalidDataTypeException
3020
-     * @throws EE_Error
3021
-     */
3022
-    public function in_entity_map()
3023
-    {
3024
-        // well, if we looked, did we find it in the entity map?
3025
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3026
-    }
3027
-
3028
-
3029
-    /**
3030
-     * refresh_from_db
3031
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3032
-     *
3033
-     * @throws ReflectionException
3034
-     * @throws InvalidArgumentException
3035
-     * @throws InvalidInterfaceException
3036
-     * @throws InvalidDataTypeException
3037
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3038
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3039
-     */
3040
-    public function refresh_from_db()
3041
-    {
3042
-        if ($this->ID() && $this->in_entity_map()) {
3043
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3044
-        } else {
3045
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3046
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3047
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3048
-            // absolutely nothing in it for this ID
3049
-            if (WP_DEBUG) {
3050
-                throw new EE_Error(
3051
-                    sprintf(
3052
-                        esc_html__(
3053
-                            '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.',
3054
-                            'event_espresso'
3055
-                        ),
3056
-                        $this->ID(),
3057
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3058
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3059
-                    )
3060
-                );
3061
-            }
3062
-        }
3063
-    }
3064
-
3065
-
3066
-    /**
3067
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3068
-     *
3069
-     * @since 4.9.80.p
3070
-     * @param EE_Model_Field_Base[] $fields
3071
-     * @param string $new_value_sql
3072
-     *      example: 'column_name=123',
3073
-     *      or 'column_name=column_name+1',
3074
-     *      or 'column_name= CASE
3075
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3076
-     *          THEN `column_name` + 5
3077
-     *          ELSE `column_name`
3078
-     *      END'
3079
-     *      Also updates $field on this model object with the latest value from the database.
3080
-     * @return bool
3081
-     * @throws EE_Error
3082
-     * @throws InvalidArgumentException
3083
-     * @throws InvalidDataTypeException
3084
-     * @throws InvalidInterfaceException
3085
-     * @throws ReflectionException
3086
-     */
3087
-    protected function updateFieldsInDB($fields, $new_value_sql)
3088
-    {
3089
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3090
-        // if it wasn't even there to start off.
3091
-        if (! $this->ID()) {
3092
-            $this->save();
3093
-        }
3094
-        global $wpdb;
3095
-        if (empty($fields)) {
3096
-            throw new InvalidArgumentException(
3097
-                esc_html__(
3098
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3099
-                    'event_espresso'
3100
-                )
3101
-            );
3102
-        }
3103
-        $first_field = reset($fields);
3104
-        $table_alias = $first_field->get_table_alias();
3105
-        foreach ($fields as $field) {
3106
-            if ($table_alias !== $field->get_table_alias()) {
3107
-                throw new InvalidArgumentException(
3108
-                    sprintf(
3109
-                        esc_html__(
3110
-                            // @codingStandardsIgnoreStart
3111
-                            '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.',
3112
-                            // @codingStandardsIgnoreEnd
3113
-                            'event_espresso'
3114
-                        ),
3115
-                        $table_alias,
3116
-                        $field->get_table_alias()
3117
-                    )
3118
-                );
3119
-            }
3120
-        }
3121
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3122
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3123
-        $table_pk_value = $this->ID();
3124
-        $table_name = $table_obj->get_table_name();
3125
-        if ($table_obj instanceof EE_Secondary_Table) {
3126
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3127
-        } else {
3128
-            $table_pk_field_name = $table_obj->get_pk_column();
3129
-        }
3130
-
3131
-        $query =
3132
-            "UPDATE `{$table_name}`
338
+				$this->_props_n_values_provided_in_constructor
339
+				&& $field_value
340
+				&& $field_name === $model->primary_key_name()
341
+			) {
342
+				// if so, we want all this object's fields to be filled either with
343
+				// what we've explicitly set on this model
344
+				// or what we have in the db
345
+				// echo "setting primary key!";
346
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
347
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
348
+				foreach ($fields_on_model as $field_obj) {
349
+					if (
350
+						! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
351
+						&& $field_obj->get_name() !== $field_name
352
+					) {
353
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
354
+					}
355
+				}
356
+				// oh this model object has an ID? well make sure its in the entity mapper
357
+				$model->add_to_entity_map($this);
358
+			}
359
+			// let's unset any cache for this field_name from the $_cached_properties property.
360
+			$this->_clear_cached_property($field_name);
361
+		} else {
362
+			throw new EE_Error(
363
+				sprintf(
364
+					esc_html__(
365
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
366
+						'event_espresso'
367
+					),
368
+					$field_name
369
+				)
370
+			);
371
+		}
372
+	}
373
+
374
+
375
+	/**
376
+	 * Set custom select values for model.
377
+	 *
378
+	 * @param array $custom_select_values
379
+	 */
380
+	public function setCustomSelectsValues(array $custom_select_values)
381
+	{
382
+		$this->custom_selection_results = $custom_select_values;
383
+	}
384
+
385
+
386
+	/**
387
+	 * Returns the custom select value for the provided alias if its set.
388
+	 * If not set, returns null.
389
+	 *
390
+	 * @param string $alias
391
+	 * @return string|int|float|null
392
+	 */
393
+	public function getCustomSelect($alias)
394
+	{
395
+		return isset($this->custom_selection_results[ $alias ])
396
+			? $this->custom_selection_results[ $alias ]
397
+			: 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
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
406
+	 * @param string $field_name  Must be the exact column name.
407
+	 * @param mixed  $field_value The value to set.
408
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
409
+	 * @throws InvalidArgumentException
410
+	 * @throws InvalidInterfaceException
411
+	 * @throws InvalidDataTypeException
412
+	 * @throws EE_Error
413
+	 * @throws ReflectionException
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
+	 */
473
+	public function set_timezone($timezone = '')
474
+	{
475
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
476
+		// make sure we clear all cached properties because they won't be relevant now
477
+		$this->_clear_cached_properties();
478
+		// make sure we update field settings and the date for all EE_Datetime_Fields
479
+		$model_fields = $this->get_model()->field_settings(false);
480
+		foreach ($model_fields as $field_name => $field_obj) {
481
+			if ($field_obj instanceof EE_Datetime_Field) {
482
+				$field_obj->set_timezone($this->_timezone);
483
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
484
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
485
+				}
486
+			}
487
+		}
488
+	}
489
+
490
+
491
+	/**
492
+	 * This just returns whatever is set for the current timezone.
493
+	 *
494
+	 * @access public
495
+	 * @return string timezone string
496
+	 */
497
+	public function get_timezone()
498
+	{
499
+		return $this->_timezone;
500
+	}
501
+
502
+
503
+	/**
504
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
505
+	 * internally instead of wp set date format options
506
+	 *
507
+	 * @since 4.6
508
+	 * @param string $format should be a format recognizable by PHP date() functions.
509
+	 */
510
+	public function set_date_format($format)
511
+	{
512
+		$this->_dt_frmt = $format;
513
+		// clear cached_properties because they won't be relevant now.
514
+		$this->_clear_cached_properties();
515
+	}
516
+
517
+
518
+	/**
519
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
520
+	 * class internally instead of wp set time format options.
521
+	 *
522
+	 * @since 4.6
523
+	 * @param string $format should be a format recognizable by PHP date() functions.
524
+	 */
525
+	public function set_time_format($format)
526
+	{
527
+		$this->_tm_frmt = $format;
528
+		// clear cached_properties because they won't be relevant now.
529
+		$this->_clear_cached_properties();
530
+	}
531
+
532
+
533
+	/**
534
+	 * This returns the current internal set format for the date and time formats.
535
+	 *
536
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
537
+	 *                             where the first value is the date format and the second value is the time format.
538
+	 * @return mixed string|array
539
+	 */
540
+	public function get_format($full = true)
541
+	{
542
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
543
+	}
544
+
545
+
546
+	/**
547
+	 * cache
548
+	 * stores the passed model object on the current model object.
549
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
550
+	 *
551
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
552
+	 *                                       'Registration' associated with this model object
553
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
554
+	 *                                       that could be a payment or a registration)
555
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
556
+	 *                                       items which will be stored in an array on this object
557
+	 * @throws ReflectionException
558
+	 * @throws InvalidArgumentException
559
+	 * @throws InvalidInterfaceException
560
+	 * @throws InvalidDataTypeException
561
+	 * @throws EE_Error
562
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
563
+	 *                                       related thing, no array)
564
+	 */
565
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
566
+	{
567
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
568
+		if (! $object_to_cache instanceof EE_Base_Class) {
569
+			return false;
570
+		}
571
+		// also get "how" the object is related, or throw an error
572
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
573
+			throw new EE_Error(
574
+				sprintf(
575
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
576
+					$relationName,
577
+					get_class($this)
578
+				)
579
+			);
580
+		}
581
+		// how many things are related ?
582
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
583
+			// if it's a "belongs to" relationship, then there's only one related model object
584
+			// eg, if this is a registration, there's only 1 attendee for it
585
+			// so for these model objects just set it to be cached
586
+			$this->_model_relations[ $relationName ] = $object_to_cache;
587
+			$return = true;
588
+		} else {
589
+			// otherwise, this is the "many" side of a one to many relationship,
590
+			// so we'll add the object to the array of related objects for that type.
591
+			// eg: if this is an event, there are many registrations for that event,
592
+			// so we cache the registrations in an array
593
+			if (! is_array($this->_model_relations[ $relationName ])) {
594
+				// if for some reason, the cached item is a model object,
595
+				// then stick that in the array, otherwise start with an empty array
596
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
597
+														   instanceof
598
+														   EE_Base_Class
599
+					? array($this->_model_relations[ $relationName ]) : array();
600
+			}
601
+			// first check for a cache_id which is normally empty
602
+			if (! empty($cache_id)) {
603
+				// if the cache_id exists, then it means we are purposely trying to cache this
604
+				// with a known key that can then be used to retrieve the object later on
605
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
606
+				$return = $cache_id;
607
+			} elseif ($object_to_cache->ID()) {
608
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
609
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
610
+				$return = $object_to_cache->ID();
611
+			} else {
612
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
613
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
614
+				// move the internal pointer to the end of the array
615
+				end($this->_model_relations[ $relationName ]);
616
+				// and grab the key so that we can return it
617
+				$return = key($this->_model_relations[ $relationName ]);
618
+			}
619
+		}
620
+		return $return;
621
+	}
622
+
623
+
624
+	/**
625
+	 * For adding an item to the cached_properties property.
626
+	 *
627
+	 * @access protected
628
+	 * @param string      $fieldname the property item the corresponding value is for.
629
+	 * @param mixed       $value     The value we are caching.
630
+	 * @param string|null $cache_type
631
+	 * @return void
632
+	 * @throws ReflectionException
633
+	 * @throws InvalidArgumentException
634
+	 * @throws InvalidInterfaceException
635
+	 * @throws InvalidDataTypeException
636
+	 * @throws EE_Error
637
+	 */
638
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
639
+	{
640
+		// first make sure this property exists
641
+		$this->get_model()->field_settings_for($fieldname);
642
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
643
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
644
+	}
645
+
646
+
647
+	/**
648
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
649
+	 * This also SETS the cache if we return the actual property!
650
+	 *
651
+	 * @param string $fieldname        the name of the property we're trying to retrieve
652
+	 * @param bool   $pretty
653
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
654
+	 *                                 (in cases where the same property may be used for different outputs
655
+	 *                                 - i.e. datetime, money etc.)
656
+	 *                                 It can also accept certain pre-defined "schema" strings
657
+	 *                                 to define how to output the property.
658
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
659
+	 * @return mixed                   whatever the value for the property is we're retrieving
660
+	 * @throws ReflectionException
661
+	 * @throws InvalidArgumentException
662
+	 * @throws InvalidInterfaceException
663
+	 * @throws InvalidDataTypeException
664
+	 * @throws EE_Error
665
+	 */
666
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
667
+	{
668
+		// verify the field exists
669
+		$model = $this->get_model();
670
+		$model->field_settings_for($fieldname);
671
+		$cache_type = $pretty ? 'pretty' : 'standard';
672
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
673
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
674
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
675
+		}
676
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
677
+		$this->_set_cached_property($fieldname, $value, $cache_type);
678
+		return $value;
679
+	}
680
+
681
+
682
+	/**
683
+	 * If the cache didn't fetch the needed item, this fetches it.
684
+	 *
685
+	 * @param string $fieldname
686
+	 * @param bool   $pretty
687
+	 * @param string $extra_cache_ref
688
+	 * @return mixed
689
+	 * @throws InvalidArgumentException
690
+	 * @throws InvalidInterfaceException
691
+	 * @throws InvalidDataTypeException
692
+	 * @throws EE_Error
693
+	 * @throws ReflectionException
694
+	 */
695
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
696
+	{
697
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
698
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
699
+		if ($field_obj instanceof EE_Datetime_Field) {
700
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
701
+		}
702
+		if (! isset($this->_fields[ $fieldname ])) {
703
+			$this->_fields[ $fieldname ] = null;
704
+		}
705
+		$value = $pretty
706
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
707
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
708
+		return $value;
709
+	}
710
+
711
+
712
+	/**
713
+	 * set timezone, formats, and output for EE_Datetime_Field objects
714
+	 *
715
+	 * @param \EE_Datetime_Field $datetime_field
716
+	 * @param bool               $pretty
717
+	 * @param null               $date_or_time
718
+	 * @return void
719
+	 * @throws InvalidArgumentException
720
+	 * @throws InvalidInterfaceException
721
+	 * @throws InvalidDataTypeException
722
+	 * @throws EE_Error
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 = array();
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 $relationName                         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
+	 * @throws ReflectionException
807
+	 * @throws InvalidArgumentException
808
+	 * @throws InvalidInterfaceException
809
+	 * @throws InvalidDataTypeException
810
+	 * @throws EE_Error
811
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
812
+	 *                                                     relation from all
813
+	 */
814
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
815
+	{
816
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
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
+					$relationName,
823
+					get_class($this)
824
+				)
825
+			);
826
+		}
827
+		if ($clear_all) {
828
+			$obj_removed = true;
829
+			$this->_model_relations[ $relationName ] = null;
830
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
831
+			$obj_removed = $this->_model_relations[ $relationName ];
832
+			$this->_model_relations[ $relationName ] = 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[ $relationName ])
841
+					&& ! isset($this->_model_relations[ $relationName ][ $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[ $relationName ] 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($relationName) 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[ $relationName ][ $index_in_cache ])) {
880
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
881
+				unset($this->_model_relations[ $relationName ][ $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        $relationName       - 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
+		$relationName,
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_' . $relationName;
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($relationName);
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[ $relationName ] = $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[ $relationName ])
926
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
927
+			) {
928
+				// then remove the current cached item
929
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
930
+				// and cache the newly saved object using it's new ID
931
+				$this->_model_relations[ $relationName ][ $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 $relationName
944
+	 * @return EE_Base_Class
945
+	 */
946
+	public function get_one_from_cache($relationName)
947
+	{
948
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
949
+			? $this->_model_relations[ $relationName ]
950
+			: null;
951
+		if (is_array($cached_array_or_object)) {
952
+			return array_shift($cached_array_or_object);
953
+		}
954
+		return $cached_array_or_object;
955
+	}
956
+
957
+
958
+	/**
959
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
960
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
961
+	 *
962
+	 * @param string $relationName
963
+	 * @throws ReflectionException
964
+	 * @throws InvalidArgumentException
965
+	 * @throws InvalidInterfaceException
966
+	 * @throws InvalidDataTypeException
967
+	 * @throws EE_Error
968
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
969
+	 */
970
+	public function get_all_from_cache($relationName)
971
+	{
972
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
973
+		// if the result is not an array, but exists, make it an array
974
+		$objects = is_array($objects) ? $objects : array($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( $relationName )->get_one_by_ID( $result->ID() );
980
+		$model = EE_Registry::instance()->load_model($relationName);
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
+						$relationName,
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 = array(), $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) ? $this->get($field) : null;
1027
+		if (empty($field) || empty($current_value)) {
1028
+			return array();
1029
+		}
1030
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1031
+	}
1032
+
1033
+
1034
+	/**
1035
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1036
+	 * matching the given query conditions.
1037
+	 *
1038
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1039
+	 * @param int   $limit              How many objects to return.
1040
+	 * @param array $query_params       Any additional conditions on the query.
1041
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1042
+	 *                                  you can indicate just the columns you want returned
1043
+	 * @return array|EE_Base_Class[]
1044
+	 * @throws ReflectionException
1045
+	 * @throws InvalidArgumentException
1046
+	 * @throws InvalidInterfaceException
1047
+	 * @throws InvalidDataTypeException
1048
+	 * @throws EE_Error
1049
+	 */
1050
+	public function previous_x(
1051
+		$field_to_order_by = null,
1052
+		$limit = 1,
1053
+		$query_params = array(),
1054
+		$columns_to_select = null
1055
+	) {
1056
+		$model = $this->get_model();
1057
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1058
+			? $model->get_primary_key_field()->get_name()
1059
+			: $field_to_order_by;
1060
+		$current_value = ! empty($field) ? $this->get($field) : null;
1061
+		if (empty($field) || empty($current_value)) {
1062
+			return array();
1063
+		}
1064
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1065
+	}
1066
+
1067
+
1068
+	/**
1069
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1070
+	 * matching the given query conditions.
1071
+	 *
1072
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1073
+	 * @param array $query_params       Any additional conditions on the query.
1074
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1075
+	 *                                  you can indicate just the columns you want returned
1076
+	 * @return array|EE_Base_Class
1077
+	 * @throws ReflectionException
1078
+	 * @throws InvalidArgumentException
1079
+	 * @throws InvalidInterfaceException
1080
+	 * @throws InvalidDataTypeException
1081
+	 * @throws EE_Error
1082
+	 */
1083
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1084
+	{
1085
+		$model = $this->get_model();
1086
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1087
+			? $model->get_primary_key_field()->get_name()
1088
+			: $field_to_order_by;
1089
+		$current_value = ! empty($field) ? $this->get($field) : null;
1090
+		if (empty($field) || empty($current_value)) {
1091
+			return array();
1092
+		}
1093
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1094
+	}
1095
+
1096
+
1097
+	/**
1098
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1099
+	 * matching the given query conditions.
1100
+	 *
1101
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1102
+	 * @param array $query_params       Any additional conditions on the query.
1103
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1104
+	 *                                  you can indicate just the column you want returned
1105
+	 * @return array|EE_Base_Class
1106
+	 * @throws ReflectionException
1107
+	 * @throws InvalidArgumentException
1108
+	 * @throws InvalidInterfaceException
1109
+	 * @throws InvalidDataTypeException
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1113
+	{
1114
+		$model = $this->get_model();
1115
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1116
+			? $model->get_primary_key_field()->get_name()
1117
+			: $field_to_order_by;
1118
+		$current_value = ! empty($field) ? $this->get($field) : null;
1119
+		if (empty($field) || empty($current_value)) {
1120
+			return array();
1121
+		}
1122
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1123
+	}
1124
+
1125
+
1126
+	/**
1127
+	 * Overrides parent because parent expects old models.
1128
+	 * This also doesn't do any validation, and won't work for serialized arrays
1129
+	 *
1130
+	 * @param string $field_name
1131
+	 * @param mixed  $field_value_from_db
1132
+	 * @throws ReflectionException
1133
+	 * @throws InvalidArgumentException
1134
+	 * @throws InvalidInterfaceException
1135
+	 * @throws InvalidDataTypeException
1136
+	 * @throws EE_Error
1137
+	 */
1138
+	public function set_from_db($field_name, $field_value_from_db)
1139
+	{
1140
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1141
+		if ($field_obj instanceof EE_Model_Field_Base) {
1142
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
1143
+			// eg, a CPT model object could have an entry in the posts table, but no
1144
+			// entry in the meta table. Meaning that all its columns in the meta table
1145
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
1146
+			if ($field_value_from_db === null) {
1147
+				if ($field_obj->is_nullable()) {
1148
+					// if the field allows nulls, then let it be null
1149
+					$field_value = null;
1150
+				} else {
1151
+					$field_value = $field_obj->get_default_value();
1152
+				}
1153
+			} else {
1154
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1155
+			}
1156
+			$this->_fields[ $field_name ] = $field_value;
1157
+			$this->_clear_cached_property($field_name);
1158
+		}
1159
+	}
1160
+
1161
+
1162
+	/**
1163
+	 * verifies that the specified field is of the correct type
1164
+	 *
1165
+	 * @param string $field_name
1166
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1167
+	 *                                (in cases where the same property may be used for different outputs
1168
+	 *                                - i.e. datetime, money etc.)
1169
+	 * @return mixed
1170
+	 * @throws ReflectionException
1171
+	 * @throws InvalidArgumentException
1172
+	 * @throws InvalidInterfaceException
1173
+	 * @throws InvalidDataTypeException
1174
+	 * @throws EE_Error
1175
+	 */
1176
+	public function get($field_name, $extra_cache_ref = null)
1177
+	{
1178
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1179
+	}
1180
+
1181
+
1182
+	/**
1183
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1184
+	 *
1185
+	 * @param  string $field_name A valid fieldname
1186
+	 * @return mixed              Whatever the raw value stored on the property is.
1187
+	 * @throws ReflectionException
1188
+	 * @throws InvalidArgumentException
1189
+	 * @throws InvalidInterfaceException
1190
+	 * @throws InvalidDataTypeException
1191
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1192
+	 */
1193
+	public function get_raw($field_name)
1194
+	{
1195
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1196
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1197
+			? $this->_fields[ $field_name ]->format('U')
1198
+			: $this->_fields[ $field_name ];
1199
+	}
1200
+
1201
+
1202
+	/**
1203
+	 * This is used to return the internal DateTime object used for a field that is a
1204
+	 * EE_Datetime_Field.
1205
+	 *
1206
+	 * @param string $field_name               The field name retrieving the DateTime object.
1207
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1208
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1209
+	 *                                         EE_Datetime_Field and but the field value is null, then
1210
+	 *                                         just null is returned (because that indicates that likely
1211
+	 *                                         this field is nullable).
1212
+	 * @throws InvalidArgumentException
1213
+	 * @throws InvalidDataTypeException
1214
+	 * @throws InvalidInterfaceException
1215
+	 * @throws ReflectionException
1216
+	 */
1217
+	public function get_DateTime_object($field_name)
1218
+	{
1219
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1220
+		if (! $field_settings instanceof EE_Datetime_Field) {
1221
+			EE_Error::add_error(
1222
+				sprintf(
1223
+					esc_html__(
1224
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1225
+						'event_espresso'
1226
+					),
1227
+					$field_name
1228
+				),
1229
+				__FILE__,
1230
+				__FUNCTION__,
1231
+				__LINE__
1232
+			);
1233
+			return false;
1234
+		}
1235
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1236
+			? clone $this->_fields[ $field_name ]
1237
+			: null;
1238
+	}
1239
+
1240
+
1241
+	/**
1242
+	 * To be used in template to immediately echo out the value, and format it for output.
1243
+	 * Eg, should call stripslashes and whatnot before echoing
1244
+	 *
1245
+	 * @param string $field_name      the name of the field as it appears in the DB
1246
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1247
+	 *                                (in cases where the same property may be used for different outputs
1248
+	 *                                - i.e. datetime, money etc.)
1249
+	 * @return void
1250
+	 * @throws ReflectionException
1251
+	 * @throws InvalidArgumentException
1252
+	 * @throws InvalidInterfaceException
1253
+	 * @throws InvalidDataTypeException
1254
+	 * @throws EE_Error
1255
+	 */
1256
+	public function e($field_name, $extra_cache_ref = null)
1257
+	{
1258
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1259
+	}
1260
+
1261
+
1262
+	/**
1263
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1264
+	 * can be easily used as the value of form input.
1265
+	 *
1266
+	 * @param string $field_name
1267
+	 * @return void
1268
+	 * @throws ReflectionException
1269
+	 * @throws InvalidArgumentException
1270
+	 * @throws InvalidInterfaceException
1271
+	 * @throws InvalidDataTypeException
1272
+	 * @throws EE_Error
1273
+	 */
1274
+	public function f($field_name)
1275
+	{
1276
+		$this->e($field_name, 'form_input');
1277
+	}
1278
+
1279
+
1280
+	/**
1281
+	 * Same as `f()` but just returns the value instead of echoing it
1282
+	 *
1283
+	 * @param string $field_name
1284
+	 * @return string
1285
+	 * @throws ReflectionException
1286
+	 * @throws InvalidArgumentException
1287
+	 * @throws InvalidInterfaceException
1288
+	 * @throws InvalidDataTypeException
1289
+	 * @throws EE_Error
1290
+	 */
1291
+	public function get_f($field_name)
1292
+	{
1293
+		return (string) $this->get_pretty($field_name, 'form_input');
1294
+	}
1295
+
1296
+
1297
+	/**
1298
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1299
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1300
+	 * to see what options are available.
1301
+	 *
1302
+	 * @param string $field_name
1303
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1304
+	 *                                (in cases where the same property may be used for different outputs
1305
+	 *                                - i.e. datetime, money etc.)
1306
+	 * @return mixed
1307
+	 * @throws ReflectionException
1308
+	 * @throws InvalidArgumentException
1309
+	 * @throws InvalidInterfaceException
1310
+	 * @throws InvalidDataTypeException
1311
+	 * @throws EE_Error
1312
+	 */
1313
+	public function get_pretty($field_name, $extra_cache_ref = null)
1314
+	{
1315
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1316
+	}
1317
+
1318
+
1319
+	/**
1320
+	 * This simply returns the datetime for the given field name
1321
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1322
+	 * (and the equivalent e_date, e_time, e_datetime).
1323
+	 *
1324
+	 * @access   protected
1325
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1326
+	 * @param string   $dt_frmt      valid datetime format used for date
1327
+	 *                               (if '' then we just use the default on the field,
1328
+	 *                               if NULL we use the last-used format)
1329
+	 * @param string   $tm_frmt      Same as above except this is for time format
1330
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1331
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1332
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1333
+	 *                               if field is not a valid dtt field, or void if echoing
1334
+	 * @throws ReflectionException
1335
+	 * @throws InvalidArgumentException
1336
+	 * @throws InvalidInterfaceException
1337
+	 * @throws InvalidDataTypeException
1338
+	 * @throws EE_Error
1339
+	 */
1340
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1341
+	{
1342
+		// clear cached property
1343
+		$this->_clear_cached_property($field_name);
1344
+		// reset format properties because they are used in get()
1345
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1346
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1347
+		if ($echo) {
1348
+			$this->e($field_name, $date_or_time);
1349
+			return '';
1350
+		}
1351
+		return $this->get($field_name, $date_or_time);
1352
+	}
1353
+
1354
+
1355
+	/**
1356
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1357
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1358
+	 * other echoes the pretty value for dtt)
1359
+	 *
1360
+	 * @param  string $field_name name of model object datetime field holding the value
1361
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1362
+	 * @return string            datetime value formatted
1363
+	 * @throws ReflectionException
1364
+	 * @throws InvalidArgumentException
1365
+	 * @throws InvalidInterfaceException
1366
+	 * @throws InvalidDataTypeException
1367
+	 * @throws EE_Error
1368
+	 */
1369
+	public function get_date($field_name, $format = '')
1370
+	{
1371
+		return $this->_get_datetime($field_name, $format, null, 'D');
1372
+	}
1373
+
1374
+
1375
+	/**
1376
+	 * @param        $field_name
1377
+	 * @param string $format
1378
+	 * @throws ReflectionException
1379
+	 * @throws InvalidArgumentException
1380
+	 * @throws InvalidInterfaceException
1381
+	 * @throws InvalidDataTypeException
1382
+	 * @throws EE_Error
1383
+	 */
1384
+	public function e_date($field_name, $format = '')
1385
+	{
1386
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1387
+	}
1388
+
1389
+
1390
+	/**
1391
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1392
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1393
+	 * other echoes the pretty value for dtt)
1394
+	 *
1395
+	 * @param  string $field_name name of model object datetime field holding the value
1396
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1397
+	 * @return string             datetime value formatted
1398
+	 * @throws ReflectionException
1399
+	 * @throws InvalidArgumentException
1400
+	 * @throws InvalidInterfaceException
1401
+	 * @throws InvalidDataTypeException
1402
+	 * @throws EE_Error
1403
+	 */
1404
+	public function get_time($field_name, $format = '')
1405
+	{
1406
+		return $this->_get_datetime($field_name, null, $format, 'T');
1407
+	}
1408
+
1409
+
1410
+	/**
1411
+	 * @param        $field_name
1412
+	 * @param string $format
1413
+	 * @throws ReflectionException
1414
+	 * @throws InvalidArgumentException
1415
+	 * @throws InvalidInterfaceException
1416
+	 * @throws InvalidDataTypeException
1417
+	 * @throws EE_Error
1418
+	 */
1419
+	public function e_time($field_name, $format = '')
1420
+	{
1421
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1422
+	}
1423
+
1424
+
1425
+	/**
1426
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1427
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1428
+	 * other echoes the pretty value for dtt)
1429
+	 *
1430
+	 * @param  string $field_name name of model object datetime field holding the value
1431
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1432
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1433
+	 * @return string             datetime value formatted
1434
+	 * @throws ReflectionException
1435
+	 * @throws InvalidArgumentException
1436
+	 * @throws InvalidInterfaceException
1437
+	 * @throws InvalidDataTypeException
1438
+	 * @throws EE_Error
1439
+	 */
1440
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1441
+	{
1442
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1443
+	}
1444
+
1445
+
1446
+	/**
1447
+	 * @param string $field_name
1448
+	 * @param string $dt_frmt
1449
+	 * @param string $tm_frmt
1450
+	 * @throws ReflectionException
1451
+	 * @throws InvalidArgumentException
1452
+	 * @throws InvalidInterfaceException
1453
+	 * @throws InvalidDataTypeException
1454
+	 * @throws EE_Error
1455
+	 */
1456
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1457
+	{
1458
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1459
+	}
1460
+
1461
+
1462
+	/**
1463
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1464
+	 *
1465
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1466
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1467
+	 *                           on the object will be used.
1468
+	 * @return string Date and time string in set locale or false if no field exists for the given
1469
+	 * @throws ReflectionException
1470
+	 * @throws InvalidArgumentException
1471
+	 * @throws InvalidInterfaceException
1472
+	 * @throws InvalidDataTypeException
1473
+	 * @throws EE_Error
1474
+	 *                           field name.
1475
+	 */
1476
+	public function get_i18n_datetime($field_name, $format = '')
1477
+	{
1478
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1479
+		return date_i18n(
1480
+			$format,
1481
+			EEH_DTT_Helper::get_timestamp_with_offset(
1482
+				$this->get_raw($field_name),
1483
+				$this->_timezone
1484
+			)
1485
+		);
1486
+	}
1487
+
1488
+
1489
+	/**
1490
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1491
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1492
+	 * thrown.
1493
+	 *
1494
+	 * @param  string $field_name The field name being checked
1495
+	 * @throws ReflectionException
1496
+	 * @throws InvalidArgumentException
1497
+	 * @throws InvalidInterfaceException
1498
+	 * @throws InvalidDataTypeException
1499
+	 * @throws EE_Error
1500
+	 * @return EE_Datetime_Field
1501
+	 */
1502
+	protected function _get_dtt_field_settings($field_name)
1503
+	{
1504
+		$field = $this->get_model()->field_settings_for($field_name);
1505
+		// check if field is dtt
1506
+		if ($field instanceof EE_Datetime_Field) {
1507
+			return $field;
1508
+		}
1509
+		throw new EE_Error(
1510
+			sprintf(
1511
+				esc_html__(
1512
+					'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',
1513
+					'event_espresso'
1514
+				),
1515
+				$field_name,
1516
+				self::_get_model_classname(get_class($this))
1517
+			)
1518
+		);
1519
+	}
1520
+
1521
+
1522
+
1523
+
1524
+	/**
1525
+	 * NOTE ABOUT BELOW:
1526
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1527
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1528
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1529
+	 * method and make sure you send the entire datetime value for setting.
1530
+	 */
1531
+	/**
1532
+	 * sets the time on a datetime property
1533
+	 *
1534
+	 * @access protected
1535
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1536
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1537
+	 * @throws ReflectionException
1538
+	 * @throws InvalidArgumentException
1539
+	 * @throws InvalidInterfaceException
1540
+	 * @throws InvalidDataTypeException
1541
+	 * @throws EE_Error
1542
+	 */
1543
+	protected function _set_time_for($time, $fieldname)
1544
+	{
1545
+		$this->_set_date_time('T', $time, $fieldname);
1546
+	}
1547
+
1548
+
1549
+	/**
1550
+	 * sets the date on a datetime property
1551
+	 *
1552
+	 * @access protected
1553
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1554
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1555
+	 * @throws ReflectionException
1556
+	 * @throws InvalidArgumentException
1557
+	 * @throws InvalidInterfaceException
1558
+	 * @throws InvalidDataTypeException
1559
+	 * @throws EE_Error
1560
+	 */
1561
+	protected function _set_date_for($date, $fieldname)
1562
+	{
1563
+		$this->_set_date_time('D', $date, $fieldname);
1564
+	}
1565
+
1566
+
1567
+	/**
1568
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1569
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1570
+	 *
1571
+	 * @access protected
1572
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1573
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1574
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1575
+	 *                                        EE_Datetime_Field property)
1576
+	 * @throws ReflectionException
1577
+	 * @throws InvalidArgumentException
1578
+	 * @throws InvalidInterfaceException
1579
+	 * @throws InvalidDataTypeException
1580
+	 * @throws EE_Error
1581
+	 */
1582
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1583
+	{
1584
+		$field = $this->_get_dtt_field_settings($fieldname);
1585
+		$field->set_timezone($this->_timezone);
1586
+		$field->set_date_format($this->_dt_frmt);
1587
+		$field->set_time_format($this->_tm_frmt);
1588
+		switch ($what) {
1589
+			case 'T':
1590
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1591
+					$datetime_value,
1592
+					$this->_fields[ $fieldname ]
1593
+				);
1594
+				$this->_has_changes = true;
1595
+				break;
1596
+			case 'D':
1597
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1598
+					$datetime_value,
1599
+					$this->_fields[ $fieldname ]
1600
+				);
1601
+				$this->_has_changes = true;
1602
+				break;
1603
+			case 'B':
1604
+				$this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1605
+				$this->_has_changes = true;
1606
+				break;
1607
+		}
1608
+		$this->_clear_cached_property($fieldname);
1609
+	}
1610
+
1611
+
1612
+	/**
1613
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1614
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1615
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1616
+	 * that could lead to some unexpected results!
1617
+	 *
1618
+	 * @access public
1619
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1620
+	 *                                         value being returned.
1621
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1622
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1623
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1624
+	 * @param string $append                   You can include something to append on the timestamp
1625
+	 * @throws ReflectionException
1626
+	 * @throws InvalidArgumentException
1627
+	 * @throws InvalidInterfaceException
1628
+	 * @throws InvalidDataTypeException
1629
+	 * @throws EE_Error
1630
+	 * @return string timestamp
1631
+	 */
1632
+	public function display_in_my_timezone(
1633
+		$field_name,
1634
+		$callback = 'get_datetime',
1635
+		$args = null,
1636
+		$prepend = '',
1637
+		$append = ''
1638
+	) {
1639
+		$timezone = EEH_DTT_Helper::get_timezone();
1640
+		if ($timezone === $this->_timezone) {
1641
+			return '';
1642
+		}
1643
+		$original_timezone = $this->_timezone;
1644
+		$this->set_timezone($timezone);
1645
+		$fn = (array) $field_name;
1646
+		$args = array_merge($fn, (array) $args);
1647
+		if (! method_exists($this, $callback)) {
1648
+			throw new EE_Error(
1649
+				sprintf(
1650
+					esc_html__(
1651
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1652
+						'event_espresso'
1653
+					),
1654
+					$callback
1655
+				)
1656
+			);
1657
+		}
1658
+		$args = (array) $args;
1659
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1660
+		$this->set_timezone($original_timezone);
1661
+		return $return;
1662
+	}
1663
+
1664
+
1665
+	/**
1666
+	 * Deletes this model object.
1667
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1668
+	 * override
1669
+	 * `EE_Base_Class::_delete` NOT this class.
1670
+	 *
1671
+	 * @return boolean | int
1672
+	 * @throws ReflectionException
1673
+	 * @throws InvalidArgumentException
1674
+	 * @throws InvalidInterfaceException
1675
+	 * @throws InvalidDataTypeException
1676
+	 * @throws EE_Error
1677
+	 */
1678
+	public function delete()
1679
+	{
1680
+		/**
1681
+		 * Called just before the `EE_Base_Class::_delete` method call.
1682
+		 * Note:
1683
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1684
+		 * should be aware that `_delete` may not always result in a permanent delete.
1685
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1686
+		 * soft deletes (trash) the object and does not permanently delete it.
1687
+		 *
1688
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1689
+		 */
1690
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1691
+		$result = $this->_delete();
1692
+		/**
1693
+		 * Called just after the `EE_Base_Class::_delete` method call.
1694
+		 * Note:
1695
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1696
+		 * should be aware that `_delete` may not always result in a permanent delete.
1697
+		 * For example `EE_Soft_Base_Class::_delete`
1698
+		 * soft deletes (trash) the object and does not permanently delete it.
1699
+		 *
1700
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1701
+		 * @param boolean       $result
1702
+		 */
1703
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1704
+		return $result;
1705
+	}
1706
+
1707
+
1708
+	/**
1709
+	 * Calls the specific delete method for the instantiated class.
1710
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1711
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1712
+	 * `EE_Base_Class::delete`
1713
+	 *
1714
+	 * @return bool|int
1715
+	 * @throws ReflectionException
1716
+	 * @throws InvalidArgumentException
1717
+	 * @throws InvalidInterfaceException
1718
+	 * @throws InvalidDataTypeException
1719
+	 * @throws EE_Error
1720
+	 */
1721
+	protected function _delete()
1722
+	{
1723
+		return $this->delete_permanently();
1724
+	}
1725
+
1726
+
1727
+	/**
1728
+	 * Deletes this model object permanently from db
1729
+	 * (but keep in mind related models may block the delete and return an error)
1730
+	 *
1731
+	 * @return bool | int
1732
+	 * @throws ReflectionException
1733
+	 * @throws InvalidArgumentException
1734
+	 * @throws InvalidInterfaceException
1735
+	 * @throws InvalidDataTypeException
1736
+	 * @throws EE_Error
1737
+	 */
1738
+	public function delete_permanently()
1739
+	{
1740
+		/**
1741
+		 * Called just before HARD deleting a model object
1742
+		 *
1743
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1744
+		 */
1745
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1746
+		$model = $this->get_model();
1747
+		$result = $model->delete_permanently_by_ID($this->ID());
1748
+		$this->refresh_cache_of_related_objects();
1749
+		/**
1750
+		 * Called just after HARD deleting a model object
1751
+		 *
1752
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1753
+		 * @param boolean       $result
1754
+		 */
1755
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1756
+		return $result;
1757
+	}
1758
+
1759
+
1760
+	/**
1761
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1762
+	 * related model objects
1763
+	 *
1764
+	 * @throws ReflectionException
1765
+	 * @throws InvalidArgumentException
1766
+	 * @throws InvalidInterfaceException
1767
+	 * @throws InvalidDataTypeException
1768
+	 * @throws EE_Error
1769
+	 */
1770
+	public function refresh_cache_of_related_objects()
1771
+	{
1772
+		$model = $this->get_model();
1773
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1774
+			if (! empty($this->_model_relations[ $relation_name ])) {
1775
+				$related_objects = $this->_model_relations[ $relation_name ];
1776
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1777
+					// this relation only stores a single model object, not an array
1778
+					// but let's make it consistent
1779
+					$related_objects = array($related_objects);
1780
+				}
1781
+				foreach ($related_objects as $related_object) {
1782
+					// only refresh their cache if they're in memory
1783
+					if ($related_object instanceof EE_Base_Class) {
1784
+						$related_object->clear_cache(
1785
+							$model->get_this_model_name(),
1786
+							$this
1787
+						);
1788
+					}
1789
+				}
1790
+			}
1791
+		}
1792
+	}
1793
+
1794
+
1795
+	/**
1796
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1797
+	 * object just before saving.
1798
+	 *
1799
+	 * @access public
1800
+	 * @param array $set_cols_n_values  keys are field names, values are their new values,
1801
+	 *                                  if provided during the save() method
1802
+	 *                                  (often client code will change the fields' values before calling save)
1803
+	 * @return false|int|string         1 on a successful update;
1804
+	 *                                  the ID of the new entry on insert;
1805
+	 *                                  0 on failure, or if the model object isn't allowed to persist
1806
+	 *                                  (as determined by EE_Base_Class::allow_persist())
1807
+	 * @throws InvalidInterfaceException
1808
+	 * @throws InvalidDataTypeException
1809
+	 * @throws EE_Error
1810
+	 * @throws InvalidArgumentException
1811
+	 * @throws ReflectionException
1812
+	 * @throws ReflectionException
1813
+	 * @throws ReflectionException
1814
+	 */
1815
+	public function save($set_cols_n_values = array())
1816
+	{
1817
+		$model = $this->get_model();
1818
+		/**
1819
+		 * Filters the fields we're about to save on the model object
1820
+		 *
1821
+		 * @param array         $set_cols_n_values
1822
+		 * @param EE_Base_Class $model_object
1823
+		 */
1824
+		$set_cols_n_values = (array) apply_filters(
1825
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1826
+			$set_cols_n_values,
1827
+			$this
1828
+		);
1829
+		// set attributes as provided in $set_cols_n_values
1830
+		foreach ($set_cols_n_values as $column => $value) {
1831
+			$this->set($column, $value);
1832
+		}
1833
+		// no changes ? then don't do anything
1834
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1835
+			return 0;
1836
+		}
1837
+		/**
1838
+		 * Saving a model object.
1839
+		 * Before we perform a save, this action is fired.
1840
+		 *
1841
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1842
+		 */
1843
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1844
+		if (! $this->allow_persist()) {
1845
+			return 0;
1846
+		}
1847
+		// now get current attribute values
1848
+		$save_cols_n_values = $this->_fields;
1849
+		// if the object already has an ID, update it. Otherwise, insert it
1850
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1851
+		// They have been
1852
+		$old_assumption_concerning_value_preparation = $model
1853
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1854
+		$model->assume_values_already_prepared_by_model_object(true);
1855
+		// does this model have an autoincrement PK?
1856
+		if ($model->has_primary_key_field()) {
1857
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1858
+				// ok check if it's set, if so: update; if not, insert
1859
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1860
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1861
+				} else {
1862
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1863
+					$results = $model->insert($save_cols_n_values);
1864
+					if ($results) {
1865
+						// if successful, set the primary key
1866
+						// but don't use the normal SET method, because it will check if
1867
+						// an item with the same ID exists in the mapper & db, then
1868
+						// will find it in the db (because we just added it) and THAT object
1869
+						// will get added to the mapper before we can add this one!
1870
+						// but if we just avoid using the SET method, all that headache can be avoided
1871
+						$pk_field_name = $model->primary_key_name();
1872
+						$this->_fields[ $pk_field_name ] = $results;
1873
+						$this->_clear_cached_property($pk_field_name);
1874
+						$model->add_to_entity_map($this);
1875
+						$this->_update_cached_related_model_objs_fks();
1876
+					}
1877
+				}
1878
+			} else {// PK is NOT auto-increment
1879
+				// so check if one like it already exists in the db
1880
+				if ($model->exists_by_ID($this->ID())) {
1881
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1882
+						throw new EE_Error(
1883
+							sprintf(
1884
+								esc_html__(
1885
+									'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',
1886
+									'event_espresso'
1887
+								),
1888
+								get_class($this),
1889
+								get_class($model) . '::instance()->add_to_entity_map()',
1890
+								get_class($model) . '::instance()->get_one_by_ID()',
1891
+								'<br />'
1892
+							)
1893
+						);
1894
+					}
1895
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1896
+				} else {
1897
+					$results = $model->insert($save_cols_n_values);
1898
+					$this->_update_cached_related_model_objs_fks();
1899
+				}
1900
+			}
1901
+		} else {// there is NO primary key
1902
+			$already_in_db = false;
1903
+			foreach ($model->unique_indexes() as $index) {
1904
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1905
+				if ($model->exists(array($uniqueness_where_params))) {
1906
+					$already_in_db = true;
1907
+				}
1908
+			}
1909
+			if ($already_in_db) {
1910
+				$combined_pk_fields_n_values = array_intersect_key(
1911
+					$save_cols_n_values,
1912
+					$model->get_combined_primary_key_fields()
1913
+				);
1914
+				$results = $model->update(
1915
+					$save_cols_n_values,
1916
+					$combined_pk_fields_n_values
1917
+				);
1918
+			} else {
1919
+				$results = $model->insert($save_cols_n_values);
1920
+			}
1921
+		}
1922
+		// restore the old assumption about values being prepared by the model object
1923
+		$model->assume_values_already_prepared_by_model_object(
1924
+			$old_assumption_concerning_value_preparation
1925
+		);
1926
+		/**
1927
+		 * After saving the model object this action is called
1928
+		 *
1929
+		 * @param EE_Base_Class $model_object which was just saved
1930
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1931
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1932
+		 */
1933
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1934
+		$this->_has_changes = false;
1935
+		return $results;
1936
+	}
1937
+
1938
+
1939
+	/**
1940
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1941
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1942
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1943
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1944
+	 * 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
1945
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1946
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1947
+	 *
1948
+	 * @return void
1949
+	 * @throws ReflectionException
1950
+	 * @throws InvalidArgumentException
1951
+	 * @throws InvalidInterfaceException
1952
+	 * @throws InvalidDataTypeException
1953
+	 * @throws EE_Error
1954
+	 */
1955
+	protected function _update_cached_related_model_objs_fks()
1956
+	{
1957
+		$model = $this->get_model();
1958
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1959
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1960
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1961
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1962
+						$model->get_this_model_name()
1963
+					);
1964
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1965
+					if ($related_model_obj_in_cache->ID()) {
1966
+						$related_model_obj_in_cache->save();
1967
+					}
1968
+				}
1969
+			}
1970
+		}
1971
+	}
1972
+
1973
+
1974
+	/**
1975
+	 * Saves this model object and its NEW cached relations to the database.
1976
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1977
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1978
+	 * because otherwise, there's a potential for infinite looping of saving
1979
+	 * Saves the cached related model objects, and ensures the relation between them
1980
+	 * and this object and properly setup
1981
+	 *
1982
+	 * @return int ID of new model object on save; 0 on failure+
1983
+	 * @throws ReflectionException
1984
+	 * @throws InvalidArgumentException
1985
+	 * @throws InvalidInterfaceException
1986
+	 * @throws InvalidDataTypeException
1987
+	 * @throws EE_Error
1988
+	 */
1989
+	public function save_new_cached_related_model_objs()
1990
+	{
1991
+		// make sure this has been saved
1992
+		if (! $this->ID()) {
1993
+			$id = $this->save();
1994
+		} else {
1995
+			$id = $this->ID();
1996
+		}
1997
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1998
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1999
+			if ($this->_model_relations[ $relationName ]) {
2000
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2001
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2002
+				/* @var $related_model_obj EE_Base_Class */
2003
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2004
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2005
+					// but ONLY if it DOES NOT exist in the DB
2006
+					$related_model_obj = $this->_model_relations[ $relationName ];
2007
+					// if( ! $related_model_obj->ID()){
2008
+					$this->_add_relation_to($related_model_obj, $relationName);
2009
+					$related_model_obj->save_new_cached_related_model_objs();
2010
+					// }
2011
+				} else {
2012
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2013
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2014
+						// but ONLY if it DOES NOT exist in the DB
2015
+						// if( ! $related_model_obj->ID()){
2016
+						$this->_add_relation_to($related_model_obj, $relationName);
2017
+						$related_model_obj->save_new_cached_related_model_objs();
2018
+						// }
2019
+					}
2020
+				}
2021
+			}
2022
+		}
2023
+		return $id;
2024
+	}
2025
+
2026
+
2027
+	/**
2028
+	 * for getting a model while instantiated.
2029
+	 *
2030
+	 * @return EEM_Base | EEM_CPT_Base
2031
+	 * @throws ReflectionException
2032
+	 * @throws InvalidArgumentException
2033
+	 * @throws InvalidInterfaceException
2034
+	 * @throws InvalidDataTypeException
2035
+	 * @throws EE_Error
2036
+	 */
2037
+	public function get_model()
2038
+	{
2039
+		if (! $this->_model) {
2040
+			$modelName = self::_get_model_classname(get_class($this));
2041
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2042
+		} else {
2043
+			$this->_model->set_timezone($this->_timezone);
2044
+		}
2045
+		return $this->_model;
2046
+	}
2047
+
2048
+
2049
+	/**
2050
+	 * @param $props_n_values
2051
+	 * @param $classname
2052
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2053
+	 * @throws ReflectionException
2054
+	 * @throws InvalidArgumentException
2055
+	 * @throws InvalidInterfaceException
2056
+	 * @throws InvalidDataTypeException
2057
+	 * @throws EE_Error
2058
+	 */
2059
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2060
+	{
2061
+		// TODO: will not work for Term_Relationships because they have no PK!
2062
+		$primary_id_ref = self::_get_primary_key_name($classname);
2063
+		if (
2064
+			array_key_exists($primary_id_ref, $props_n_values)
2065
+			&& ! empty($props_n_values[ $primary_id_ref ])
2066
+		) {
2067
+			$id = $props_n_values[ $primary_id_ref ];
2068
+			return self::_get_model($classname)->get_from_entity_map($id);
2069
+		}
2070
+		return false;
2071
+	}
2072
+
2073
+
2074
+	/**
2075
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2076
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2077
+	 * 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
2078
+	 * we return false.
2079
+	 *
2080
+	 * @param  array  $props_n_values   incoming array of properties and their values
2081
+	 * @param  string $classname        the classname of the child class
2082
+	 * @param null    $timezone
2083
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2084
+	 *                                  date_format and the second value is the time format
2085
+	 * @return mixed (EE_Base_Class|bool)
2086
+	 * @throws InvalidArgumentException
2087
+	 * @throws InvalidInterfaceException
2088
+	 * @throws InvalidDataTypeException
2089
+	 * @throws EE_Error
2090
+	 * @throws ReflectionException
2091
+	 * @throws ReflectionException
2092
+	 * @throws ReflectionException
2093
+	 */
2094
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2095
+	{
2096
+		$existing = null;
2097
+		$model = self::_get_model($classname, $timezone);
2098
+		if ($model->has_primary_key_field()) {
2099
+			$primary_id_ref = self::_get_primary_key_name($classname);
2100
+			if (
2101
+				array_key_exists($primary_id_ref, $props_n_values)
2102
+				&& ! empty($props_n_values[ $primary_id_ref ])
2103
+			) {
2104
+				$existing = $model->get_one_by_ID(
2105
+					$props_n_values[ $primary_id_ref ]
2106
+				);
2107
+			}
2108
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2109
+			// no primary key on this model, but there's still a matching item in the DB
2110
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2111
+				self::_get_model($classname, $timezone)
2112
+					->get_index_primary_key_string($props_n_values)
2113
+			);
2114
+		}
2115
+		if ($existing) {
2116
+			// set date formats if present before setting values
2117
+			if (! empty($date_formats) && is_array($date_formats)) {
2118
+				$existing->set_date_format($date_formats[0]);
2119
+				$existing->set_time_format($date_formats[1]);
2120
+			} else {
2121
+				// set default formats for date and time
2122
+				$existing->set_date_format(get_option('date_format'));
2123
+				$existing->set_time_format(get_option('time_format'));
2124
+			}
2125
+			foreach ($props_n_values as $property => $field_value) {
2126
+				$existing->set($property, $field_value);
2127
+			}
2128
+			return $existing;
2129
+		}
2130
+		return false;
2131
+	}
2132
+
2133
+
2134
+	/**
2135
+	 * Gets the EEM_*_Model for this class
2136
+	 *
2137
+	 * @access public now, as this is more convenient
2138
+	 * @param      $classname
2139
+	 * @param null $timezone
2140
+	 * @throws ReflectionException
2141
+	 * @throws InvalidArgumentException
2142
+	 * @throws InvalidInterfaceException
2143
+	 * @throws InvalidDataTypeException
2144
+	 * @throws EE_Error
2145
+	 * @return EEM_Base
2146
+	 */
2147
+	protected static function _get_model($classname, $timezone = null)
2148
+	{
2149
+		// find model for this class
2150
+		if (! $classname) {
2151
+			throw new EE_Error(
2152
+				sprintf(
2153
+					esc_html__(
2154
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2155
+						'event_espresso'
2156
+					),
2157
+					$classname
2158
+				)
2159
+			);
2160
+		}
2161
+		$modelName = self::_get_model_classname($classname);
2162
+		return self::_get_model_instance_with_name($modelName, $timezone);
2163
+	}
2164
+
2165
+
2166
+	/**
2167
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2168
+	 *
2169
+	 * @param string $model_classname
2170
+	 * @param null   $timezone
2171
+	 * @return EEM_Base
2172
+	 * @throws ReflectionException
2173
+	 * @throws InvalidArgumentException
2174
+	 * @throws InvalidInterfaceException
2175
+	 * @throws InvalidDataTypeException
2176
+	 * @throws EE_Error
2177
+	 */
2178
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2179
+	{
2180
+		$model_classname = str_replace('EEM_', '', $model_classname);
2181
+		$model = EE_Registry::instance()->load_model($model_classname);
2182
+		$model->set_timezone($timezone);
2183
+		return $model;
2184
+	}
2185
+
2186
+
2187
+	/**
2188
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2189
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2190
+	 *
2191
+	 * @param null $model_name
2192
+	 * @return string like EEM_Attendee
2193
+	 */
2194
+	private static function _get_model_classname($model_name = null)
2195
+	{
2196
+		if (strpos($model_name, 'EE_') === 0) {
2197
+			$model_classname = str_replace('EE_', 'EEM_', $model_name);
2198
+		} else {
2199
+			$model_classname = 'EEM_' . $model_name;
2200
+		}
2201
+		return $model_classname;
2202
+	}
2203
+
2204
+
2205
+	/**
2206
+	 * returns the name of the primary key attribute
2207
+	 *
2208
+	 * @param null $classname
2209
+	 * @throws ReflectionException
2210
+	 * @throws InvalidArgumentException
2211
+	 * @throws InvalidInterfaceException
2212
+	 * @throws InvalidDataTypeException
2213
+	 * @throws EE_Error
2214
+	 * @return string
2215
+	 */
2216
+	protected static function _get_primary_key_name($classname = null)
2217
+	{
2218
+		if (! $classname) {
2219
+			throw new EE_Error(
2220
+				sprintf(
2221
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2222
+					$classname
2223
+				)
2224
+			);
2225
+		}
2226
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2227
+	}
2228
+
2229
+
2230
+	/**
2231
+	 * Gets the value of the primary key.
2232
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2233
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2234
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2235
+	 *
2236
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2237
+	 * @throws ReflectionException
2238
+	 * @throws InvalidArgumentException
2239
+	 * @throws InvalidInterfaceException
2240
+	 * @throws InvalidDataTypeException
2241
+	 * @throws EE_Error
2242
+	 */
2243
+	public function ID()
2244
+	{
2245
+		$model = $this->get_model();
2246
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2247
+		if ($model->has_primary_key_field()) {
2248
+			return $this->_fields[ $model->primary_key_name() ];
2249
+		}
2250
+		return $model->get_index_primary_key_string($this->_fields);
2251
+	}
2252
+
2253
+
2254
+	/**
2255
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2256
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2257
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2258
+	 *
2259
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2260
+	 * @param string $relationName                     eg 'Events','Question',etc.
2261
+	 *                                                 an attendee to a group, you also want to specify which role they
2262
+	 *                                                 will have in that group. So you would use this parameter to
2263
+	 *                                                 specify array('role-column-name'=>'role-id')
2264
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2265
+	 *                                                 allow you to further constrict the relation to being added.
2266
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2267
+	 *                                                 column on the JOIN table and currently only the HABTM models
2268
+	 *                                                 accept these additional conditions.  Also remember that if an
2269
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2270
+	 *                                                 NEW row is created in the join table.
2271
+	 * @param null   $cache_id
2272
+	 * @throws ReflectionException
2273
+	 * @throws InvalidArgumentException
2274
+	 * @throws InvalidInterfaceException
2275
+	 * @throws InvalidDataTypeException
2276
+	 * @throws EE_Error
2277
+	 * @return EE_Base_Class the object the relation was added to
2278
+	 */
2279
+	public function _add_relation_to(
2280
+		$otherObjectModelObjectOrID,
2281
+		$relationName,
2282
+		$extra_join_model_fields_n_values = array(),
2283
+		$cache_id = null
2284
+	) {
2285
+		$model = $this->get_model();
2286
+		// if this thing exists in the DB, save the relation to the DB
2287
+		if ($this->ID()) {
2288
+			$otherObject = $model->add_relationship_to(
2289
+				$this,
2290
+				$otherObjectModelObjectOrID,
2291
+				$relationName,
2292
+				$extra_join_model_fields_n_values
2293
+			);
2294
+			// clear cache so future get_many_related and get_first_related() return new results.
2295
+			$this->clear_cache($relationName, $otherObject, true);
2296
+			if ($otherObject instanceof EE_Base_Class) {
2297
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2298
+			}
2299
+		} else {
2300
+			// this thing doesn't exist in the DB,  so just cache it
2301
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2302
+				throw new EE_Error(
2303
+					sprintf(
2304
+						esc_html__(
2305
+							'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',
2306
+							'event_espresso'
2307
+						),
2308
+						$otherObjectModelObjectOrID,
2309
+						get_class($this)
2310
+					)
2311
+				);
2312
+			}
2313
+			$otherObject = $otherObjectModelObjectOrID;
2314
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2315
+		}
2316
+		if ($otherObject instanceof EE_Base_Class) {
2317
+			// fix the reciprocal relation too
2318
+			if ($otherObject->ID()) {
2319
+				// its saved so assumed relations exist in the DB, so we can just
2320
+				// clear the cache so future queries use the updated info in the DB
2321
+				$otherObject->clear_cache(
2322
+					$model->get_this_model_name(),
2323
+					null,
2324
+					true
2325
+				);
2326
+			} else {
2327
+				// it's not saved, so it caches relations like this
2328
+				$otherObject->cache($model->get_this_model_name(), $this);
2329
+			}
2330
+		}
2331
+		return $otherObject;
2332
+	}
2333
+
2334
+
2335
+	/**
2336
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2337
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2338
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2339
+	 * from the cache
2340
+	 *
2341
+	 * @param mixed  $otherObjectModelObjectOrID
2342
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2343
+	 *                to the DB yet
2344
+	 * @param string $relationName
2345
+	 * @param array  $where_query
2346
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2347
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2348
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2349
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2350
+	 *                deleted.
2351
+	 * @return EE_Base_Class the relation was removed from
2352
+	 * @throws ReflectionException
2353
+	 * @throws InvalidArgumentException
2354
+	 * @throws InvalidInterfaceException
2355
+	 * @throws InvalidDataTypeException
2356
+	 * @throws EE_Error
2357
+	 */
2358
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2359
+	{
2360
+		if ($this->ID()) {
2361
+			// if this exists in the DB, save the relation change to the DB too
2362
+			$otherObject = $this->get_model()->remove_relationship_to(
2363
+				$this,
2364
+				$otherObjectModelObjectOrID,
2365
+				$relationName,
2366
+				$where_query
2367
+			);
2368
+			$this->clear_cache(
2369
+				$relationName,
2370
+				$otherObject
2371
+			);
2372
+		} else {
2373
+			// this doesn't exist in the DB, just remove it from the cache
2374
+			$otherObject = $this->clear_cache(
2375
+				$relationName,
2376
+				$otherObjectModelObjectOrID
2377
+			);
2378
+		}
2379
+		if ($otherObject instanceof EE_Base_Class) {
2380
+			$otherObject->clear_cache(
2381
+				$this->get_model()->get_this_model_name(),
2382
+				$this
2383
+			);
2384
+		}
2385
+		return $otherObject;
2386
+	}
2387
+
2388
+
2389
+	/**
2390
+	 * Removes ALL the related things for the $relationName.
2391
+	 *
2392
+	 * @param string $relationName
2393
+	 * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2394
+	 * @return EE_Base_Class
2395
+	 * @throws ReflectionException
2396
+	 * @throws InvalidArgumentException
2397
+	 * @throws InvalidInterfaceException
2398
+	 * @throws InvalidDataTypeException
2399
+	 * @throws EE_Error
2400
+	 */
2401
+	public function _remove_relations($relationName, $where_query_params = array())
2402
+	{
2403
+		if ($this->ID()) {
2404
+			// if this exists in the DB, save the relation change to the DB too
2405
+			$otherObjects = $this->get_model()->remove_relations(
2406
+				$this,
2407
+				$relationName,
2408
+				$where_query_params
2409
+			);
2410
+			$this->clear_cache(
2411
+				$relationName,
2412
+				null,
2413
+				true
2414
+			);
2415
+		} else {
2416
+			// this doesn't exist in the DB, just remove it from the cache
2417
+			$otherObjects = $this->clear_cache(
2418
+				$relationName,
2419
+				null,
2420
+				true
2421
+			);
2422
+		}
2423
+		if (is_array($otherObjects)) {
2424
+			foreach ($otherObjects as $otherObject) {
2425
+				$otherObject->clear_cache(
2426
+					$this->get_model()->get_this_model_name(),
2427
+					$this
2428
+				);
2429
+			}
2430
+		}
2431
+		return $otherObjects;
2432
+	}
2433
+
2434
+
2435
+	/**
2436
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2437
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2438
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2439
+	 * because we want to get even deleted items etc.
2440
+	 *
2441
+	 * @param string $relationName key in the model's _model_relations array
2442
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2443
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2444
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2445
+	 *                             results if you want IDs
2446
+	 * @throws ReflectionException
2447
+	 * @throws InvalidArgumentException
2448
+	 * @throws InvalidInterfaceException
2449
+	 * @throws InvalidDataTypeException
2450
+	 * @throws EE_Error
2451
+	 */
2452
+	public function get_many_related($relationName, $query_params = array())
2453
+	{
2454
+		if ($this->ID()) {
2455
+			// this exists in the DB, so get the related things from either the cache or the DB
2456
+			// if there are query parameters, forget about caching the related model objects.
2457
+			if ($query_params) {
2458
+				$related_model_objects = $this->get_model()->get_all_related(
2459
+					$this,
2460
+					$relationName,
2461
+					$query_params
2462
+				);
2463
+			} else {
2464
+				// did we already cache the result of this query?
2465
+				$cached_results = $this->get_all_from_cache($relationName);
2466
+				if (! $cached_results) {
2467
+					$related_model_objects = $this->get_model()->get_all_related(
2468
+						$this,
2469
+						$relationName,
2470
+						$query_params
2471
+					);
2472
+					// if no query parameters were passed, then we got all the related model objects
2473
+					// for that relation. We can cache them then.
2474
+					foreach ($related_model_objects as $related_model_object) {
2475
+						$this->cache($relationName, $related_model_object);
2476
+					}
2477
+				} else {
2478
+					$related_model_objects = $cached_results;
2479
+				}
2480
+			}
2481
+		} else {
2482
+			// this doesn't exist in the DB, so just get the related things from the cache
2483
+			$related_model_objects = $this->get_all_from_cache($relationName);
2484
+		}
2485
+		return $related_model_objects;
2486
+	}
2487
+
2488
+
2489
+	/**
2490
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2491
+	 * unless otherwise specified in the $query_params
2492
+	 *
2493
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2494
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2495
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2496
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2497
+	 *                               that by the setting $distinct to TRUE;
2498
+	 * @return int
2499
+	 * @throws ReflectionException
2500
+	 * @throws InvalidArgumentException
2501
+	 * @throws InvalidInterfaceException
2502
+	 * @throws InvalidDataTypeException
2503
+	 * @throws EE_Error
2504
+	 */
2505
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2506
+	{
2507
+		return $this->get_model()->count_related(
2508
+			$this,
2509
+			$relation_name,
2510
+			$query_params,
2511
+			$field_to_count,
2512
+			$distinct
2513
+		);
2514
+	}
2515
+
2516
+
2517
+	/**
2518
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2519
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2520
+	 *
2521
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2522
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2523
+	 * @param string $field_to_sum  name of field to count by.
2524
+	 *                              By default, uses primary key
2525
+	 *                              (which doesn't make much sense, so you should probably change it)
2526
+	 * @return int
2527
+	 * @throws ReflectionException
2528
+	 * @throws InvalidArgumentException
2529
+	 * @throws InvalidInterfaceException
2530
+	 * @throws InvalidDataTypeException
2531
+	 * @throws EE_Error
2532
+	 */
2533
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2534
+	{
2535
+		return $this->get_model()->sum_related(
2536
+			$this,
2537
+			$relation_name,
2538
+			$query_params,
2539
+			$field_to_sum
2540
+		);
2541
+	}
2542
+
2543
+
2544
+	/**
2545
+	 * Gets the first (ie, one) related model object of the specified type.
2546
+	 *
2547
+	 * @param string $relationName key in the model's _model_relations array
2548
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2549
+	 * @return EE_Base_Class (not an array, a single object)
2550
+	 * @throws ReflectionException
2551
+	 * @throws InvalidArgumentException
2552
+	 * @throws InvalidInterfaceException
2553
+	 * @throws InvalidDataTypeException
2554
+	 * @throws EE_Error
2555
+	 */
2556
+	public function get_first_related($relationName, $query_params = array())
2557
+	{
2558
+		$model = $this->get_model();
2559
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2560
+			// if they've provided some query parameters, don't bother trying to cache the result
2561
+			// also make sure we're not caching the result of get_first_related
2562
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2563
+			if (
2564
+				$query_params
2565
+				|| ! $model->related_settings_for($relationName)
2566
+					 instanceof
2567
+					 EE_Belongs_To_Relation
2568
+			) {
2569
+				$related_model_object = $model->get_first_related(
2570
+					$this,
2571
+					$relationName,
2572
+					$query_params
2573
+				);
2574
+			} else {
2575
+				// first, check if we've already cached the result of this query
2576
+				$cached_result = $this->get_one_from_cache($relationName);
2577
+				if (! $cached_result) {
2578
+					$related_model_object = $model->get_first_related(
2579
+						$this,
2580
+						$relationName,
2581
+						$query_params
2582
+					);
2583
+					$this->cache($relationName, $related_model_object);
2584
+				} else {
2585
+					$related_model_object = $cached_result;
2586
+				}
2587
+			}
2588
+		} else {
2589
+			$related_model_object = null;
2590
+			// this doesn't exist in the Db,
2591
+			// but maybe the relation is of type belongs to, and so the related thing might
2592
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2593
+				$related_model_object = $model->get_first_related(
2594
+					$this,
2595
+					$relationName,
2596
+					$query_params
2597
+				);
2598
+			}
2599
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2600
+			// just get what's cached on this object
2601
+			if (! $related_model_object) {
2602
+				$related_model_object = $this->get_one_from_cache($relationName);
2603
+			}
2604
+		}
2605
+		return $related_model_object;
2606
+	}
2607
+
2608
+
2609
+	/**
2610
+	 * Does a delete on all related objects of type $relationName and removes
2611
+	 * the current model object's relation to them. If they can't be deleted (because
2612
+	 * of blocking related model objects) does nothing. If the related model objects are
2613
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2614
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2615
+	 *
2616
+	 * @param string $relationName
2617
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2618
+	 * @return int how many deleted
2619
+	 * @throws ReflectionException
2620
+	 * @throws InvalidArgumentException
2621
+	 * @throws InvalidInterfaceException
2622
+	 * @throws InvalidDataTypeException
2623
+	 * @throws EE_Error
2624
+	 */
2625
+	public function delete_related($relationName, $query_params = array())
2626
+	{
2627
+		if ($this->ID()) {
2628
+			$count = $this->get_model()->delete_related(
2629
+				$this,
2630
+				$relationName,
2631
+				$query_params
2632
+			);
2633
+		} else {
2634
+			$count = count($this->get_all_from_cache($relationName));
2635
+			$this->clear_cache($relationName, null, true);
2636
+		}
2637
+		return $count;
2638
+	}
2639
+
2640
+
2641
+	/**
2642
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2643
+	 * the current model object's relation to them. If they can't be deleted (because
2644
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2645
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2646
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2647
+	 *
2648
+	 * @param string $relationName
2649
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2650
+	 * @return int how many deleted (including those soft deleted)
2651
+	 * @throws ReflectionException
2652
+	 * @throws InvalidArgumentException
2653
+	 * @throws InvalidInterfaceException
2654
+	 * @throws InvalidDataTypeException
2655
+	 * @throws EE_Error
2656
+	 */
2657
+	public function delete_related_permanently($relationName, $query_params = array())
2658
+	{
2659
+		if ($this->ID()) {
2660
+			$count = $this->get_model()->delete_related_permanently(
2661
+				$this,
2662
+				$relationName,
2663
+				$query_params
2664
+			);
2665
+		} else {
2666
+			$count = count($this->get_all_from_cache($relationName));
2667
+		}
2668
+		$this->clear_cache($relationName, null, true);
2669
+		return $count;
2670
+	}
2671
+
2672
+
2673
+	/**
2674
+	 * is_set
2675
+	 * Just a simple utility function children can use for checking if property exists
2676
+	 *
2677
+	 * @access  public
2678
+	 * @param  string $field_name property to check
2679
+	 * @return bool                              TRUE if existing,FALSE if not.
2680
+	 */
2681
+	public function is_set($field_name)
2682
+	{
2683
+		return isset($this->_fields[ $field_name ]);
2684
+	}
2685
+
2686
+
2687
+	/**
2688
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2689
+	 * EE_Error exception if they don't
2690
+	 *
2691
+	 * @param  mixed (string|array) $properties properties to check
2692
+	 * @throws EE_Error
2693
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2694
+	 */
2695
+	protected function _property_exists($properties)
2696
+	{
2697
+		foreach ((array) $properties as $property_name) {
2698
+			// first make sure this property exists
2699
+			if (! $this->_fields[ $property_name ]) {
2700
+				throw new EE_Error(
2701
+					sprintf(
2702
+						esc_html__(
2703
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2704
+							'event_espresso'
2705
+						),
2706
+						$property_name
2707
+					)
2708
+				);
2709
+			}
2710
+		}
2711
+		return true;
2712
+	}
2713
+
2714
+
2715
+	/**
2716
+	 * This simply returns an array of model fields for this object
2717
+	 *
2718
+	 * @return array
2719
+	 * @throws ReflectionException
2720
+	 * @throws InvalidArgumentException
2721
+	 * @throws InvalidInterfaceException
2722
+	 * @throws InvalidDataTypeException
2723
+	 * @throws EE_Error
2724
+	 */
2725
+	public function model_field_array()
2726
+	{
2727
+		$fields = $this->get_model()->field_settings(false);
2728
+		$properties = array();
2729
+		// remove prepended underscore
2730
+		foreach ($fields as $field_name => $settings) {
2731
+			$properties[ $field_name ] = $this->get($field_name);
2732
+		}
2733
+		return $properties;
2734
+	}
2735
+
2736
+
2737
+	/**
2738
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2739
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2740
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2741
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2742
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2743
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2744
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2745
+	 * and accepts 2 arguments: the object on which the function was called,
2746
+	 * and an array of the original arguments passed to the function.
2747
+	 * Whatever their callback function returns will be returned by this function.
2748
+	 *
2749
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2750
+	 * @param array  $args       array of original arguments passed to the function
2751
+	 * @throws EE_Error
2752
+	 * @return mixed whatever the plugin which calls add_filter decides
2753
+	 */
2754
+	public function __call($methodName, $args)
2755
+	{
2756
+		$className = get_class($this);
2757
+		$tagName = "FHEE__{$className}__{$methodName}";
2758
+		if (! has_filter($tagName)) {
2759
+			throw new EE_Error(
2760
+				sprintf(
2761
+					esc_html__(
2762
+						"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;}",
2763
+						'event_espresso'
2764
+					),
2765
+					$methodName,
2766
+					$className,
2767
+					$tagName
2768
+				)
2769
+			);
2770
+		}
2771
+		return apply_filters($tagName, null, $this, $args);
2772
+	}
2773
+
2774
+
2775
+	/**
2776
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2777
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2778
+	 *
2779
+	 * @param string $meta_key
2780
+	 * @param mixed  $meta_value
2781
+	 * @param mixed  $previous_value
2782
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2783
+	 *                  NOTE: if the values haven't changed, returns 0
2784
+	 * @throws InvalidArgumentException
2785
+	 * @throws InvalidInterfaceException
2786
+	 * @throws InvalidDataTypeException
2787
+	 * @throws EE_Error
2788
+	 * @throws ReflectionException
2789
+	 */
2790
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2791
+	{
2792
+		$query_params = array(
2793
+			array(
2794
+				'EXM_key'  => $meta_key,
2795
+				'OBJ_ID'   => $this->ID(),
2796
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2797
+			),
2798
+		);
2799
+		if ($previous_value !== null) {
2800
+			$query_params[0]['EXM_value'] = $meta_value;
2801
+		}
2802
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2803
+		if (! $existing_rows_like_that) {
2804
+			return $this->add_extra_meta($meta_key, $meta_value);
2805
+		}
2806
+		foreach ($existing_rows_like_that as $existing_row) {
2807
+			$existing_row->save(array('EXM_value' => $meta_value));
2808
+		}
2809
+		return count($existing_rows_like_that);
2810
+	}
2811
+
2812
+
2813
+	/**
2814
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2815
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2816
+	 * extra meta row was entered, false if not
2817
+	 *
2818
+	 * @param string  $meta_key
2819
+	 * @param mixed   $meta_value
2820
+	 * @param boolean $unique
2821
+	 * @return boolean
2822
+	 * @throws InvalidArgumentException
2823
+	 * @throws InvalidInterfaceException
2824
+	 * @throws InvalidDataTypeException
2825
+	 * @throws EE_Error
2826
+	 * @throws ReflectionException
2827
+	 * @throws ReflectionException
2828
+	 */
2829
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2830
+	{
2831
+		if ($unique) {
2832
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2833
+				array(
2834
+					array(
2835
+						'EXM_key'  => $meta_key,
2836
+						'OBJ_ID'   => $this->ID(),
2837
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2838
+					),
2839
+				)
2840
+			);
2841
+			if ($existing_extra_meta) {
2842
+				return false;
2843
+			}
2844
+		}
2845
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2846
+			array(
2847
+				'EXM_key'   => $meta_key,
2848
+				'EXM_value' => $meta_value,
2849
+				'OBJ_ID'    => $this->ID(),
2850
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2851
+			)
2852
+		);
2853
+		$new_extra_meta->save();
2854
+		return true;
2855
+	}
2856
+
2857
+
2858
+	/**
2859
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2860
+	 * is specified, only deletes extra meta records with that value.
2861
+	 *
2862
+	 * @param string $meta_key
2863
+	 * @param mixed  $meta_value
2864
+	 * @return int number of extra meta rows deleted
2865
+	 * @throws InvalidArgumentException
2866
+	 * @throws InvalidInterfaceException
2867
+	 * @throws InvalidDataTypeException
2868
+	 * @throws EE_Error
2869
+	 * @throws ReflectionException
2870
+	 */
2871
+	public function delete_extra_meta($meta_key, $meta_value = null)
2872
+	{
2873
+		$query_params = array(
2874
+			array(
2875
+				'EXM_key'  => $meta_key,
2876
+				'OBJ_ID'   => $this->ID(),
2877
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2878
+			),
2879
+		);
2880
+		if ($meta_value !== null) {
2881
+			$query_params[0]['EXM_value'] = $meta_value;
2882
+		}
2883
+		return EEM_Extra_Meta::instance()->delete($query_params);
2884
+	}
2885
+
2886
+
2887
+	/**
2888
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2889
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2890
+	 * You can specify $default is case you haven't found the extra meta
2891
+	 *
2892
+	 * @param string  $meta_key
2893
+	 * @param boolean $single
2894
+	 * @param mixed   $default if we don't find anything, what should we return?
2895
+	 * @return mixed single value if $single; array if ! $single
2896
+	 * @throws ReflectionException
2897
+	 * @throws InvalidArgumentException
2898
+	 * @throws InvalidInterfaceException
2899
+	 * @throws InvalidDataTypeException
2900
+	 * @throws EE_Error
2901
+	 */
2902
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2903
+	{
2904
+		if ($single) {
2905
+			$result = $this->get_first_related(
2906
+				'Extra_Meta',
2907
+				array(array('EXM_key' => $meta_key))
2908
+			);
2909
+			if ($result instanceof EE_Extra_Meta) {
2910
+				return $result->value();
2911
+			}
2912
+		} else {
2913
+			$results = $this->get_many_related(
2914
+				'Extra_Meta',
2915
+				array(array('EXM_key' => $meta_key))
2916
+			);
2917
+			if ($results) {
2918
+				$values = array();
2919
+				foreach ($results as $result) {
2920
+					if ($result instanceof EE_Extra_Meta) {
2921
+						$values[ $result->ID() ] = $result->value();
2922
+					}
2923
+				}
2924
+				return $values;
2925
+			}
2926
+		}
2927
+		// if nothing discovered yet return default.
2928
+		return apply_filters(
2929
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2930
+			$default,
2931
+			$meta_key,
2932
+			$single,
2933
+			$this
2934
+		);
2935
+	}
2936
+
2937
+
2938
+	/**
2939
+	 * Returns a simple array of all the extra meta associated with this model object.
2940
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2941
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2942
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2943
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2944
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2945
+	 * finally the extra meta's value as each sub-value. (eg
2946
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2947
+	 *
2948
+	 * @param boolean $one_of_each_key
2949
+	 * @return array
2950
+	 * @throws ReflectionException
2951
+	 * @throws InvalidArgumentException
2952
+	 * @throws InvalidInterfaceException
2953
+	 * @throws InvalidDataTypeException
2954
+	 * @throws EE_Error
2955
+	 */
2956
+	public function all_extra_meta_array($one_of_each_key = true)
2957
+	{
2958
+		$return_array = array();
2959
+		if ($one_of_each_key) {
2960
+			$extra_meta_objs = $this->get_many_related(
2961
+				'Extra_Meta',
2962
+				array('group_by' => 'EXM_key')
2963
+			);
2964
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2965
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2966
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2967
+				}
2968
+			}
2969
+		} else {
2970
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2971
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2972
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2973
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2974
+						$return_array[ $extra_meta_obj->key() ] = array();
2975
+					}
2976
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2977
+				}
2978
+			}
2979
+		}
2980
+		return $return_array;
2981
+	}
2982
+
2983
+
2984
+	/**
2985
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2986
+	 *
2987
+	 * @return string
2988
+	 * @throws ReflectionException
2989
+	 * @throws InvalidArgumentException
2990
+	 * @throws InvalidInterfaceException
2991
+	 * @throws InvalidDataTypeException
2992
+	 * @throws EE_Error
2993
+	 */
2994
+	public function name()
2995
+	{
2996
+		// find a field that's not a text field
2997
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2998
+		if ($field_we_can_use) {
2999
+			return $this->get($field_we_can_use->get_name());
3000
+		}
3001
+		$first_few_properties = $this->model_field_array();
3002
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3003
+		$name_parts = array();
3004
+		foreach ($first_few_properties as $name => $value) {
3005
+			$name_parts[] = "$name:$value";
3006
+		}
3007
+		return implode(',', $name_parts);
3008
+	}
3009
+
3010
+
3011
+	/**
3012
+	 * in_entity_map
3013
+	 * Checks if this model object has been proven to already be in the entity map
3014
+	 *
3015
+	 * @return boolean
3016
+	 * @throws ReflectionException
3017
+	 * @throws InvalidArgumentException
3018
+	 * @throws InvalidInterfaceException
3019
+	 * @throws InvalidDataTypeException
3020
+	 * @throws EE_Error
3021
+	 */
3022
+	public function in_entity_map()
3023
+	{
3024
+		// well, if we looked, did we find it in the entity map?
3025
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3026
+	}
3027
+
3028
+
3029
+	/**
3030
+	 * refresh_from_db
3031
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3032
+	 *
3033
+	 * @throws ReflectionException
3034
+	 * @throws InvalidArgumentException
3035
+	 * @throws InvalidInterfaceException
3036
+	 * @throws InvalidDataTypeException
3037
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3038
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3039
+	 */
3040
+	public function refresh_from_db()
3041
+	{
3042
+		if ($this->ID() && $this->in_entity_map()) {
3043
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3044
+		} else {
3045
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3046
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3047
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3048
+			// absolutely nothing in it for this ID
3049
+			if (WP_DEBUG) {
3050
+				throw new EE_Error(
3051
+					sprintf(
3052
+						esc_html__(
3053
+							'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.',
3054
+							'event_espresso'
3055
+						),
3056
+						$this->ID(),
3057
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3058
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3059
+					)
3060
+				);
3061
+			}
3062
+		}
3063
+	}
3064
+
3065
+
3066
+	/**
3067
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3068
+	 *
3069
+	 * @since 4.9.80.p
3070
+	 * @param EE_Model_Field_Base[] $fields
3071
+	 * @param string $new_value_sql
3072
+	 *      example: 'column_name=123',
3073
+	 *      or 'column_name=column_name+1',
3074
+	 *      or 'column_name= CASE
3075
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3076
+	 *          THEN `column_name` + 5
3077
+	 *          ELSE `column_name`
3078
+	 *      END'
3079
+	 *      Also updates $field on this model object with the latest value from the database.
3080
+	 * @return bool
3081
+	 * @throws EE_Error
3082
+	 * @throws InvalidArgumentException
3083
+	 * @throws InvalidDataTypeException
3084
+	 * @throws InvalidInterfaceException
3085
+	 * @throws ReflectionException
3086
+	 */
3087
+	protected function updateFieldsInDB($fields, $new_value_sql)
3088
+	{
3089
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3090
+		// if it wasn't even there to start off.
3091
+		if (! $this->ID()) {
3092
+			$this->save();
3093
+		}
3094
+		global $wpdb;
3095
+		if (empty($fields)) {
3096
+			throw new InvalidArgumentException(
3097
+				esc_html__(
3098
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3099
+					'event_espresso'
3100
+				)
3101
+			);
3102
+		}
3103
+		$first_field = reset($fields);
3104
+		$table_alias = $first_field->get_table_alias();
3105
+		foreach ($fields as $field) {
3106
+			if ($table_alias !== $field->get_table_alias()) {
3107
+				throw new InvalidArgumentException(
3108
+					sprintf(
3109
+						esc_html__(
3110
+							// @codingStandardsIgnoreStart
3111
+							'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.',
3112
+							// @codingStandardsIgnoreEnd
3113
+							'event_espresso'
3114
+						),
3115
+						$table_alias,
3116
+						$field->get_table_alias()
3117
+					)
3118
+				);
3119
+			}
3120
+		}
3121
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3122
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3123
+		$table_pk_value = $this->ID();
3124
+		$table_name = $table_obj->get_table_name();
3125
+		if ($table_obj instanceof EE_Secondary_Table) {
3126
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3127
+		} else {
3128
+			$table_pk_field_name = $table_obj->get_pk_column();
3129
+		}
3130
+
3131
+		$query =
3132
+			"UPDATE `{$table_name}`
3133 3133
             SET "
3134
-            . $new_value_sql
3135
-            . $wpdb->prepare(
3136
-                "
3134
+			. $new_value_sql
3135
+			. $wpdb->prepare(
3136
+				"
3137 3137
             WHERE `{$table_pk_field_name}` = %d;",
3138
-                $table_pk_value
3139
-            );
3140
-        $result = $wpdb->query($query);
3141
-        foreach ($fields as $field) {
3142
-            // If it was successful, we'd like to know the new value.
3143
-            // If it failed, we'd also like to know the new value.
3144
-            $new_value = $this->get_model()->get_var(
3145
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3146
-                    $this->get_model()->get_index_primary_key_string(
3147
-                        $this->model_field_array()
3148
-                    ),
3149
-                    array(
3150
-                        'default_where_conditions' => 'minimum',
3151
-                    )
3152
-                ),
3153
-                $field->get_name()
3154
-            );
3155
-            $this->set_from_db(
3156
-                $field->get_name(),
3157
-                $new_value
3158
-            );
3159
-        }
3160
-        return (bool) $result;
3161
-    }
3162
-
3163
-
3164
-    /**
3165
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3166
-     * Does not allow negative values, however.
3167
-     *
3168
-     * @since 4.9.80.p
3169
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3170
-     *                                   (positive or negative). One important gotcha: all these values must be
3171
-     *                                   on the same table (eg don't pass in one field for the posts table and
3172
-     *                                   another for the event meta table.)
3173
-     * @return bool
3174
-     * @throws EE_Error
3175
-     * @throws InvalidArgumentException
3176
-     * @throws InvalidDataTypeException
3177
-     * @throws InvalidInterfaceException
3178
-     * @throws ReflectionException
3179
-     */
3180
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3181
-    {
3182
-        global $wpdb;
3183
-        if (empty($fields_n_quantities)) {
3184
-            // No fields to update? Well sure, we updated them to that value just fine.
3185
-            return true;
3186
-        }
3187
-        $fields = [];
3188
-        $set_sql_statements = [];
3189
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3190
-            $field = $this->get_model()->field_settings_for($field_name, true);
3191
-            $fields[] = $field;
3192
-            $column_name = $field->get_table_column();
3193
-
3194
-            $abs_qty = absint($quantity);
3195
-            if ($quantity > 0) {
3196
-                // don't let the value be negative as often these fields are unsigned
3197
-                $set_sql_statements[] = $wpdb->prepare(
3198
-                    "`{$column_name}` = `{$column_name}` + %d",
3199
-                    $abs_qty
3200
-                );
3201
-            } else {
3202
-                $set_sql_statements[] = $wpdb->prepare(
3203
-                    "`{$column_name}` = CASE
3138
+				$table_pk_value
3139
+			);
3140
+		$result = $wpdb->query($query);
3141
+		foreach ($fields as $field) {
3142
+			// If it was successful, we'd like to know the new value.
3143
+			// If it failed, we'd also like to know the new value.
3144
+			$new_value = $this->get_model()->get_var(
3145
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3146
+					$this->get_model()->get_index_primary_key_string(
3147
+						$this->model_field_array()
3148
+					),
3149
+					array(
3150
+						'default_where_conditions' => 'minimum',
3151
+					)
3152
+				),
3153
+				$field->get_name()
3154
+			);
3155
+			$this->set_from_db(
3156
+				$field->get_name(),
3157
+				$new_value
3158
+			);
3159
+		}
3160
+		return (bool) $result;
3161
+	}
3162
+
3163
+
3164
+	/**
3165
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3166
+	 * Does not allow negative values, however.
3167
+	 *
3168
+	 * @since 4.9.80.p
3169
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3170
+	 *                                   (positive or negative). One important gotcha: all these values must be
3171
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3172
+	 *                                   another for the event meta table.)
3173
+	 * @return bool
3174
+	 * @throws EE_Error
3175
+	 * @throws InvalidArgumentException
3176
+	 * @throws InvalidDataTypeException
3177
+	 * @throws InvalidInterfaceException
3178
+	 * @throws ReflectionException
3179
+	 */
3180
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3181
+	{
3182
+		global $wpdb;
3183
+		if (empty($fields_n_quantities)) {
3184
+			// No fields to update? Well sure, we updated them to that value just fine.
3185
+			return true;
3186
+		}
3187
+		$fields = [];
3188
+		$set_sql_statements = [];
3189
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3190
+			$field = $this->get_model()->field_settings_for($field_name, true);
3191
+			$fields[] = $field;
3192
+			$column_name = $field->get_table_column();
3193
+
3194
+			$abs_qty = absint($quantity);
3195
+			if ($quantity > 0) {
3196
+				// don't let the value be negative as often these fields are unsigned
3197
+				$set_sql_statements[] = $wpdb->prepare(
3198
+					"`{$column_name}` = `{$column_name}` + %d",
3199
+					$abs_qty
3200
+				);
3201
+			} else {
3202
+				$set_sql_statements[] = $wpdb->prepare(
3203
+					"`{$column_name}` = CASE
3204 3204
                        WHEN (`{$column_name}` >= %d)
3205 3205
                        THEN `{$column_name}` - %d
3206 3206
                        ELSE 0
3207 3207
                     END",
3208
-                    $abs_qty,
3209
-                    $abs_qty
3210
-                );
3211
-            }
3212
-        }
3213
-        return $this->updateFieldsInDB(
3214
-            $fields,
3215
-            implode(', ', $set_sql_statements)
3216
-        );
3217
-    }
3218
-
3219
-
3220
-    /**
3221
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3222
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3223
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3224
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3225
-     * Otherwise returns false.
3226
-     *
3227
-     * @since 4.9.80.p
3228
-     * @param string $field_name_to_bump
3229
-     * @param string $field_name_affecting_total
3230
-     * @param string $limit_field_name
3231
-     * @param int    $quantity
3232
-     * @return bool
3233
-     * @throws EE_Error
3234
-     * @throws InvalidArgumentException
3235
-     * @throws InvalidDataTypeException
3236
-     * @throws InvalidInterfaceException
3237
-     * @throws ReflectionException
3238
-     */
3239
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3240
-    {
3241
-        global $wpdb;
3242
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3243
-        $column_name = $field->get_table_column();
3244
-
3245
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3246
-        $column_affecting_total = $field_affecting_total->get_table_column();
3247
-
3248
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3249
-        $limiting_column = $limiting_field->get_table_column();
3250
-        return $this->updateFieldsInDB(
3251
-            [$field],
3252
-            $wpdb->prepare(
3253
-                "`{$column_name}` =
3208
+					$abs_qty,
3209
+					$abs_qty
3210
+				);
3211
+			}
3212
+		}
3213
+		return $this->updateFieldsInDB(
3214
+			$fields,
3215
+			implode(', ', $set_sql_statements)
3216
+		);
3217
+	}
3218
+
3219
+
3220
+	/**
3221
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3222
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3223
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3224
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3225
+	 * Otherwise returns false.
3226
+	 *
3227
+	 * @since 4.9.80.p
3228
+	 * @param string $field_name_to_bump
3229
+	 * @param string $field_name_affecting_total
3230
+	 * @param string $limit_field_name
3231
+	 * @param int    $quantity
3232
+	 * @return bool
3233
+	 * @throws EE_Error
3234
+	 * @throws InvalidArgumentException
3235
+	 * @throws InvalidDataTypeException
3236
+	 * @throws InvalidInterfaceException
3237
+	 * @throws ReflectionException
3238
+	 */
3239
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3240
+	{
3241
+		global $wpdb;
3242
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3243
+		$column_name = $field->get_table_column();
3244
+
3245
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3246
+		$column_affecting_total = $field_affecting_total->get_table_column();
3247
+
3248
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3249
+		$limiting_column = $limiting_field->get_table_column();
3250
+		return $this->updateFieldsInDB(
3251
+			[$field],
3252
+			$wpdb->prepare(
3253
+				"`{$column_name}` =
3254 3254
             CASE
3255 3255
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3256 3256
                THEN `{$column_name}` + %d
3257 3257
                ELSE `{$column_name}`
3258 3258
             END",
3259
-                $quantity,
3260
-                EE_INF_IN_DB,
3261
-                $quantity
3262
-            )
3263
-        );
3264
-    }
3265
-
3266
-
3267
-    /**
3268
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3269
-     * (probably a bad assumption they have made, oh well)
3270
-     *
3271
-     * @return string
3272
-     */
3273
-    public function __toString()
3274
-    {
3275
-        try {
3276
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3277
-        } catch (Exception $e) {
3278
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3279
-            return '';
3280
-        }
3281
-    }
3282
-
3283
-
3284
-    /**
3285
-     * Clear related model objects if they're already in the DB, because otherwise when we
3286
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3287
-     * This means if we have made changes to those related model objects, and want to unserialize
3288
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3289
-     * Instead, those related model objects should be directly serialized and stored.
3290
-     * Eg, the following won't work:
3291
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3292
-     * $att = $reg->attendee();
3293
-     * $att->set( 'ATT_fname', 'Dirk' );
3294
-     * update_option( 'my_option', serialize( $reg ) );
3295
-     * //END REQUEST
3296
-     * //START NEXT REQUEST
3297
-     * $reg = get_option( 'my_option' );
3298
-     * $reg->attendee()->save();
3299
-     * And would need to be replace with:
3300
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3301
-     * $att = $reg->attendee();
3302
-     * $att->set( 'ATT_fname', 'Dirk' );
3303
-     * update_option( 'my_option', serialize( $reg ) );
3304
-     * //END REQUEST
3305
-     * //START NEXT REQUEST
3306
-     * $att = get_option( 'my_option' );
3307
-     * $att->save();
3308
-     *
3309
-     * @return array
3310
-     * @throws ReflectionException
3311
-     * @throws InvalidArgumentException
3312
-     * @throws InvalidInterfaceException
3313
-     * @throws InvalidDataTypeException
3314
-     * @throws EE_Error
3315
-     */
3316
-    public function __sleep()
3317
-    {
3318
-        $model = $this->get_model();
3319
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3320
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3321
-                $classname = 'EE_' . $model->get_this_model_name();
3322
-                if (
3323
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3324
-                    && $this->get_one_from_cache($relation_name)->ID()
3325
-                ) {
3326
-                    $this->clear_cache(
3327
-                        $relation_name,
3328
-                        $this->get_one_from_cache($relation_name)->ID()
3329
-                    );
3330
-                }
3331
-            }
3332
-        }
3333
-        $this->_props_n_values_provided_in_constructor = array();
3334
-        $properties_to_serialize = get_object_vars($this);
3335
-        // don't serialize the model. It's big and that risks recursion
3336
-        unset($properties_to_serialize['_model']);
3337
-        return array_keys($properties_to_serialize);
3338
-    }
3339
-
3340
-
3341
-    /**
3342
-     * restore _props_n_values_provided_in_constructor
3343
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3344
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3345
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3346
-     */
3347
-    public function __wakeup()
3348
-    {
3349
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3350
-    }
3351
-
3352
-
3353
-    /**
3354
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3355
-     * distinct with the clone host instance are also cloned.
3356
-     */
3357
-    public function __clone()
3358
-    {
3359
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3360
-        foreach ($this->_fields as $field => $value) {
3361
-            if ($value instanceof DateTime) {
3362
-                $this->_fields[ $field ] = clone $value;
3363
-            }
3364
-        }
3365
-    }
3259
+				$quantity,
3260
+				EE_INF_IN_DB,
3261
+				$quantity
3262
+			)
3263
+		);
3264
+	}
3265
+
3266
+
3267
+	/**
3268
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3269
+	 * (probably a bad assumption they have made, oh well)
3270
+	 *
3271
+	 * @return string
3272
+	 */
3273
+	public function __toString()
3274
+	{
3275
+		try {
3276
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3277
+		} catch (Exception $e) {
3278
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3279
+			return '';
3280
+		}
3281
+	}
3282
+
3283
+
3284
+	/**
3285
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3286
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3287
+	 * This means if we have made changes to those related model objects, and want to unserialize
3288
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3289
+	 * Instead, those related model objects should be directly serialized and stored.
3290
+	 * Eg, the following won't work:
3291
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3292
+	 * $att = $reg->attendee();
3293
+	 * $att->set( 'ATT_fname', 'Dirk' );
3294
+	 * update_option( 'my_option', serialize( $reg ) );
3295
+	 * //END REQUEST
3296
+	 * //START NEXT REQUEST
3297
+	 * $reg = get_option( 'my_option' );
3298
+	 * $reg->attendee()->save();
3299
+	 * And would need to be replace with:
3300
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3301
+	 * $att = $reg->attendee();
3302
+	 * $att->set( 'ATT_fname', 'Dirk' );
3303
+	 * update_option( 'my_option', serialize( $reg ) );
3304
+	 * //END REQUEST
3305
+	 * //START NEXT REQUEST
3306
+	 * $att = get_option( 'my_option' );
3307
+	 * $att->save();
3308
+	 *
3309
+	 * @return array
3310
+	 * @throws ReflectionException
3311
+	 * @throws InvalidArgumentException
3312
+	 * @throws InvalidInterfaceException
3313
+	 * @throws InvalidDataTypeException
3314
+	 * @throws EE_Error
3315
+	 */
3316
+	public function __sleep()
3317
+	{
3318
+		$model = $this->get_model();
3319
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3320
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3321
+				$classname = 'EE_' . $model->get_this_model_name();
3322
+				if (
3323
+					$this->get_one_from_cache($relation_name) instanceof $classname
3324
+					&& $this->get_one_from_cache($relation_name)->ID()
3325
+				) {
3326
+					$this->clear_cache(
3327
+						$relation_name,
3328
+						$this->get_one_from_cache($relation_name)->ID()
3329
+					);
3330
+				}
3331
+			}
3332
+		}
3333
+		$this->_props_n_values_provided_in_constructor = array();
3334
+		$properties_to_serialize = get_object_vars($this);
3335
+		// don't serialize the model. It's big and that risks recursion
3336
+		unset($properties_to_serialize['_model']);
3337
+		return array_keys($properties_to_serialize);
3338
+	}
3339
+
3340
+
3341
+	/**
3342
+	 * restore _props_n_values_provided_in_constructor
3343
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3344
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3345
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3346
+	 */
3347
+	public function __wakeup()
3348
+	{
3349
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3350
+	}
3351
+
3352
+
3353
+	/**
3354
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3355
+	 * distinct with the clone host instance are also cloned.
3356
+	 */
3357
+	public function __clone()
3358
+	{
3359
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3360
+		foreach ($this->_fields as $field => $value) {
3361
+			if ($value instanceof DateTime) {
3362
+				$this->_fields[ $field ] = clone $value;
3363
+			}
3364
+		}
3365
+	}
3366 3366
 }
Please login to merge, or discard this patch.
core/EE_Error.core.php 2 patches
Indentation   +1126 added lines, -1126 removed lines patch added patch discarded remove patch
@@ -12,8 +12,8 @@  discard block
 block discarded – undo
12 12
 // if you're a dev and want to receive all errors via email
13 13
 // add this to your wp-config.php: define( 'EE_ERROR_EMAILS', TRUE );
14 14
 if (defined('WP_DEBUG') && WP_DEBUG === true && defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS === true) {
15
-    set_error_handler(array('EE_Error', 'error_handler'));
16
-    register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
15
+	set_error_handler(array('EE_Error', 'error_handler'));
16
+	register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
17 17
 }
18 18
 
19 19
 
@@ -27,266 +27,266 @@  discard block
 block discarded – undo
27 27
 class EE_Error extends Exception
28 28
 {
29 29
 
30
-    const OPTIONS_KEY_NOTICES = 'ee_notices';
31
-
32
-
33
-    /**
34
-     * name of the file to log exceptions to
35
-     *
36
-     * @var string
37
-     */
38
-    private static $_exception_log_file = 'espresso_error_log.txt';
39
-
40
-    /**
41
-     *    stores details for all exception
42
-     *
43
-     * @var array
44
-     */
45
-    private static $_all_exceptions = array();
46
-
47
-    /**
48
-     *    tracks number of errors
49
-     *
50
-     * @var int
51
-     */
52
-    private static $_error_count = 0;
53
-
54
-    /**
55
-     * @var array $_espresso_notices
56
-     */
57
-    private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
58
-
59
-
60
-    /**
61
-     * @override default exception handling
62
-     * @param string         $message
63
-     * @param int            $code
64
-     * @param Exception|null $previous
65
-     */
66
-    public function __construct($message, $code = 0, Exception $previous = null)
67
-    {
68
-        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
69
-            parent::__construct($message, $code);
70
-        } else {
71
-            parent::__construct($message, $code, $previous);
72
-        }
73
-    }
74
-
75
-
76
-    /**
77
-     *    error_handler
78
-     *
79
-     * @param $code
80
-     * @param $message
81
-     * @param $file
82
-     * @param $line
83
-     * @return void
84
-     */
85
-    public static function error_handler($code, $message, $file, $line)
86
-    {
87
-        $type = EE_Error::error_type($code);
88
-        $site = site_url();
89
-        switch ($site) {
90
-            case 'http://ee4.eventespresso.com/':
91
-            case 'http://ee4decaf.eventespresso.com/':
92
-            case 'http://ee4hf.eventespresso.com/':
93
-            case 'http://ee4a.eventespresso.com/':
94
-            case 'http://ee4ad.eventespresso.com/':
95
-            case 'http://ee4b.eventespresso.com/':
96
-            case 'http://ee4bd.eventespresso.com/':
97
-            case 'http://ee4d.eventespresso.com/':
98
-            case 'http://ee4dd.eventespresso.com/':
99
-                $to = '[email protected]';
100
-                break;
101
-            default:
102
-                $to = get_option('admin_email');
103
-        }
104
-        $subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
105
-        $msg = EE_Error::_format_error($type, $message, $file, $line);
106
-        if (function_exists('wp_mail')) {
107
-            add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
108
-            wp_mail($to, $subject, $msg);
109
-        }
110
-        echo '<div id="message" class="espresso-notices error"><p>';
111
-        echo wp_kses($type . ': ' . $message . '<br />' . $file . ' line ' . $line, AllowedTags::getWithFormTags());
112
-        echo '<br /></p></div>';
113
-    }
114
-
115
-
116
-    /**
117
-     * error_type
118
-     * http://www.php.net/manual/en/errorfunc.constants.php#109430
119
-     *
120
-     * @param $code
121
-     * @return string
122
-     */
123
-    public static function error_type($code)
124
-    {
125
-        switch ($code) {
126
-            case E_ERROR: // 1 //
127
-                return 'E_ERROR';
128
-            case E_WARNING: // 2 //
129
-                return 'E_WARNING';
130
-            case E_PARSE: // 4 //
131
-                return 'E_PARSE';
132
-            case E_NOTICE: // 8 //
133
-                return 'E_NOTICE';
134
-            case E_CORE_ERROR: // 16 //
135
-                return 'E_CORE_ERROR';
136
-            case E_CORE_WARNING: // 32 //
137
-                return 'E_CORE_WARNING';
138
-            case E_COMPILE_ERROR: // 64 //
139
-                return 'E_COMPILE_ERROR';
140
-            case E_COMPILE_WARNING: // 128 //
141
-                return 'E_COMPILE_WARNING';
142
-            case E_USER_ERROR: // 256 //
143
-                return 'E_USER_ERROR';
144
-            case E_USER_WARNING: // 512 //
145
-                return 'E_USER_WARNING';
146
-            case E_USER_NOTICE: // 1024 //
147
-                return 'E_USER_NOTICE';
148
-            case E_STRICT: // 2048 //
149
-                return 'E_STRICT';
150
-            case E_RECOVERABLE_ERROR: // 4096 //
151
-                return 'E_RECOVERABLE_ERROR';
152
-            case E_DEPRECATED: // 8192 //
153
-                return 'E_DEPRECATED';
154
-            case E_USER_DEPRECATED: // 16384 //
155
-                return 'E_USER_DEPRECATED';
156
-            case E_ALL: // 16384 //
157
-                return 'E_ALL';
158
-        }
159
-        return '';
160
-    }
161
-
162
-
163
-    /**
164
-     *    fatal_error_handler
165
-     *
166
-     * @return void
167
-     */
168
-    public static function fatal_error_handler()
169
-    {
170
-        $last_error = error_get_last();
171
-        if ($last_error['type'] === E_ERROR) {
172
-            EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
173
-        }
174
-    }
175
-
176
-
177
-    /**
178
-     * _format_error
179
-     *
180
-     * @param $code
181
-     * @param $message
182
-     * @param $file
183
-     * @param $line
184
-     * @return string
185
-     */
186
-    private static function _format_error($code, $message, $file, $line)
187
-    {
188
-        $html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
189
-        $html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
190
-        $html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
191
-        $html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
192
-        $html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
193
-        $html .= '</tbody></table>';
194
-        return $html;
195
-    }
196
-
197
-
198
-    /**
199
-     * set_content_type
200
-     *
201
-     * @param $content_type
202
-     * @return string
203
-     */
204
-    public static function set_content_type($content_type)
205
-    {
206
-        return 'text/html';
207
-    }
208
-
209
-
210
-    /**
211
-     * @return void
212
-     * @throws EE_Error
213
-     * @throws ReflectionException
214
-     */
215
-    public function get_error()
216
-    {
217
-        if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
218
-            throw $this;
219
-        }
220
-        // get separate user and developer messages if they exist
221
-        $msg = explode('||', $this->getMessage());
222
-        $user_msg = $msg[0];
223
-        $dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
224
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
225
-        // add details to _all_exceptions array
226
-        $x_time = time();
227
-        self::$_all_exceptions[ $x_time ]['name'] = get_class($this);
228
-        self::$_all_exceptions[ $x_time ]['file'] = $this->getFile();
229
-        self::$_all_exceptions[ $x_time ]['line'] = $this->getLine();
230
-        self::$_all_exceptions[ $x_time ]['msg'] = $msg;
231
-        self::$_all_exceptions[ $x_time ]['code'] = $this->getCode();
232
-        self::$_all_exceptions[ $x_time ]['trace'] = $this->getTrace();
233
-        self::$_all_exceptions[ $x_time ]['string'] = $this->getTraceAsString();
234
-        self::$_error_count++;
235
-        // add_action( 'shutdown', array( $this, 'display_errors' ));
236
-        $this->display_errors();
237
-    }
238
-
239
-
240
-    /**
241
-     * @param bool   $check_stored
242
-     * @param string $type_to_check
243
-     * @return bool
244
-     * @throws InvalidInterfaceException
245
-     * @throws InvalidArgumentException
246
-     * @throws InvalidDataTypeException
247
-     */
248
-    public static function has_error($check_stored = false, $type_to_check = 'errors')
249
-    {
250
-        $has_error = isset(self::$_espresso_notices[ $type_to_check ])
251
-                     && ! empty(self::$_espresso_notices[ $type_to_check ])
252
-            ? true
253
-            : false;
254
-        if ($check_stored && ! $has_error) {
255
-            $notices = EE_Error::getStoredNotices();
256
-            foreach ($notices as $type => $notice) {
257
-                if ($type === $type_to_check && $notice) {
258
-                    return true;
259
-                }
260
-            }
261
-        }
262
-        return $has_error;
263
-    }
264
-
265
-
266
-    /**
267
-     * @echo string
268
-     * @throws ReflectionException
269
-     */
270
-    public function display_errors()
271
-    {
272
-        $trace_details = '';
273
-        $output = '
30
+	const OPTIONS_KEY_NOTICES = 'ee_notices';
31
+
32
+
33
+	/**
34
+	 * name of the file to log exceptions to
35
+	 *
36
+	 * @var string
37
+	 */
38
+	private static $_exception_log_file = 'espresso_error_log.txt';
39
+
40
+	/**
41
+	 *    stores details for all exception
42
+	 *
43
+	 * @var array
44
+	 */
45
+	private static $_all_exceptions = array();
46
+
47
+	/**
48
+	 *    tracks number of errors
49
+	 *
50
+	 * @var int
51
+	 */
52
+	private static $_error_count = 0;
53
+
54
+	/**
55
+	 * @var array $_espresso_notices
56
+	 */
57
+	private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
58
+
59
+
60
+	/**
61
+	 * @override default exception handling
62
+	 * @param string         $message
63
+	 * @param int            $code
64
+	 * @param Exception|null $previous
65
+	 */
66
+	public function __construct($message, $code = 0, Exception $previous = null)
67
+	{
68
+		if (version_compare(PHP_VERSION, '5.3.0', '<')) {
69
+			parent::__construct($message, $code);
70
+		} else {
71
+			parent::__construct($message, $code, $previous);
72
+		}
73
+	}
74
+
75
+
76
+	/**
77
+	 *    error_handler
78
+	 *
79
+	 * @param $code
80
+	 * @param $message
81
+	 * @param $file
82
+	 * @param $line
83
+	 * @return void
84
+	 */
85
+	public static function error_handler($code, $message, $file, $line)
86
+	{
87
+		$type = EE_Error::error_type($code);
88
+		$site = site_url();
89
+		switch ($site) {
90
+			case 'http://ee4.eventespresso.com/':
91
+			case 'http://ee4decaf.eventespresso.com/':
92
+			case 'http://ee4hf.eventespresso.com/':
93
+			case 'http://ee4a.eventespresso.com/':
94
+			case 'http://ee4ad.eventespresso.com/':
95
+			case 'http://ee4b.eventespresso.com/':
96
+			case 'http://ee4bd.eventespresso.com/':
97
+			case 'http://ee4d.eventespresso.com/':
98
+			case 'http://ee4dd.eventespresso.com/':
99
+				$to = '[email protected]';
100
+				break;
101
+			default:
102
+				$to = get_option('admin_email');
103
+		}
104
+		$subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
105
+		$msg = EE_Error::_format_error($type, $message, $file, $line);
106
+		if (function_exists('wp_mail')) {
107
+			add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
108
+			wp_mail($to, $subject, $msg);
109
+		}
110
+		echo '<div id="message" class="espresso-notices error"><p>';
111
+		echo wp_kses($type . ': ' . $message . '<br />' . $file . ' line ' . $line, AllowedTags::getWithFormTags());
112
+		echo '<br /></p></div>';
113
+	}
114
+
115
+
116
+	/**
117
+	 * error_type
118
+	 * http://www.php.net/manual/en/errorfunc.constants.php#109430
119
+	 *
120
+	 * @param $code
121
+	 * @return string
122
+	 */
123
+	public static function error_type($code)
124
+	{
125
+		switch ($code) {
126
+			case E_ERROR: // 1 //
127
+				return 'E_ERROR';
128
+			case E_WARNING: // 2 //
129
+				return 'E_WARNING';
130
+			case E_PARSE: // 4 //
131
+				return 'E_PARSE';
132
+			case E_NOTICE: // 8 //
133
+				return 'E_NOTICE';
134
+			case E_CORE_ERROR: // 16 //
135
+				return 'E_CORE_ERROR';
136
+			case E_CORE_WARNING: // 32 //
137
+				return 'E_CORE_WARNING';
138
+			case E_COMPILE_ERROR: // 64 //
139
+				return 'E_COMPILE_ERROR';
140
+			case E_COMPILE_WARNING: // 128 //
141
+				return 'E_COMPILE_WARNING';
142
+			case E_USER_ERROR: // 256 //
143
+				return 'E_USER_ERROR';
144
+			case E_USER_WARNING: // 512 //
145
+				return 'E_USER_WARNING';
146
+			case E_USER_NOTICE: // 1024 //
147
+				return 'E_USER_NOTICE';
148
+			case E_STRICT: // 2048 //
149
+				return 'E_STRICT';
150
+			case E_RECOVERABLE_ERROR: // 4096 //
151
+				return 'E_RECOVERABLE_ERROR';
152
+			case E_DEPRECATED: // 8192 //
153
+				return 'E_DEPRECATED';
154
+			case E_USER_DEPRECATED: // 16384 //
155
+				return 'E_USER_DEPRECATED';
156
+			case E_ALL: // 16384 //
157
+				return 'E_ALL';
158
+		}
159
+		return '';
160
+	}
161
+
162
+
163
+	/**
164
+	 *    fatal_error_handler
165
+	 *
166
+	 * @return void
167
+	 */
168
+	public static function fatal_error_handler()
169
+	{
170
+		$last_error = error_get_last();
171
+		if ($last_error['type'] === E_ERROR) {
172
+			EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
173
+		}
174
+	}
175
+
176
+
177
+	/**
178
+	 * _format_error
179
+	 *
180
+	 * @param $code
181
+	 * @param $message
182
+	 * @param $file
183
+	 * @param $line
184
+	 * @return string
185
+	 */
186
+	private static function _format_error($code, $message, $file, $line)
187
+	{
188
+		$html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
189
+		$html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
190
+		$html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
191
+		$html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
192
+		$html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
193
+		$html .= '</tbody></table>';
194
+		return $html;
195
+	}
196
+
197
+
198
+	/**
199
+	 * set_content_type
200
+	 *
201
+	 * @param $content_type
202
+	 * @return string
203
+	 */
204
+	public static function set_content_type($content_type)
205
+	{
206
+		return 'text/html';
207
+	}
208
+
209
+
210
+	/**
211
+	 * @return void
212
+	 * @throws EE_Error
213
+	 * @throws ReflectionException
214
+	 */
215
+	public function get_error()
216
+	{
217
+		if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
218
+			throw $this;
219
+		}
220
+		// get separate user and developer messages if they exist
221
+		$msg = explode('||', $this->getMessage());
222
+		$user_msg = $msg[0];
223
+		$dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
224
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
225
+		// add details to _all_exceptions array
226
+		$x_time = time();
227
+		self::$_all_exceptions[ $x_time ]['name'] = get_class($this);
228
+		self::$_all_exceptions[ $x_time ]['file'] = $this->getFile();
229
+		self::$_all_exceptions[ $x_time ]['line'] = $this->getLine();
230
+		self::$_all_exceptions[ $x_time ]['msg'] = $msg;
231
+		self::$_all_exceptions[ $x_time ]['code'] = $this->getCode();
232
+		self::$_all_exceptions[ $x_time ]['trace'] = $this->getTrace();
233
+		self::$_all_exceptions[ $x_time ]['string'] = $this->getTraceAsString();
234
+		self::$_error_count++;
235
+		// add_action( 'shutdown', array( $this, 'display_errors' ));
236
+		$this->display_errors();
237
+	}
238
+
239
+
240
+	/**
241
+	 * @param bool   $check_stored
242
+	 * @param string $type_to_check
243
+	 * @return bool
244
+	 * @throws InvalidInterfaceException
245
+	 * @throws InvalidArgumentException
246
+	 * @throws InvalidDataTypeException
247
+	 */
248
+	public static function has_error($check_stored = false, $type_to_check = 'errors')
249
+	{
250
+		$has_error = isset(self::$_espresso_notices[ $type_to_check ])
251
+					 && ! empty(self::$_espresso_notices[ $type_to_check ])
252
+			? true
253
+			: false;
254
+		if ($check_stored && ! $has_error) {
255
+			$notices = EE_Error::getStoredNotices();
256
+			foreach ($notices as $type => $notice) {
257
+				if ($type === $type_to_check && $notice) {
258
+					return true;
259
+				}
260
+			}
261
+		}
262
+		return $has_error;
263
+	}
264
+
265
+
266
+	/**
267
+	 * @echo string
268
+	 * @throws ReflectionException
269
+	 */
270
+	public function display_errors()
271
+	{
272
+		$trace_details = '';
273
+		$output = '
274 274
         <div id="ee-error-message" class="error">';
275
-        if (! WP_DEBUG) {
276
-            $output .= '
275
+		if (! WP_DEBUG) {
276
+			$output .= '
277 277
 	        <p>';
278
-        }
279
-        // cycle thru errors
280
-        foreach (self::$_all_exceptions as $time => $ex) {
281
-            $error_code = '';
282
-            // process trace info
283
-            if (empty($ex['trace'])) {
284
-                $trace_details .= esc_html__(
285
-                    'Sorry, but no trace information was available for this exception.',
286
-                    'event_espresso'
287
-                );
288
-            } else {
289
-                $trace_details .= '
278
+		}
279
+		// cycle thru errors
280
+		foreach (self::$_all_exceptions as $time => $ex) {
281
+			$error_code = '';
282
+			// process trace info
283
+			if (empty($ex['trace'])) {
284
+				$trace_details .= esc_html__(
285
+					'Sorry, but no trace information was available for this exception.',
286
+					'event_espresso'
287
+				);
288
+			} else {
289
+				$trace_details .= '
290 290
 			<div id="ee-trace-details">
291 291
 			<table width="100%" border="0" cellpadding="5" cellspacing="0">
292 292
 				<tr>
@@ -296,43 +296,43 @@  discard block
 block discarded – undo
296 296
 					<th scope="col" align="left">Class</th>
297 297
 					<th scope="col" align="left">Method( arguments )</th>
298 298
 				</tr>';
299
-                $last_on_stack = count($ex['trace']) - 1;
300
-                // reverse array so that stack is in proper chronological order
301
-                $sorted_trace = array_reverse($ex['trace']);
302
-                foreach ($sorted_trace as $nmbr => $trace) {
303
-                    $file = isset($trace['file']) ? $trace['file'] : '';
304
-                    $class = isset($trace['class']) ? $trace['class'] : '';
305
-                    $type = isset($trace['type']) ? $trace['type'] : '';
306
-                    $function = isset($trace['function']) ? $trace['function'] : '';
307
-                    $args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
308
-                    $line = isset($trace['line']) ? $trace['line'] : '';
309
-                    $zebra = ($nmbr % 2) ? ' odd' : '';
310
-                    if (empty($file) && ! empty($class)) {
311
-                        $a = new ReflectionClass($class);
312
-                        $file = $a->getFileName();
313
-                        if (empty($line) && ! empty($function)) {
314
-                            try {
315
-                                // if $function is a closure, this throws an exception
316
-                                $b = new ReflectionMethod($class, $function);
317
-                                $line = $b->getStartLine();
318
-                            } catch (Exception $closure_exception) {
319
-                                $line = 'unknown';
320
-                            }
321
-                        }
322
-                    }
323
-                    if ($nmbr === $last_on_stack) {
324
-                        $file = $ex['file'] !== '' ? $ex['file'] : $file;
325
-                        $line = $ex['line'] !== '' ? $ex['line'] : $line;
326
-                        $error_code = self::generate_error_code($file, $trace['function'], $line);
327
-                    }
328
-                    $nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
329
-                    $line_dsply = ! empty($line) ? $line : '&nbsp;';
330
-                    $file_dsply = ! empty($file) ? $file : '&nbsp;';
331
-                    $class_dsply = ! empty($class) ? $class : '&nbsp;';
332
-                    $type_dsply = ! empty($type) ? $type : '&nbsp;';
333
-                    $function_dsply = ! empty($function) ? $function : '&nbsp;';
334
-                    $args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
335
-                    $trace_details .= '
299
+				$last_on_stack = count($ex['trace']) - 1;
300
+				// reverse array so that stack is in proper chronological order
301
+				$sorted_trace = array_reverse($ex['trace']);
302
+				foreach ($sorted_trace as $nmbr => $trace) {
303
+					$file = isset($trace['file']) ? $trace['file'] : '';
304
+					$class = isset($trace['class']) ? $trace['class'] : '';
305
+					$type = isset($trace['type']) ? $trace['type'] : '';
306
+					$function = isset($trace['function']) ? $trace['function'] : '';
307
+					$args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
308
+					$line = isset($trace['line']) ? $trace['line'] : '';
309
+					$zebra = ($nmbr % 2) ? ' odd' : '';
310
+					if (empty($file) && ! empty($class)) {
311
+						$a = new ReflectionClass($class);
312
+						$file = $a->getFileName();
313
+						if (empty($line) && ! empty($function)) {
314
+							try {
315
+								// if $function is a closure, this throws an exception
316
+								$b = new ReflectionMethod($class, $function);
317
+								$line = $b->getStartLine();
318
+							} catch (Exception $closure_exception) {
319
+								$line = 'unknown';
320
+							}
321
+						}
322
+					}
323
+					if ($nmbr === $last_on_stack) {
324
+						$file = $ex['file'] !== '' ? $ex['file'] : $file;
325
+						$line = $ex['line'] !== '' ? $ex['line'] : $line;
326
+						$error_code = self::generate_error_code($file, $trace['function'], $line);
327
+					}
328
+					$nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
329
+					$line_dsply = ! empty($line) ? $line : '&nbsp;';
330
+					$file_dsply = ! empty($file) ? $file : '&nbsp;';
331
+					$class_dsply = ! empty($class) ? $class : '&nbsp;';
332
+					$type_dsply = ! empty($type) ? $type : '&nbsp;';
333
+					$function_dsply = ! empty($function) ? $function : '&nbsp;';
334
+					$args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
335
+					$trace_details .= '
336 336
 					<tr>
337 337
 						<td align="right" class="' . $zebra . '">' . $nmbr_dsply . '</td>
338 338
 						<td align="right" class="' . $zebra . '">' . $line_dsply . '</td>
@@ -340,628 +340,628 @@  discard block
 block discarded – undo
340 340
 						<td align="left" class="' . $zebra . '">' . $class_dsply . '</td>
341 341
 						<td align="left" class="' . $zebra . '">' . $type_dsply . $function_dsply . $args_dsply . '</td>
342 342
 					</tr>';
343
-                }
344
-                $trace_details .= '
343
+				}
344
+				$trace_details .= '
345 345
 			 </table>
346 346
 			</div>';
347
-            }
348
-            $ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
349
-            // add generic non-identifying messages for non-privileged users
350
-            if (! WP_DEBUG) {
351
-                $output .= '<span class="ee-error-user-msg-spn">'
352
-                           . trim($ex['msg'])
353
-                           . '</span> &nbsp; <sup>'
354
-                           . $ex['code']
355
-                           . '</sup><br />';
356
-            } else {
357
-                // or helpful developer messages if debugging is on
358
-                $output .= '
347
+			}
348
+			$ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
349
+			// add generic non-identifying messages for non-privileged users
350
+			if (! WP_DEBUG) {
351
+				$output .= '<span class="ee-error-user-msg-spn">'
352
+						   . trim($ex['msg'])
353
+						   . '</span> &nbsp; <sup>'
354
+						   . $ex['code']
355
+						   . '</sup><br />';
356
+			} else {
357
+				// or helpful developer messages if debugging is on
358
+				$output .= '
359 359
 		<div class="ee-error-dev-msg-dv">
360 360
 			<p class="ee-error-dev-msg-pg">
361 361
 				<strong class="ee-error-dev-msg-str">An '
362
-                           . $ex['name']
363
-                           . ' exception was thrown!</strong>  &nbsp; <span>code: '
364
-                           . $ex['code']
365
-                           . '</span><br />
362
+						   . $ex['name']
363
+						   . ' exception was thrown!</strong>  &nbsp; <span>code: '
364
+						   . $ex['code']
365
+						   . '</span><br />
366 366
 				<span class="big-text">"'
367
-                           . trim($ex['msg'])
368
-                           . '"</span><br/>
367
+						   . trim($ex['msg'])
368
+						   . '"</span><br/>
369 369
 				<a id="display-ee-error-trace-'
370
-                           . self::$_error_count
371
-                           . $time
372
-                           . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
373
-                           . self::$_error_count
374
-                           . $time
375
-                           . '">
370
+						   . self::$_error_count
371
+						   . $time
372
+						   . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
373
+						   . self::$_error_count
374
+						   . $time
375
+						   . '">
376 376
 					'
377
-                           . esc_html__('click to view backtrace and class/method details', 'event_espresso')
378
-                           . '
377
+						   . esc_html__('click to view backtrace and class/method details', 'event_espresso')
378
+						   . '
379 379
 				</a><br />
380 380
 				<span class="small-text lt-grey-text">'
381
-                           . $ex['file']
382
-                           . ' &nbsp; ( line no: '
383
-                           . $ex['line']
384
-                           . ' )</span>
381
+						   . $ex['file']
382
+						   . ' &nbsp; ( line no: '
383
+						   . $ex['line']
384
+						   . ' )</span>
385 385
 			</p>
386 386
 			<div id="ee-error-trace-'
387
-                           . self::$_error_count
388
-                           . $time
389
-                           . '-dv" class="ee-error-trace-dv" style="display: none;">
387
+						   . self::$_error_count
388
+						   . $time
389
+						   . '-dv" class="ee-error-trace-dv" style="display: none;">
390 390
 				'
391
-                           . $trace_details;
392
-                if (! empty($class)) {
393
-                    $output .= '
391
+						   . $trace_details;
392
+				if (! empty($class)) {
393
+					$output .= '
394 394
 				<div style="padding:3px; margin:0 0 1em; border:1px solid #666; background:#fff; border-radius:3px;">
395 395
 					<div style="padding:1em 2em; border:1px solid #666; background:#f9f9f9;">
396 396
 						<h3>Class Details</h3>';
397
-                    $a = new ReflectionClass($class);
398
-                    $output .= '
397
+					$a = new ReflectionClass($class);
398
+					$output .= '
399 399
 						<pre>' . $a . '</pre>
400 400
 					</div>
401 401
 				</div>';
402
-                }
403
-                $output .= '
402
+				}
403
+				$output .= '
404 404
 			</div>
405 405
 		</div>
406 406
 		<br />';
407
-            }
408
-            $this->write_to_error_log($time, $ex);
409
-        }
410
-        // remove last linebreak
411
-        $output = substr($output, 0, -6);
412
-        if (! WP_DEBUG) {
413
-            $output .= '
407
+			}
408
+			$this->write_to_error_log($time, $ex);
409
+		}
410
+		// remove last linebreak
411
+		$output = substr($output, 0, -6);
412
+		if (! WP_DEBUG) {
413
+			$output .= '
414 414
 	        </p>';
415
-        }
416
-        $output .= '
415
+		}
416
+		$output .= '
417 417
         </div>';
418
-        $output .= self::_print_scripts(true);
419
-        if (defined('DOING_AJAX')) {
420
-            echo wp_json_encode(array('error' => $output));
421
-            exit();
422
-        }
423
-        echo wp_kses($output, AllowedTags::getWithFormTags());
424
-        die();
425
-    }
426
-
427
-
428
-    /**
429
-     *    generate string from exception trace args
430
-     *
431
-     * @param array $arguments
432
-     * @param bool  $array
433
-     * @return string
434
-     */
435
-    private function _convert_args_to_string($arguments = array(), $array = false)
436
-    {
437
-        $arg_string = '';
438
-        if (! empty($arguments)) {
439
-            $args = array();
440
-            foreach ($arguments as $arg) {
441
-                if (! empty($arg)) {
442
-                    if (is_string($arg)) {
443
-                        $args[] = " '" . $arg . "'";
444
-                    } elseif (is_array($arg)) {
445
-                        $args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
446
-                    } elseif ($arg === null) {
447
-                        $args[] = ' NULL';
448
-                    } elseif (is_bool($arg)) {
449
-                        $args[] = ($arg) ? ' TRUE' : ' FALSE';
450
-                    } elseif (is_object($arg)) {
451
-                        $args[] = ' OBJECT ' . get_class($arg);
452
-                    } elseif (is_resource($arg)) {
453
-                        $args[] = get_resource_type($arg);
454
-                    } else {
455
-                        $args[] = $arg;
456
-                    }
457
-                }
458
-            }
459
-            $arg_string = implode(', ', $args);
460
-        }
461
-        if ($array) {
462
-            $arg_string .= ' )';
463
-        }
464
-        return $arg_string;
465
-    }
466
-
467
-
468
-    /**
469
-     *    add error message
470
-     *
471
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
472
-     *                            separate messages for user || dev
473
-     * @param        string $file the file that the error occurred in - just use __FILE__
474
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
475
-     * @param        string $line the line number where the error occurred - just use __LINE__
476
-     * @return        void
477
-     */
478
-    public static function add_error($msg = null, $file = null, $func = null, $line = null)
479
-    {
480
-        self::_add_notice('errors', $msg, $file, $func, $line);
481
-        self::$_error_count++;
482
-    }
483
-
484
-
485
-    /**
486
-     * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
487
-     * adds an error
488
-     *
489
-     * @param string $msg
490
-     * @param string $file
491
-     * @param string $func
492
-     * @param string $line
493
-     * @throws EE_Error
494
-     */
495
-    public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
496
-    {
497
-        if (WP_DEBUG) {
498
-            throw new EE_Error($msg);
499
-        }
500
-        EE_Error::add_error($msg, $file, $func, $line);
501
-    }
502
-
503
-
504
-    /**
505
-     *    add success message
506
-     *
507
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
508
-     *                            separate messages for user || dev
509
-     * @param        string $file the file that the error occurred in - just use __FILE__
510
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
511
-     * @param        string $line the line number where the error occurred - just use __LINE__
512
-     * @return        void
513
-     */
514
-    public static function add_success($msg = null, $file = null, $func = null, $line = null)
515
-    {
516
-        self::_add_notice('success', $msg, $file, $func, $line);
517
-    }
518
-
519
-
520
-    /**
521
-     *    add attention message
522
-     *
523
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
524
-     *                            separate messages for user || dev
525
-     * @param        string $file the file that the error occurred in - just use __FILE__
526
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
527
-     * @param        string $line the line number where the error occurred - just use __LINE__
528
-     * @return        void
529
-     */
530
-    public static function add_attention($msg = null, $file = null, $func = null, $line = null)
531
-    {
532
-        self::_add_notice('attention', $msg, $file, $func, $line);
533
-    }
534
-
535
-
536
-    /**
537
-     * @param string $type whether the message is for a success or error notification
538
-     * @param string $msg  the message to display to users or developers
539
-     *                     - adding a double pipe || (OR) creates separate messages for user || dev
540
-     * @param string $file the file that the error occurred in - just use __FILE__
541
-     * @param string $func the function/method that the error occurred in - just use __FUNCTION__
542
-     * @param string $line the line number where the error occurred - just use __LINE__
543
-     * @return void
544
-     */
545
-    private static function _add_notice($type = 'success', $msg = '', $file = '', $func = '', $line = '')
546
-    {
547
-        if (empty($msg)) {
548
-            EE_Error::doing_it_wrong(
549
-                'EE_Error::add_' . $type . '()',
550
-                sprintf(
551
-                    esc_html__(
552
-                        'Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
553
-                        'event_espresso'
554
-                    ),
555
-                    $type,
556
-                    $file,
557
-                    $line
558
-                ),
559
-                EVENT_ESPRESSO_VERSION
560
-            );
561
-        }
562
-        if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
563
-            EE_Error::doing_it_wrong(
564
-                'EE_Error::add_error()',
565
-                esc_html__(
566
-                    'You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
567
-                    'event_espresso'
568
-                ),
569
-                EVENT_ESPRESSO_VERSION
570
-            );
571
-        }
572
-        // get separate user and developer messages if they exist
573
-        $msg = explode('||', $msg);
574
-        $user_msg = $msg[0];
575
-        $dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
576
-        /**
577
-         * Do an action so other code can be triggered when a notice is created
578
-         *
579
-         * @param string $type     can be 'errors', 'attention', or 'success'
580
-         * @param string $user_msg message displayed to user when WP_DEBUG is off
581
-         * @param string $user_msg message displayed to user when WP_DEBUG is on
582
-         * @param string $file     file where error was generated
583
-         * @param string $func     function where error was generated
584
-         * @param string $line     line where error was generated
585
-         */
586
-        do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
587
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
588
-        // add notice if message exists
589
-        if (! empty($msg)) {
590
-            // get error code
591
-            $notice_code = EE_Error::generate_error_code($file, $func, $line);
592
-            if (WP_DEBUG && $type === 'errors') {
593
-                $msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
594
-            }
595
-            // add notice. Index by code if it's not blank
596
-            if ($notice_code) {
597
-                self::$_espresso_notices[ $type ][ $notice_code ] = $msg;
598
-            } else {
599
-                self::$_espresso_notices[ $type ][] = $msg;
600
-            }
601
-            add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
602
-        }
603
-    }
604
-
605
-
606
-    /**
607
-     * in some case it may be necessary to overwrite the existing success messages
608
-     *
609
-     * @return        void
610
-     */
611
-    public static function overwrite_success()
612
-    {
613
-        self::$_espresso_notices['success'] = false;
614
-    }
615
-
616
-
617
-    /**
618
-     * in some case it may be necessary to overwrite the existing attention messages
619
-     *
620
-     * @return void
621
-     */
622
-    public static function overwrite_attention()
623
-    {
624
-        self::$_espresso_notices['attention'] = false;
625
-    }
626
-
627
-
628
-    /**
629
-     * in some case it may be necessary to overwrite the existing error messages
630
-     *
631
-     * @return void
632
-     */
633
-    public static function overwrite_errors()
634
-    {
635
-        self::$_espresso_notices['errors'] = false;
636
-    }
637
-
638
-
639
-    /**
640
-     * @return void
641
-     */
642
-    public static function reset_notices()
643
-    {
644
-        self::$_espresso_notices['success'] = false;
645
-        self::$_espresso_notices['attention'] = false;
646
-        self::$_espresso_notices['errors'] = false;
647
-    }
648
-
649
-
650
-    /**
651
-     * @return int
652
-     */
653
-    public static function has_notices()
654
-    {
655
-        $has_notices = 0;
656
-        // check for success messages
657
-        $has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])
658
-            ? 3
659
-            : $has_notices;
660
-        // check for attention messages
661
-        $has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])
662
-            ? 2
663
-            : $has_notices;
664
-        // check for error messages
665
-        $has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])
666
-            ? 1
667
-            : $has_notices;
668
-        return $has_notices;
669
-    }
670
-
671
-
672
-    /**
673
-     * This simply returns non formatted error notices as they were sent into the EE_Error object.
674
-     *
675
-     * @since 4.9.0
676
-     * @return array
677
-     */
678
-    public static function get_vanilla_notices()
679
-    {
680
-        return array(
681
-            'success'   => isset(self::$_espresso_notices['success'])
682
-                ? self::$_espresso_notices['success']
683
-                : array(),
684
-            'attention' => isset(self::$_espresso_notices['attention'])
685
-                ? self::$_espresso_notices['attention']
686
-                : array(),
687
-            'errors'    => isset(self::$_espresso_notices['errors'])
688
-                ? self::$_espresso_notices['errors']
689
-                : array(),
690
-        );
691
-    }
692
-
693
-
694
-    /**
695
-     * @return array
696
-     * @throws InvalidArgumentException
697
-     * @throws InvalidDataTypeException
698
-     * @throws InvalidInterfaceException
699
-     */
700
-    public static function getStoredNotices()
701
-    {
702
-        if ($user_id = get_current_user_id()) {
703
-            // get notices for logged in user
704
-            $notices = get_user_option(EE_Error::OPTIONS_KEY_NOTICES, $user_id);
705
-            return is_array($notices) ? $notices : array();
706
-        }
707
-        if (EE_Session::isLoadedAndActive()) {
708
-            // get notices for user currently engaged in a session
709
-            $session_data = EE_Session::instance()->get_session_data(EE_Error::OPTIONS_KEY_NOTICES);
710
-            return is_array($session_data) ? $session_data : array();
711
-        }
712
-        // get global notices and hope they apply to the current site visitor
713
-        $notices = get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
714
-        return is_array($notices) ? $notices : array();
715
-    }
716
-
717
-
718
-    /**
719
-     * @param array $notices
720
-     * @return bool
721
-     * @throws InvalidArgumentException
722
-     * @throws InvalidDataTypeException
723
-     * @throws InvalidInterfaceException
724
-     */
725
-    public static function storeNotices(array $notices)
726
-    {
727
-        if ($user_id = get_current_user_id()) {
728
-            // store notices for logged in user
729
-            return (bool) update_user_option(
730
-                $user_id,
731
-                EE_Error::OPTIONS_KEY_NOTICES,
732
-                $notices
733
-            );
734
-        }
735
-        if (EE_Session::isLoadedAndActive()) {
736
-            // store notices for user currently engaged in a session
737
-            return EE_Session::instance()->set_session_data(
738
-                array(EE_Error::OPTIONS_KEY_NOTICES => $notices)
739
-            );
740
-        }
741
-        // store global notices and hope they apply to the same site visitor on the next request
742
-        return update_option(EE_Error::OPTIONS_KEY_NOTICES, $notices);
743
-    }
744
-
745
-
746
-    /**
747
-     * @return bool|TRUE
748
-     * @throws InvalidArgumentException
749
-     * @throws InvalidDataTypeException
750
-     * @throws InvalidInterfaceException
751
-     */
752
-    public static function clearNotices()
753
-    {
754
-        if ($user_id = get_current_user_id()) {
755
-            // clear notices for logged in user
756
-            return (bool) update_user_option(
757
-                $user_id,
758
-                EE_Error::OPTIONS_KEY_NOTICES,
759
-                array()
760
-            );
761
-        }
762
-        if (EE_Session::isLoadedAndActive()) {
763
-            // clear notices for user currently engaged in a session
764
-            return EE_Session::instance()->reset_data(EE_Error::OPTIONS_KEY_NOTICES);
765
-        }
766
-        // clear global notices and hope none belonged to some for some other site visitor
767
-        return update_option(EE_Error::OPTIONS_KEY_NOTICES, array());
768
-    }
769
-
770
-
771
-    /**
772
-     * saves notices to the db for retrieval on next request
773
-     *
774
-     * @return void
775
-     * @throws InvalidArgumentException
776
-     * @throws InvalidDataTypeException
777
-     * @throws InvalidInterfaceException
778
-     */
779
-    public static function stashNoticesBeforeRedirect()
780
-    {
781
-        EE_Error::get_notices(false, true);
782
-    }
783
-
784
-
785
-    /**
786
-     * compile all error or success messages into one string
787
-     *
788
-     * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
789
-     * @param bool $format_output            whether or not to format the messages for display in the WP admin
790
-     * @param bool $save_to_transient        whether or not to save notices to the db for retrieval on next request
791
-     *                                          - ONLY do this just before redirecting
792
-     * @param bool $remove_empty             whether or not to unset empty messages
793
-     * @return array|string
794
-     * @throws InvalidArgumentException
795
-     * @throws InvalidDataTypeException
796
-     * @throws InvalidInterfaceException
797
-     */
798
-    public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
799
-    {
800
-        $success_messages = '';
801
-        $attention_messages = '';
802
-        $error_messages = '';
803
-        /** @var RequestInterface $request */
804
-        $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
805
-        // either save notices to the db
806
-        if ($save_to_transient || $request->requestParamIsSet('activate-selected')) {
807
-            self::$_espresso_notices = array_merge(
808
-                EE_Error::getStoredNotices(),
809
-                self::$_espresso_notices
810
-            );
811
-            EE_Error::storeNotices(self::$_espresso_notices);
812
-            return array();
813
-        }
814
-        $print_scripts = EE_Error::combineExistingAndNewNotices();
815
-        // check for success messages
816
-        if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
817
-            // combine messages
818
-            $success_messages .= implode('<br />', self::$_espresso_notices['success']);
819
-            $print_scripts = true;
820
-        }
821
-        // check for attention messages
822
-        if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
823
-            // combine messages
824
-            $attention_messages .= implode('<br />', self::$_espresso_notices['attention']);
825
-            $print_scripts = true;
826
-        }
827
-        // check for error messages
828
-        if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
829
-            $error_messages .= count(self::$_espresso_notices['errors']) > 1
830
-                ? esc_html__('The following errors have occurred:', 'event_espresso')
831
-                : esc_html__('An error has occurred:', 'event_espresso');
832
-            // combine messages
833
-            $error_messages .= '<br />' . implode('<br />', self::$_espresso_notices['errors']);
834
-            $print_scripts = true;
835
-        }
836
-        if ($format_output) {
837
-            $notices = EE_Error::formatNoticesOutput(
838
-                $success_messages,
839
-                $attention_messages,
840
-                $error_messages
841
-            );
842
-        } else {
843
-            $notices = array(
844
-                'success'   => $success_messages,
845
-                'attention' => $attention_messages,
846
-                'errors'    => $error_messages,
847
-            );
848
-            if ($remove_empty) {
849
-                // remove empty notices
850
-                foreach ($notices as $type => $notice) {
851
-                    if (empty($notice)) {
852
-                        unset($notices[ $type ]);
853
-                    }
854
-                }
855
-            }
856
-        }
857
-        if ($print_scripts) {
858
-            self::_print_scripts();
859
-        }
860
-        return $notices;
861
-    }
862
-
863
-
864
-    /**
865
-     * @return bool
866
-     * @throws InvalidArgumentException
867
-     * @throws InvalidDataTypeException
868
-     * @throws InvalidInterfaceException
869
-     */
870
-    private static function combineExistingAndNewNotices()
871
-    {
872
-        $print_scripts = false;
873
-        // grab any notices that have been previously saved
874
-        $notices = EE_Error::getStoredNotices();
875
-        if (! empty($notices)) {
876
-            foreach ($notices as $type => $notice) {
877
-                if (is_array($notice) && ! empty($notice)) {
878
-                    // make sure that existing notice type is an array
879
-                    self::$_espresso_notices[ $type ] = is_array(self::$_espresso_notices[ $type ])
880
-                                                        && ! empty(self::$_espresso_notices[ $type ])
881
-                        ? self::$_espresso_notices[ $type ]
882
-                        : array();
883
-                    // add newly created notices to existing ones
884
-                    self::$_espresso_notices[ $type ] += $notice;
885
-                    $print_scripts = true;
886
-                }
887
-            }
888
-            // now clear any stored notices
889
-            EE_Error::clearNotices();
890
-        }
891
-        return $print_scripts;
892
-    }
893
-
894
-
895
-    /**
896
-     * @param string $success_messages
897
-     * @param string $attention_messages
898
-     * @param string $error_messages
899
-     * @return string
900
-     */
901
-    private static function formatNoticesOutput($success_messages, $attention_messages, $error_messages)
902
-    {
903
-        $notices = '<div id="espresso-notices">';
904
-        $close = is_admin()
905
-            ? ''
906
-            : '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"/></a>';
907
-        if ($success_messages !== '') {
908
-            $css_id = is_admin() ? 'ee-success-message' : 'espresso-notices-success';
909
-            $css_class = is_admin() ? 'updated fade' : 'success fade-away';
910
-            // showMessage( $success_messages );
911
-            $notices .= '<div id="' . $css_id . '" '
912
-                        . 'class="espresso-notices ' . $css_class . '" '
913
-                        . 'style="display:none;">'
914
-                        . '<p>' . $success_messages . '</p>'
915
-                        . $close
916
-                        . '</div>';
917
-        }
918
-        if ($attention_messages !== '') {
919
-            $css_id = is_admin() ? 'ee-attention-message' : 'espresso-notices-attention';
920
-            $css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
921
-            // showMessage( $error_messages, TRUE );
922
-            $notices .= '<div id="' . $css_id . '" '
923
-                        . 'class="espresso-notices ' . $css_class . '" '
924
-                        . 'style="display:none;">'
925
-                        . '<p>' . $attention_messages . '</p>'
926
-                        . $close
927
-                        . '</div>';
928
-        }
929
-        if ($error_messages !== '') {
930
-            $css_id = is_admin() ? 'ee-error-message' : 'espresso-notices-error';
931
-            $css_class = is_admin() ? 'error' : 'error fade-away';
932
-            // showMessage( $error_messages, TRUE );
933
-            $notices .= '<div id="' . $css_id . '" '
934
-                        . 'class="espresso-notices ' . $css_class . '" '
935
-                        . 'style="display:none;">'
936
-                        . '<p>' . $error_messages . '</p>'
937
-                        . $close
938
-                        . '</div>';
939
-        }
940
-        $notices .= '</div>';
941
-        return $notices;
942
-    }
943
-
944
-
945
-    /**
946
-     * _print_scripts
947
-     *
948
-     * @param    bool $force_print
949
-     * @return    string
950
-     */
951
-    private static function _print_scripts($force_print = false)
952
-    {
953
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
954
-            if (wp_script_is('ee_error_js', 'registered')) {
955
-                wp_enqueue_style('espresso_default');
956
-                wp_enqueue_style('espresso_custom_css');
957
-                wp_enqueue_script('ee_error_js');
958
-            }
959
-            if (wp_script_is('ee_error_js', 'enqueued')) {
960
-                wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
961
-                return '';
962
-            }
963
-        } else {
964
-            return '
418
+		$output .= self::_print_scripts(true);
419
+		if (defined('DOING_AJAX')) {
420
+			echo wp_json_encode(array('error' => $output));
421
+			exit();
422
+		}
423
+		echo wp_kses($output, AllowedTags::getWithFormTags());
424
+		die();
425
+	}
426
+
427
+
428
+	/**
429
+	 *    generate string from exception trace args
430
+	 *
431
+	 * @param array $arguments
432
+	 * @param bool  $array
433
+	 * @return string
434
+	 */
435
+	private function _convert_args_to_string($arguments = array(), $array = false)
436
+	{
437
+		$arg_string = '';
438
+		if (! empty($arguments)) {
439
+			$args = array();
440
+			foreach ($arguments as $arg) {
441
+				if (! empty($arg)) {
442
+					if (is_string($arg)) {
443
+						$args[] = " '" . $arg . "'";
444
+					} elseif (is_array($arg)) {
445
+						$args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
446
+					} elseif ($arg === null) {
447
+						$args[] = ' NULL';
448
+					} elseif (is_bool($arg)) {
449
+						$args[] = ($arg) ? ' TRUE' : ' FALSE';
450
+					} elseif (is_object($arg)) {
451
+						$args[] = ' OBJECT ' . get_class($arg);
452
+					} elseif (is_resource($arg)) {
453
+						$args[] = get_resource_type($arg);
454
+					} else {
455
+						$args[] = $arg;
456
+					}
457
+				}
458
+			}
459
+			$arg_string = implode(', ', $args);
460
+		}
461
+		if ($array) {
462
+			$arg_string .= ' )';
463
+		}
464
+		return $arg_string;
465
+	}
466
+
467
+
468
+	/**
469
+	 *    add error message
470
+	 *
471
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
472
+	 *                            separate messages for user || dev
473
+	 * @param        string $file the file that the error occurred in - just use __FILE__
474
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
475
+	 * @param        string $line the line number where the error occurred - just use __LINE__
476
+	 * @return        void
477
+	 */
478
+	public static function add_error($msg = null, $file = null, $func = null, $line = null)
479
+	{
480
+		self::_add_notice('errors', $msg, $file, $func, $line);
481
+		self::$_error_count++;
482
+	}
483
+
484
+
485
+	/**
486
+	 * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
487
+	 * adds an error
488
+	 *
489
+	 * @param string $msg
490
+	 * @param string $file
491
+	 * @param string $func
492
+	 * @param string $line
493
+	 * @throws EE_Error
494
+	 */
495
+	public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
496
+	{
497
+		if (WP_DEBUG) {
498
+			throw new EE_Error($msg);
499
+		}
500
+		EE_Error::add_error($msg, $file, $func, $line);
501
+	}
502
+
503
+
504
+	/**
505
+	 *    add success message
506
+	 *
507
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
508
+	 *                            separate messages for user || dev
509
+	 * @param        string $file the file that the error occurred in - just use __FILE__
510
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
511
+	 * @param        string $line the line number where the error occurred - just use __LINE__
512
+	 * @return        void
513
+	 */
514
+	public static function add_success($msg = null, $file = null, $func = null, $line = null)
515
+	{
516
+		self::_add_notice('success', $msg, $file, $func, $line);
517
+	}
518
+
519
+
520
+	/**
521
+	 *    add attention message
522
+	 *
523
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
524
+	 *                            separate messages for user || dev
525
+	 * @param        string $file the file that the error occurred in - just use __FILE__
526
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
527
+	 * @param        string $line the line number where the error occurred - just use __LINE__
528
+	 * @return        void
529
+	 */
530
+	public static function add_attention($msg = null, $file = null, $func = null, $line = null)
531
+	{
532
+		self::_add_notice('attention', $msg, $file, $func, $line);
533
+	}
534
+
535
+
536
+	/**
537
+	 * @param string $type whether the message is for a success or error notification
538
+	 * @param string $msg  the message to display to users or developers
539
+	 *                     - adding a double pipe || (OR) creates separate messages for user || dev
540
+	 * @param string $file the file that the error occurred in - just use __FILE__
541
+	 * @param string $func the function/method that the error occurred in - just use __FUNCTION__
542
+	 * @param string $line the line number where the error occurred - just use __LINE__
543
+	 * @return void
544
+	 */
545
+	private static function _add_notice($type = 'success', $msg = '', $file = '', $func = '', $line = '')
546
+	{
547
+		if (empty($msg)) {
548
+			EE_Error::doing_it_wrong(
549
+				'EE_Error::add_' . $type . '()',
550
+				sprintf(
551
+					esc_html__(
552
+						'Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
553
+						'event_espresso'
554
+					),
555
+					$type,
556
+					$file,
557
+					$line
558
+				),
559
+				EVENT_ESPRESSO_VERSION
560
+			);
561
+		}
562
+		if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
563
+			EE_Error::doing_it_wrong(
564
+				'EE_Error::add_error()',
565
+				esc_html__(
566
+					'You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
567
+					'event_espresso'
568
+				),
569
+				EVENT_ESPRESSO_VERSION
570
+			);
571
+		}
572
+		// get separate user and developer messages if they exist
573
+		$msg = explode('||', $msg);
574
+		$user_msg = $msg[0];
575
+		$dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
576
+		/**
577
+		 * Do an action so other code can be triggered when a notice is created
578
+		 *
579
+		 * @param string $type     can be 'errors', 'attention', or 'success'
580
+		 * @param string $user_msg message displayed to user when WP_DEBUG is off
581
+		 * @param string $user_msg message displayed to user when WP_DEBUG is on
582
+		 * @param string $file     file where error was generated
583
+		 * @param string $func     function where error was generated
584
+		 * @param string $line     line where error was generated
585
+		 */
586
+		do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
587
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
588
+		// add notice if message exists
589
+		if (! empty($msg)) {
590
+			// get error code
591
+			$notice_code = EE_Error::generate_error_code($file, $func, $line);
592
+			if (WP_DEBUG && $type === 'errors') {
593
+				$msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
594
+			}
595
+			// add notice. Index by code if it's not blank
596
+			if ($notice_code) {
597
+				self::$_espresso_notices[ $type ][ $notice_code ] = $msg;
598
+			} else {
599
+				self::$_espresso_notices[ $type ][] = $msg;
600
+			}
601
+			add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
602
+		}
603
+	}
604
+
605
+
606
+	/**
607
+	 * in some case it may be necessary to overwrite the existing success messages
608
+	 *
609
+	 * @return        void
610
+	 */
611
+	public static function overwrite_success()
612
+	{
613
+		self::$_espresso_notices['success'] = false;
614
+	}
615
+
616
+
617
+	/**
618
+	 * in some case it may be necessary to overwrite the existing attention messages
619
+	 *
620
+	 * @return void
621
+	 */
622
+	public static function overwrite_attention()
623
+	{
624
+		self::$_espresso_notices['attention'] = false;
625
+	}
626
+
627
+
628
+	/**
629
+	 * in some case it may be necessary to overwrite the existing error messages
630
+	 *
631
+	 * @return void
632
+	 */
633
+	public static function overwrite_errors()
634
+	{
635
+		self::$_espresso_notices['errors'] = false;
636
+	}
637
+
638
+
639
+	/**
640
+	 * @return void
641
+	 */
642
+	public static function reset_notices()
643
+	{
644
+		self::$_espresso_notices['success'] = false;
645
+		self::$_espresso_notices['attention'] = false;
646
+		self::$_espresso_notices['errors'] = false;
647
+	}
648
+
649
+
650
+	/**
651
+	 * @return int
652
+	 */
653
+	public static function has_notices()
654
+	{
655
+		$has_notices = 0;
656
+		// check for success messages
657
+		$has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])
658
+			? 3
659
+			: $has_notices;
660
+		// check for attention messages
661
+		$has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])
662
+			? 2
663
+			: $has_notices;
664
+		// check for error messages
665
+		$has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])
666
+			? 1
667
+			: $has_notices;
668
+		return $has_notices;
669
+	}
670
+
671
+
672
+	/**
673
+	 * This simply returns non formatted error notices as they were sent into the EE_Error object.
674
+	 *
675
+	 * @since 4.9.0
676
+	 * @return array
677
+	 */
678
+	public static function get_vanilla_notices()
679
+	{
680
+		return array(
681
+			'success'   => isset(self::$_espresso_notices['success'])
682
+				? self::$_espresso_notices['success']
683
+				: array(),
684
+			'attention' => isset(self::$_espresso_notices['attention'])
685
+				? self::$_espresso_notices['attention']
686
+				: array(),
687
+			'errors'    => isset(self::$_espresso_notices['errors'])
688
+				? self::$_espresso_notices['errors']
689
+				: array(),
690
+		);
691
+	}
692
+
693
+
694
+	/**
695
+	 * @return array
696
+	 * @throws InvalidArgumentException
697
+	 * @throws InvalidDataTypeException
698
+	 * @throws InvalidInterfaceException
699
+	 */
700
+	public static function getStoredNotices()
701
+	{
702
+		if ($user_id = get_current_user_id()) {
703
+			// get notices for logged in user
704
+			$notices = get_user_option(EE_Error::OPTIONS_KEY_NOTICES, $user_id);
705
+			return is_array($notices) ? $notices : array();
706
+		}
707
+		if (EE_Session::isLoadedAndActive()) {
708
+			// get notices for user currently engaged in a session
709
+			$session_data = EE_Session::instance()->get_session_data(EE_Error::OPTIONS_KEY_NOTICES);
710
+			return is_array($session_data) ? $session_data : array();
711
+		}
712
+		// get global notices and hope they apply to the current site visitor
713
+		$notices = get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
714
+		return is_array($notices) ? $notices : array();
715
+	}
716
+
717
+
718
+	/**
719
+	 * @param array $notices
720
+	 * @return bool
721
+	 * @throws InvalidArgumentException
722
+	 * @throws InvalidDataTypeException
723
+	 * @throws InvalidInterfaceException
724
+	 */
725
+	public static function storeNotices(array $notices)
726
+	{
727
+		if ($user_id = get_current_user_id()) {
728
+			// store notices for logged in user
729
+			return (bool) update_user_option(
730
+				$user_id,
731
+				EE_Error::OPTIONS_KEY_NOTICES,
732
+				$notices
733
+			);
734
+		}
735
+		if (EE_Session::isLoadedAndActive()) {
736
+			// store notices for user currently engaged in a session
737
+			return EE_Session::instance()->set_session_data(
738
+				array(EE_Error::OPTIONS_KEY_NOTICES => $notices)
739
+			);
740
+		}
741
+		// store global notices and hope they apply to the same site visitor on the next request
742
+		return update_option(EE_Error::OPTIONS_KEY_NOTICES, $notices);
743
+	}
744
+
745
+
746
+	/**
747
+	 * @return bool|TRUE
748
+	 * @throws InvalidArgumentException
749
+	 * @throws InvalidDataTypeException
750
+	 * @throws InvalidInterfaceException
751
+	 */
752
+	public static function clearNotices()
753
+	{
754
+		if ($user_id = get_current_user_id()) {
755
+			// clear notices for logged in user
756
+			return (bool) update_user_option(
757
+				$user_id,
758
+				EE_Error::OPTIONS_KEY_NOTICES,
759
+				array()
760
+			);
761
+		}
762
+		if (EE_Session::isLoadedAndActive()) {
763
+			// clear notices for user currently engaged in a session
764
+			return EE_Session::instance()->reset_data(EE_Error::OPTIONS_KEY_NOTICES);
765
+		}
766
+		// clear global notices and hope none belonged to some for some other site visitor
767
+		return update_option(EE_Error::OPTIONS_KEY_NOTICES, array());
768
+	}
769
+
770
+
771
+	/**
772
+	 * saves notices to the db for retrieval on next request
773
+	 *
774
+	 * @return void
775
+	 * @throws InvalidArgumentException
776
+	 * @throws InvalidDataTypeException
777
+	 * @throws InvalidInterfaceException
778
+	 */
779
+	public static function stashNoticesBeforeRedirect()
780
+	{
781
+		EE_Error::get_notices(false, true);
782
+	}
783
+
784
+
785
+	/**
786
+	 * compile all error or success messages into one string
787
+	 *
788
+	 * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
789
+	 * @param bool $format_output            whether or not to format the messages for display in the WP admin
790
+	 * @param bool $save_to_transient        whether or not to save notices to the db for retrieval on next request
791
+	 *                                          - ONLY do this just before redirecting
792
+	 * @param bool $remove_empty             whether or not to unset empty messages
793
+	 * @return array|string
794
+	 * @throws InvalidArgumentException
795
+	 * @throws InvalidDataTypeException
796
+	 * @throws InvalidInterfaceException
797
+	 */
798
+	public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
799
+	{
800
+		$success_messages = '';
801
+		$attention_messages = '';
802
+		$error_messages = '';
803
+		/** @var RequestInterface $request */
804
+		$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
805
+		// either save notices to the db
806
+		if ($save_to_transient || $request->requestParamIsSet('activate-selected')) {
807
+			self::$_espresso_notices = array_merge(
808
+				EE_Error::getStoredNotices(),
809
+				self::$_espresso_notices
810
+			);
811
+			EE_Error::storeNotices(self::$_espresso_notices);
812
+			return array();
813
+		}
814
+		$print_scripts = EE_Error::combineExistingAndNewNotices();
815
+		// check for success messages
816
+		if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
817
+			// combine messages
818
+			$success_messages .= implode('<br />', self::$_espresso_notices['success']);
819
+			$print_scripts = true;
820
+		}
821
+		// check for attention messages
822
+		if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
823
+			// combine messages
824
+			$attention_messages .= implode('<br />', self::$_espresso_notices['attention']);
825
+			$print_scripts = true;
826
+		}
827
+		// check for error messages
828
+		if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
829
+			$error_messages .= count(self::$_espresso_notices['errors']) > 1
830
+				? esc_html__('The following errors have occurred:', 'event_espresso')
831
+				: esc_html__('An error has occurred:', 'event_espresso');
832
+			// combine messages
833
+			$error_messages .= '<br />' . implode('<br />', self::$_espresso_notices['errors']);
834
+			$print_scripts = true;
835
+		}
836
+		if ($format_output) {
837
+			$notices = EE_Error::formatNoticesOutput(
838
+				$success_messages,
839
+				$attention_messages,
840
+				$error_messages
841
+			);
842
+		} else {
843
+			$notices = array(
844
+				'success'   => $success_messages,
845
+				'attention' => $attention_messages,
846
+				'errors'    => $error_messages,
847
+			);
848
+			if ($remove_empty) {
849
+				// remove empty notices
850
+				foreach ($notices as $type => $notice) {
851
+					if (empty($notice)) {
852
+						unset($notices[ $type ]);
853
+					}
854
+				}
855
+			}
856
+		}
857
+		if ($print_scripts) {
858
+			self::_print_scripts();
859
+		}
860
+		return $notices;
861
+	}
862
+
863
+
864
+	/**
865
+	 * @return bool
866
+	 * @throws InvalidArgumentException
867
+	 * @throws InvalidDataTypeException
868
+	 * @throws InvalidInterfaceException
869
+	 */
870
+	private static function combineExistingAndNewNotices()
871
+	{
872
+		$print_scripts = false;
873
+		// grab any notices that have been previously saved
874
+		$notices = EE_Error::getStoredNotices();
875
+		if (! empty($notices)) {
876
+			foreach ($notices as $type => $notice) {
877
+				if (is_array($notice) && ! empty($notice)) {
878
+					// make sure that existing notice type is an array
879
+					self::$_espresso_notices[ $type ] = is_array(self::$_espresso_notices[ $type ])
880
+														&& ! empty(self::$_espresso_notices[ $type ])
881
+						? self::$_espresso_notices[ $type ]
882
+						: array();
883
+					// add newly created notices to existing ones
884
+					self::$_espresso_notices[ $type ] += $notice;
885
+					$print_scripts = true;
886
+				}
887
+			}
888
+			// now clear any stored notices
889
+			EE_Error::clearNotices();
890
+		}
891
+		return $print_scripts;
892
+	}
893
+
894
+
895
+	/**
896
+	 * @param string $success_messages
897
+	 * @param string $attention_messages
898
+	 * @param string $error_messages
899
+	 * @return string
900
+	 */
901
+	private static function formatNoticesOutput($success_messages, $attention_messages, $error_messages)
902
+	{
903
+		$notices = '<div id="espresso-notices">';
904
+		$close = is_admin()
905
+			? ''
906
+			: '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"/></a>';
907
+		if ($success_messages !== '') {
908
+			$css_id = is_admin() ? 'ee-success-message' : 'espresso-notices-success';
909
+			$css_class = is_admin() ? 'updated fade' : 'success fade-away';
910
+			// showMessage( $success_messages );
911
+			$notices .= '<div id="' . $css_id . '" '
912
+						. 'class="espresso-notices ' . $css_class . '" '
913
+						. 'style="display:none;">'
914
+						. '<p>' . $success_messages . '</p>'
915
+						. $close
916
+						. '</div>';
917
+		}
918
+		if ($attention_messages !== '') {
919
+			$css_id = is_admin() ? 'ee-attention-message' : 'espresso-notices-attention';
920
+			$css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
921
+			// showMessage( $error_messages, TRUE );
922
+			$notices .= '<div id="' . $css_id . '" '
923
+						. 'class="espresso-notices ' . $css_class . '" '
924
+						. 'style="display:none;">'
925
+						. '<p>' . $attention_messages . '</p>'
926
+						. $close
927
+						. '</div>';
928
+		}
929
+		if ($error_messages !== '') {
930
+			$css_id = is_admin() ? 'ee-error-message' : 'espresso-notices-error';
931
+			$css_class = is_admin() ? 'error' : 'error fade-away';
932
+			// showMessage( $error_messages, TRUE );
933
+			$notices .= '<div id="' . $css_id . '" '
934
+						. 'class="espresso-notices ' . $css_class . '" '
935
+						. 'style="display:none;">'
936
+						. '<p>' . $error_messages . '</p>'
937
+						. $close
938
+						. '</div>';
939
+		}
940
+		$notices .= '</div>';
941
+		return $notices;
942
+	}
943
+
944
+
945
+	/**
946
+	 * _print_scripts
947
+	 *
948
+	 * @param    bool $force_print
949
+	 * @return    string
950
+	 */
951
+	private static function _print_scripts($force_print = false)
952
+	{
953
+		if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
954
+			if (wp_script_is('ee_error_js', 'registered')) {
955
+				wp_enqueue_style('espresso_default');
956
+				wp_enqueue_style('espresso_custom_css');
957
+				wp_enqueue_script('ee_error_js');
958
+			}
959
+			if (wp_script_is('ee_error_js', 'enqueued')) {
960
+				wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
961
+				return '';
962
+			}
963
+		} else {
964
+			return '
965 965
                 <script>
966 966
                 /* <![CDATA[ */
967 967
                 var ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
@@ -971,221 +971,221 @@  discard block
 block discarded – undo
971 971
                 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
972 972
                 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
973 973
             ';
974
-        }
975
-        return '';
976
-    }
977
-
978
-
979
-    /**
980
-     * @return void
981
-     */
982
-    public static function enqueue_error_scripts()
983
-    {
984
-        self::_print_scripts();
985
-    }
986
-
987
-
988
-    /**
989
-     * create error code from filepath, function name,
990
-     * and line number where exception or error was thrown
991
-     *
992
-     * @param string $file
993
-     * @param string $func
994
-     * @param string $line
995
-     * @return string
996
-     */
997
-    public static function generate_error_code($file = '', $func = '', $line = '')
998
-    {
999
-        $file = explode('.', basename($file));
1000
-        $error_code = ! empty($file[0]) ? $file[0] : '';
1001
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
1002
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
1003
-        return $error_code;
1004
-    }
1005
-
1006
-
1007
-    /**
1008
-     * write exception details to log file
1009
-     * Since 4.9.53.rc.006 this writes to the standard PHP log file, not EE's custom log file
1010
-     *
1011
-     * @param int   $time
1012
-     * @param array $ex
1013
-     * @param bool  $clear
1014
-     * @return void
1015
-     */
1016
-    public function write_to_error_log($time = 0, $ex = array(), $clear = false)
1017
-    {
1018
-        if (empty($ex)) {
1019
-            return;
1020
-        }
1021
-        if (! $time) {
1022
-            $time = time();
1023
-        }
1024
-        $exception_log = '----------------------------------------------------------------------------------------'
1025
-                         . PHP_EOL;
1026
-        $exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1027
-        $exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1028
-        $exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1029
-        $exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1030
-        $exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1031
-        $exception_log .= 'Stack trace: ' . PHP_EOL;
1032
-        $exception_log .= $ex['string'] . PHP_EOL;
1033
-        $exception_log .= '----------------------------------------------------------------------------------------'
1034
-                          . PHP_EOL;
1035
-        try {
1036
-            error_log($exception_log);
1037
-        } catch (EE_Error $e) {
1038
-            EE_Error::add_error(
1039
-                sprintf(
1040
-                    esc_html__(
1041
-                        'Event Espresso error logging could not be setup because: %s',
1042
-                        'event_espresso'
1043
-                    ),
1044
-                    $e->getMessage()
1045
-                )
1046
-            );
1047
-        }
1048
-    }
1049
-
1050
-
1051
-    /**
1052
-     * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1053
-     * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1054
-     * but the code execution is done in a manner that could lead to unexpected results
1055
-     * (i.e. running to early, or too late in WP or EE loading process).
1056
-     * A good test for knowing whether to use this method is:
1057
-     * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1058
-     * Yes -> use EE_Error::add_error() or throw new EE_Error()
1059
-     * 2. If this is loaded before something else, it won't break anything,
1060
-     * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1061
-     *
1062
-     * @uses   constant WP_DEBUG test if wp_debug is on or not
1063
-     * @param string $function      The function that was called
1064
-     * @param string $message       A message explaining what has been done incorrectly
1065
-     * @param string $version       The version of Event Espresso where the error was added
1066
-     * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1067
-     *                              for a deprecated function. This allows deprecation to occur during one version,
1068
-     *                              but not have any notices appear until a later version. This allows developers
1069
-     *                              extra time to update their code before notices appear.
1070
-     * @param int    $error_type
1071
-     */
1072
-    public static function doing_it_wrong(
1073
-        $function,
1074
-        $message,
1075
-        $version,
1076
-        $applies_when = '',
1077
-        $error_type = null
1078
-    ) {
1079
-        if (defined('WP_DEBUG') && WP_DEBUG) {
1080
-            EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1081
-        }
1082
-    }
1083
-
1084
-
1085
-    /**
1086
-     * Like get_notices, but returns an array of all the notices of the given type.
1087
-     *
1088
-     * @return array {
1089
-     * @type array $success   all the success messages
1090
-     * @type array $errors    all the error messages
1091
-     * @type array $attention all the attention messages
1092
-     * }
1093
-     */
1094
-    public static function get_raw_notices()
1095
-    {
1096
-        return self::$_espresso_notices;
1097
-    }
1098
-
1099
-
1100
-    /**
1101
-     * @deprecated 4.9.27
1102
-     * @param string $pan_name     the name, or key of the Persistent Admin Notice to be stored
1103
-     * @param string $pan_message  the message to be stored persistently until dismissed
1104
-     * @param bool   $force_update allows one to enforce the reappearance of a persistent message.
1105
-     * @return void
1106
-     * @throws InvalidDataTypeException
1107
-     */
1108
-    public static function add_persistent_admin_notice($pan_name, $pan_message, $force_update = false)
1109
-    {
1110
-        new PersistentAdminNotice(
1111
-            $pan_name,
1112
-            $pan_message,
1113
-            $force_update
1114
-        );
1115
-        EE_Error::doing_it_wrong(
1116
-            __METHOD__,
1117
-            sprintf(
1118
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1119
-                '\EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
1120
-            ),
1121
-            '4.9.27'
1122
-        );
1123
-    }
1124
-
1125
-
1126
-    /**
1127
-     * @deprecated 4.9.27
1128
-     * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
1129
-     * @param bool   $purge
1130
-     * @param bool   $return
1131
-     * @throws DomainException
1132
-     * @throws InvalidInterfaceException
1133
-     * @throws InvalidDataTypeException
1134
-     * @throws ServiceNotFoundException
1135
-     * @throws InvalidArgumentException
1136
-     */
1137
-    public static function dismiss_persistent_admin_notice($pan_name, $purge = false, $return = false)
1138
-    {
1139
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
1140
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
1141
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1142
-        );
1143
-        $persistent_admin_notice_manager->dismissNotice($pan_name, $purge, $return);
1144
-        EE_Error::doing_it_wrong(
1145
-            __METHOD__,
1146
-            sprintf(
1147
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1148
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1149
-            ),
1150
-            '4.9.27'
1151
-        );
1152
-    }
1153
-
1154
-
1155
-    /**
1156
-     * @deprecated 4.9.27
1157
-     * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
1158
-     * @param  string $pan_message the message to be stored persistently until dismissed
1159
-     * @param  string $return_url  URL to go back to after nag notice is dismissed
1160
-     */
1161
-    public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
1162
-    {
1163
-        EE_Error::doing_it_wrong(
1164
-            __METHOD__,
1165
-            sprintf(
1166
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1167
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1168
-            ),
1169
-            '4.9.27'
1170
-        );
1171
-    }
1172
-
1173
-
1174
-    /**
1175
-     * @deprecated 4.9.27
1176
-     * @param string $return_url
1177
-     */
1178
-    public static function get_persistent_admin_notices($return_url = '')
1179
-    {
1180
-        EE_Error::doing_it_wrong(
1181
-            __METHOD__,
1182
-            sprintf(
1183
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1184
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1185
-            ),
1186
-            '4.9.27'
1187
-        );
1188
-    }
974
+		}
975
+		return '';
976
+	}
977
+
978
+
979
+	/**
980
+	 * @return void
981
+	 */
982
+	public static function enqueue_error_scripts()
983
+	{
984
+		self::_print_scripts();
985
+	}
986
+
987
+
988
+	/**
989
+	 * create error code from filepath, function name,
990
+	 * and line number where exception or error was thrown
991
+	 *
992
+	 * @param string $file
993
+	 * @param string $func
994
+	 * @param string $line
995
+	 * @return string
996
+	 */
997
+	public static function generate_error_code($file = '', $func = '', $line = '')
998
+	{
999
+		$file = explode('.', basename($file));
1000
+		$error_code = ! empty($file[0]) ? $file[0] : '';
1001
+		$error_code .= ! empty($func) ? ' - ' . $func : '';
1002
+		$error_code .= ! empty($line) ? ' - ' . $line : '';
1003
+		return $error_code;
1004
+	}
1005
+
1006
+
1007
+	/**
1008
+	 * write exception details to log file
1009
+	 * Since 4.9.53.rc.006 this writes to the standard PHP log file, not EE's custom log file
1010
+	 *
1011
+	 * @param int   $time
1012
+	 * @param array $ex
1013
+	 * @param bool  $clear
1014
+	 * @return void
1015
+	 */
1016
+	public function write_to_error_log($time = 0, $ex = array(), $clear = false)
1017
+	{
1018
+		if (empty($ex)) {
1019
+			return;
1020
+		}
1021
+		if (! $time) {
1022
+			$time = time();
1023
+		}
1024
+		$exception_log = '----------------------------------------------------------------------------------------'
1025
+						 . PHP_EOL;
1026
+		$exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1027
+		$exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1028
+		$exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1029
+		$exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1030
+		$exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1031
+		$exception_log .= 'Stack trace: ' . PHP_EOL;
1032
+		$exception_log .= $ex['string'] . PHP_EOL;
1033
+		$exception_log .= '----------------------------------------------------------------------------------------'
1034
+						  . PHP_EOL;
1035
+		try {
1036
+			error_log($exception_log);
1037
+		} catch (EE_Error $e) {
1038
+			EE_Error::add_error(
1039
+				sprintf(
1040
+					esc_html__(
1041
+						'Event Espresso error logging could not be setup because: %s',
1042
+						'event_espresso'
1043
+					),
1044
+					$e->getMessage()
1045
+				)
1046
+			);
1047
+		}
1048
+	}
1049
+
1050
+
1051
+	/**
1052
+	 * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1053
+	 * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1054
+	 * but the code execution is done in a manner that could lead to unexpected results
1055
+	 * (i.e. running to early, or too late in WP or EE loading process).
1056
+	 * A good test for knowing whether to use this method is:
1057
+	 * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1058
+	 * Yes -> use EE_Error::add_error() or throw new EE_Error()
1059
+	 * 2. If this is loaded before something else, it won't break anything,
1060
+	 * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1061
+	 *
1062
+	 * @uses   constant WP_DEBUG test if wp_debug is on or not
1063
+	 * @param string $function      The function that was called
1064
+	 * @param string $message       A message explaining what has been done incorrectly
1065
+	 * @param string $version       The version of Event Espresso where the error was added
1066
+	 * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1067
+	 *                              for a deprecated function. This allows deprecation to occur during one version,
1068
+	 *                              but not have any notices appear until a later version. This allows developers
1069
+	 *                              extra time to update their code before notices appear.
1070
+	 * @param int    $error_type
1071
+	 */
1072
+	public static function doing_it_wrong(
1073
+		$function,
1074
+		$message,
1075
+		$version,
1076
+		$applies_when = '',
1077
+		$error_type = null
1078
+	) {
1079
+		if (defined('WP_DEBUG') && WP_DEBUG) {
1080
+			EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1081
+		}
1082
+	}
1083
+
1084
+
1085
+	/**
1086
+	 * Like get_notices, but returns an array of all the notices of the given type.
1087
+	 *
1088
+	 * @return array {
1089
+	 * @type array $success   all the success messages
1090
+	 * @type array $errors    all the error messages
1091
+	 * @type array $attention all the attention messages
1092
+	 * }
1093
+	 */
1094
+	public static function get_raw_notices()
1095
+	{
1096
+		return self::$_espresso_notices;
1097
+	}
1098
+
1099
+
1100
+	/**
1101
+	 * @deprecated 4.9.27
1102
+	 * @param string $pan_name     the name, or key of the Persistent Admin Notice to be stored
1103
+	 * @param string $pan_message  the message to be stored persistently until dismissed
1104
+	 * @param bool   $force_update allows one to enforce the reappearance of a persistent message.
1105
+	 * @return void
1106
+	 * @throws InvalidDataTypeException
1107
+	 */
1108
+	public static function add_persistent_admin_notice($pan_name, $pan_message, $force_update = false)
1109
+	{
1110
+		new PersistentAdminNotice(
1111
+			$pan_name,
1112
+			$pan_message,
1113
+			$force_update
1114
+		);
1115
+		EE_Error::doing_it_wrong(
1116
+			__METHOD__,
1117
+			sprintf(
1118
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1119
+				'\EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
1120
+			),
1121
+			'4.9.27'
1122
+		);
1123
+	}
1124
+
1125
+
1126
+	/**
1127
+	 * @deprecated 4.9.27
1128
+	 * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
1129
+	 * @param bool   $purge
1130
+	 * @param bool   $return
1131
+	 * @throws DomainException
1132
+	 * @throws InvalidInterfaceException
1133
+	 * @throws InvalidDataTypeException
1134
+	 * @throws ServiceNotFoundException
1135
+	 * @throws InvalidArgumentException
1136
+	 */
1137
+	public static function dismiss_persistent_admin_notice($pan_name, $purge = false, $return = false)
1138
+	{
1139
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
1140
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
1141
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1142
+		);
1143
+		$persistent_admin_notice_manager->dismissNotice($pan_name, $purge, $return);
1144
+		EE_Error::doing_it_wrong(
1145
+			__METHOD__,
1146
+			sprintf(
1147
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1148
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1149
+			),
1150
+			'4.9.27'
1151
+		);
1152
+	}
1153
+
1154
+
1155
+	/**
1156
+	 * @deprecated 4.9.27
1157
+	 * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
1158
+	 * @param  string $pan_message the message to be stored persistently until dismissed
1159
+	 * @param  string $return_url  URL to go back to after nag notice is dismissed
1160
+	 */
1161
+	public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
1162
+	{
1163
+		EE_Error::doing_it_wrong(
1164
+			__METHOD__,
1165
+			sprintf(
1166
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1167
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1168
+			),
1169
+			'4.9.27'
1170
+		);
1171
+	}
1172
+
1173
+
1174
+	/**
1175
+	 * @deprecated 4.9.27
1176
+	 * @param string $return_url
1177
+	 */
1178
+	public static function get_persistent_admin_notices($return_url = '')
1179
+	{
1180
+		EE_Error::doing_it_wrong(
1181
+			__METHOD__,
1182
+			sprintf(
1183
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1184
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1185
+			),
1186
+			'4.9.27'
1187
+		);
1188
+	}
1189 1189
 }
1190 1190
 
1191 1191
 // end of Class EE_Exceptions
@@ -1198,26 +1198,26 @@  discard block
 block discarded – undo
1198 1198
  */
1199 1199
 function espresso_error_enqueue_scripts()
1200 1200
 {
1201
-    // js for error handling
1202
-    wp_register_script(
1203
-        'espresso_core',
1204
-        EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1205
-        array('jquery'),
1206
-        EVENT_ESPRESSO_VERSION
1207
-    );
1208
-    wp_register_script(
1209
-        'ee_error_js',
1210
-        EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1211
-        array('espresso_core'),
1212
-        EVENT_ESPRESSO_VERSION
1213
-    );
1214
-    wp_localize_script('ee_error_js', 'ee_settings', ['wp_debug' => WP_DEBUG]);
1201
+	// js for error handling
1202
+	wp_register_script(
1203
+		'espresso_core',
1204
+		EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1205
+		array('jquery'),
1206
+		EVENT_ESPRESSO_VERSION
1207
+	);
1208
+	wp_register_script(
1209
+		'ee_error_js',
1210
+		EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1211
+		array('espresso_core'),
1212
+		EVENT_ESPRESSO_VERSION
1213
+	);
1214
+	wp_localize_script('ee_error_js', 'ee_settings', ['wp_debug' => WP_DEBUG]);
1215 1215
 }
1216 1216
 
1217 1217
 if (is_admin()) {
1218
-    add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 5);
1218
+	add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 5);
1219 1219
 } else {
1220
-    add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 5);
1220
+	add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 5);
1221 1221
 }
1222 1222
 
1223 1223
 
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -101,14 +101,14 @@  discard block
 block discarded – undo
101 101
             default:
102 102
                 $to = get_option('admin_email');
103 103
         }
104
-        $subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
104
+        $subject = $type.' '.$message.' in '.EVENT_ESPRESSO_VERSION.' on '.site_url();
105 105
         $msg = EE_Error::_format_error($type, $message, $file, $line);
106 106
         if (function_exists('wp_mail')) {
107 107
             add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
108 108
             wp_mail($to, $subject, $msg);
109 109
         }
110 110
         echo '<div id="message" class="espresso-notices error"><p>';
111
-        echo wp_kses($type . ': ' . $message . '<br />' . $file . ' line ' . $line, AllowedTags::getWithFormTags());
111
+        echo wp_kses($type.': '.$message.'<br />'.$file.' line '.$line, AllowedTags::getWithFormTags());
112 112
         echo '<br /></p></div>';
113 113
     }
114 114
 
@@ -224,13 +224,13 @@  discard block
 block discarded – undo
224 224
         $msg = WP_DEBUG ? $dev_msg : $user_msg;
225 225
         // add details to _all_exceptions array
226 226
         $x_time = time();
227
-        self::$_all_exceptions[ $x_time ]['name'] = get_class($this);
228
-        self::$_all_exceptions[ $x_time ]['file'] = $this->getFile();
229
-        self::$_all_exceptions[ $x_time ]['line'] = $this->getLine();
230
-        self::$_all_exceptions[ $x_time ]['msg'] = $msg;
231
-        self::$_all_exceptions[ $x_time ]['code'] = $this->getCode();
232
-        self::$_all_exceptions[ $x_time ]['trace'] = $this->getTrace();
233
-        self::$_all_exceptions[ $x_time ]['string'] = $this->getTraceAsString();
227
+        self::$_all_exceptions[$x_time]['name'] = get_class($this);
228
+        self::$_all_exceptions[$x_time]['file'] = $this->getFile();
229
+        self::$_all_exceptions[$x_time]['line'] = $this->getLine();
230
+        self::$_all_exceptions[$x_time]['msg'] = $msg;
231
+        self::$_all_exceptions[$x_time]['code'] = $this->getCode();
232
+        self::$_all_exceptions[$x_time]['trace'] = $this->getTrace();
233
+        self::$_all_exceptions[$x_time]['string'] = $this->getTraceAsString();
234 234
         self::$_error_count++;
235 235
         // add_action( 'shutdown', array( $this, 'display_errors' ));
236 236
         $this->display_errors();
@@ -247,8 +247,8 @@  discard block
 block discarded – undo
247 247
      */
248 248
     public static function has_error($check_stored = false, $type_to_check = 'errors')
249 249
     {
250
-        $has_error = isset(self::$_espresso_notices[ $type_to_check ])
251
-                     && ! empty(self::$_espresso_notices[ $type_to_check ])
250
+        $has_error = isset(self::$_espresso_notices[$type_to_check])
251
+                     && ! empty(self::$_espresso_notices[$type_to_check])
252 252
             ? true
253 253
             : false;
254 254
         if ($check_stored && ! $has_error) {
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
         $trace_details = '';
273 273
         $output = '
274 274
         <div id="ee-error-message" class="error">';
275
-        if (! WP_DEBUG) {
275
+        if ( ! WP_DEBUG) {
276 276
             $output .= '
277 277
 	        <p>';
278 278
         }
@@ -331,14 +331,14 @@  discard block
 block discarded – undo
331 331
                     $class_dsply = ! empty($class) ? $class : '&nbsp;';
332 332
                     $type_dsply = ! empty($type) ? $type : '&nbsp;';
333 333
                     $function_dsply = ! empty($function) ? $function : '&nbsp;';
334
-                    $args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
334
+                    $args_dsply = ! empty($args) ? '( '.$args.' )' : '';
335 335
                     $trace_details .= '
336 336
 					<tr>
337
-						<td align="right" class="' . $zebra . '">' . $nmbr_dsply . '</td>
338
-						<td align="right" class="' . $zebra . '">' . $line_dsply . '</td>
339
-						<td align="left" class="' . $zebra . '">' . $file_dsply . '</td>
340
-						<td align="left" class="' . $zebra . '">' . $class_dsply . '</td>
341
-						<td align="left" class="' . $zebra . '">' . $type_dsply . $function_dsply . $args_dsply . '</td>
337
+						<td align="right" class="' . $zebra.'">'.$nmbr_dsply.'</td>
338
+						<td align="right" class="' . $zebra.'">'.$line_dsply.'</td>
339
+						<td align="left" class="' . $zebra.'">'.$file_dsply.'</td>
340
+						<td align="left" class="' . $zebra.'">'.$class_dsply.'</td>
341
+						<td align="left" class="' . $zebra.'">'.$type_dsply.$function_dsply.$args_dsply.'</td>
342 342
 					</tr>';
343 343
                 }
344 344
                 $trace_details .= '
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
             }
348 348
             $ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
349 349
             // add generic non-identifying messages for non-privileged users
350
-            if (! WP_DEBUG) {
350
+            if ( ! WP_DEBUG) {
351 351
                 $output .= '<span class="ee-error-user-msg-spn">'
352 352
                            . trim($ex['msg'])
353 353
                            . '</span> &nbsp; <sup>'
@@ -389,14 +389,14 @@  discard block
 block discarded – undo
389 389
                            . '-dv" class="ee-error-trace-dv" style="display: none;">
390 390
 				'
391 391
                            . $trace_details;
392
-                if (! empty($class)) {
392
+                if ( ! empty($class)) {
393 393
                     $output .= '
394 394
 				<div style="padding:3px; margin:0 0 1em; border:1px solid #666; background:#fff; border-radius:3px;">
395 395
 					<div style="padding:1em 2em; border:1px solid #666; background:#f9f9f9;">
396 396
 						<h3>Class Details</h3>';
397 397
                     $a = new ReflectionClass($class);
398 398
                     $output .= '
399
-						<pre>' . $a . '</pre>
399
+						<pre>' . $a.'</pre>
400 400
 					</div>
401 401
 				</div>';
402 402
                 }
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
         }
410 410
         // remove last linebreak
411 411
         $output = substr($output, 0, -6);
412
-        if (! WP_DEBUG) {
412
+        if ( ! WP_DEBUG) {
413 413
             $output .= '
414 414
 	        </p>';
415 415
         }
@@ -435,20 +435,20 @@  discard block
 block discarded – undo
435 435
     private function _convert_args_to_string($arguments = array(), $array = false)
436 436
     {
437 437
         $arg_string = '';
438
-        if (! empty($arguments)) {
438
+        if ( ! empty($arguments)) {
439 439
             $args = array();
440 440
             foreach ($arguments as $arg) {
441
-                if (! empty($arg)) {
441
+                if ( ! empty($arg)) {
442 442
                     if (is_string($arg)) {
443
-                        $args[] = " '" . $arg . "'";
443
+                        $args[] = " '".$arg."'";
444 444
                     } elseif (is_array($arg)) {
445
-                        $args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
445
+                        $args[] = 'ARRAY('.$this->_convert_args_to_string($arg, true);
446 446
                     } elseif ($arg === null) {
447 447
                         $args[] = ' NULL';
448 448
                     } elseif (is_bool($arg)) {
449 449
                         $args[] = ($arg) ? ' TRUE' : ' FALSE';
450 450
                     } elseif (is_object($arg)) {
451
-                        $args[] = ' OBJECT ' . get_class($arg);
451
+                        $args[] = ' OBJECT '.get_class($arg);
452 452
                     } elseif (is_resource($arg)) {
453 453
                         $args[] = get_resource_type($arg);
454 454
                     } else {
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
     {
547 547
         if (empty($msg)) {
548 548
             EE_Error::doing_it_wrong(
549
-                'EE_Error::add_' . $type . '()',
549
+                'EE_Error::add_'.$type.'()',
550 550
                 sprintf(
551 551
                     esc_html__(
552 552
                         'Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
@@ -586,17 +586,17 @@  discard block
 block discarded – undo
586 586
         do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
587 587
         $msg = WP_DEBUG ? $dev_msg : $user_msg;
588 588
         // add notice if message exists
589
-        if (! empty($msg)) {
589
+        if ( ! empty($msg)) {
590 590
             // get error code
591 591
             $notice_code = EE_Error::generate_error_code($file, $func, $line);
592 592
             if (WP_DEBUG && $type === 'errors') {
593
-                $msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
593
+                $msg .= '<br/><span class="tiny-text">'.$notice_code.'</span>';
594 594
             }
595 595
             // add notice. Index by code if it's not blank
596 596
             if ($notice_code) {
597
-                self::$_espresso_notices[ $type ][ $notice_code ] = $msg;
597
+                self::$_espresso_notices[$type][$notice_code] = $msg;
598 598
             } else {
599
-                self::$_espresso_notices[ $type ][] = $msg;
599
+                self::$_espresso_notices[$type][] = $msg;
600 600
             }
601 601
             add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
602 602
         }
@@ -830,7 +830,7 @@  discard block
 block discarded – undo
830 830
                 ? esc_html__('The following errors have occurred:', 'event_espresso')
831 831
                 : esc_html__('An error has occurred:', 'event_espresso');
832 832
             // combine messages
833
-            $error_messages .= '<br />' . implode('<br />', self::$_espresso_notices['errors']);
833
+            $error_messages .= '<br />'.implode('<br />', self::$_espresso_notices['errors']);
834 834
             $print_scripts = true;
835 835
         }
836 836
         if ($format_output) {
@@ -849,7 +849,7 @@  discard block
 block discarded – undo
849 849
                 // remove empty notices
850 850
                 foreach ($notices as $type => $notice) {
851 851
                     if (empty($notice)) {
852
-                        unset($notices[ $type ]);
852
+                        unset($notices[$type]);
853 853
                     }
854 854
                 }
855 855
             }
@@ -872,16 +872,16 @@  discard block
 block discarded – undo
872 872
         $print_scripts = false;
873 873
         // grab any notices that have been previously saved
874 874
         $notices = EE_Error::getStoredNotices();
875
-        if (! empty($notices)) {
875
+        if ( ! empty($notices)) {
876 876
             foreach ($notices as $type => $notice) {
877 877
                 if (is_array($notice) && ! empty($notice)) {
878 878
                     // make sure that existing notice type is an array
879
-                    self::$_espresso_notices[ $type ] = is_array(self::$_espresso_notices[ $type ])
880
-                                                        && ! empty(self::$_espresso_notices[ $type ])
881
-                        ? self::$_espresso_notices[ $type ]
879
+                    self::$_espresso_notices[$type] = is_array(self::$_espresso_notices[$type])
880
+                                                        && ! empty(self::$_espresso_notices[$type])
881
+                        ? self::$_espresso_notices[$type]
882 882
                         : array();
883 883
                     // add newly created notices to existing ones
884
-                    self::$_espresso_notices[ $type ] += $notice;
884
+                    self::$_espresso_notices[$type] += $notice;
885 885
                     $print_scripts = true;
886 886
                 }
887 887
             }
@@ -908,10 +908,10 @@  discard block
 block discarded – undo
908 908
             $css_id = is_admin() ? 'ee-success-message' : 'espresso-notices-success';
909 909
             $css_class = is_admin() ? 'updated fade' : 'success fade-away';
910 910
             // showMessage( $success_messages );
911
-            $notices .= '<div id="' . $css_id . '" '
912
-                        . 'class="espresso-notices ' . $css_class . '" '
911
+            $notices .= '<div id="'.$css_id.'" '
912
+                        . 'class="espresso-notices '.$css_class.'" '
913 913
                         . 'style="display:none;">'
914
-                        . '<p>' . $success_messages . '</p>'
914
+                        . '<p>'.$success_messages.'</p>'
915 915
                         . $close
916 916
                         . '</div>';
917 917
         }
@@ -919,10 +919,10 @@  discard block
 block discarded – undo
919 919
             $css_id = is_admin() ? 'ee-attention-message' : 'espresso-notices-attention';
920 920
             $css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
921 921
             // showMessage( $error_messages, TRUE );
922
-            $notices .= '<div id="' . $css_id . '" '
923
-                        . 'class="espresso-notices ' . $css_class . '" '
922
+            $notices .= '<div id="'.$css_id.'" '
923
+                        . 'class="espresso-notices '.$css_class.'" '
924 924
                         . 'style="display:none;">'
925
-                        . '<p>' . $attention_messages . '</p>'
925
+                        . '<p>'.$attention_messages.'</p>'
926 926
                         . $close
927 927
                         . '</div>';
928 928
         }
@@ -930,10 +930,10 @@  discard block
 block discarded – undo
930 930
             $css_id = is_admin() ? 'ee-error-message' : 'espresso-notices-error';
931 931
             $css_class = is_admin() ? 'error' : 'error fade-away';
932 932
             // showMessage( $error_messages, TRUE );
933
-            $notices .= '<div id="' . $css_id . '" '
934
-                        . 'class="espresso-notices ' . $css_class . '" '
933
+            $notices .= '<div id="'.$css_id.'" '
934
+                        . 'class="espresso-notices '.$css_class.'" '
935 935
                         . 'style="display:none;">'
936
-                        . '<p>' . $error_messages . '</p>'
936
+                        . '<p>'.$error_messages.'</p>'
937 937
                         . $close
938 938
                         . '</div>';
939 939
         }
@@ -950,7 +950,7 @@  discard block
 block discarded – undo
950 950
      */
951 951
     private static function _print_scripts($force_print = false)
952 952
     {
953
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
953
+        if ( ! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
954 954
             if (wp_script_is('ee_error_js', 'registered')) {
955 955
                 wp_enqueue_style('espresso_default');
956 956
                 wp_enqueue_style('espresso_custom_css');
@@ -964,12 +964,12 @@  discard block
 block discarded – undo
964 964
             return '
965 965
                 <script>
966 966
                 /* <![CDATA[ */
967
-                var ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
967
+                var ee_settings = {"wp_debug":"' . WP_DEBUG.'"};
968 968
                 /* ]]> */
969 969
                 </script>
970
-                <script src="' . includes_url() . 'js/jquery/jquery.js" type="text/javascript"></script>
971
-                <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
972
-                <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
970
+                <script src="' . includes_url().'js/jquery/jquery.js" type="text/javascript"></script>
971
+                <script src="' . EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js'.'?ver='.espresso_version().'" type="text/javascript"></script>
972
+                <script src="' . EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js'.'?ver='.espresso_version().'" type="text/javascript"></script>
973 973
             ';
974 974
         }
975 975
         return '';
@@ -998,8 +998,8 @@  discard block
 block discarded – undo
998 998
     {
999 999
         $file = explode('.', basename($file));
1000 1000
         $error_code = ! empty($file[0]) ? $file[0] : '';
1001
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
1002
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
1001
+        $error_code .= ! empty($func) ? ' - '.$func : '';
1002
+        $error_code .= ! empty($line) ? ' - '.$line : '';
1003 1003
         return $error_code;
1004 1004
     }
1005 1005
 
@@ -1018,18 +1018,18 @@  discard block
 block discarded – undo
1018 1018
         if (empty($ex)) {
1019 1019
             return;
1020 1020
         }
1021
-        if (! $time) {
1021
+        if ( ! $time) {
1022 1022
             $time = time();
1023 1023
         }
1024 1024
         $exception_log = '----------------------------------------------------------------------------------------'
1025 1025
                          . PHP_EOL;
1026
-        $exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1027
-        $exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1028
-        $exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1029
-        $exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1030
-        $exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1031
-        $exception_log .= 'Stack trace: ' . PHP_EOL;
1032
-        $exception_log .= $ex['string'] . PHP_EOL;
1026
+        $exception_log .= '['.date('Y-m-d H:i:s', $time).']  Exception Details'.PHP_EOL;
1027
+        $exception_log .= 'Message: '.$ex['msg'].PHP_EOL;
1028
+        $exception_log .= 'Code: '.$ex['code'].PHP_EOL;
1029
+        $exception_log .= 'File: '.$ex['file'].PHP_EOL;
1030
+        $exception_log .= 'Line No: '.$ex['line'].PHP_EOL;
1031
+        $exception_log .= 'Stack trace: '.PHP_EOL;
1032
+        $exception_log .= $ex['string'].PHP_EOL;
1033 1033
         $exception_log .= '----------------------------------------------------------------------------------------'
1034 1034
                           . PHP_EOL;
1035 1035
         try {
@@ -1201,13 +1201,13 @@  discard block
 block discarded – undo
1201 1201
     // js for error handling
1202 1202
     wp_register_script(
1203 1203
         'espresso_core',
1204
-        EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1204
+        EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
1205 1205
         array('jquery'),
1206 1206
         EVENT_ESPRESSO_VERSION
1207 1207
     );
1208 1208
     wp_register_script(
1209 1209
         'ee_error_js',
1210
-        EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1210
+        EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js',
1211 1211
         array('espresso_core'),
1212 1212
         EVENT_ESPRESSO_VERSION
1213 1213
     );
Please login to merge, or discard this patch.
modules/single_page_checkout/inc/EE_SPCO_JSON_Response.php 1 patch
Indentation   +397 added lines, -397 removed lines patch added patch discarded remove patch
@@ -15,401 +15,401 @@
 block discarded – undo
15 15
 class EE_SPCO_JSON_Response
16 16
 {
17 17
 
18
-    /**
19
-     * @var string
20
-     */
21
-    protected $_errors = '';
22
-
23
-    /**
24
-     * @var string
25
-     */
26
-    protected $_unexpected_errors = '';
27
-
28
-    /**
29
-     * @var string
30
-     */
31
-    protected $_attention = '';
32
-
33
-    /**
34
-     * @var string
35
-     */
36
-    protected $_success = '';
37
-
38
-    /**
39
-     * @var string
40
-     */
41
-    protected $_plz_select_method_of_payment = '';
42
-
43
-    /**
44
-     * @var string
45
-     */
46
-    protected $_redirect_url = '';
47
-
48
-    /**
49
-     * @var string
50
-     */
51
-    protected $_registration_time_limit = '';
52
-
53
-    /**
54
-     * @var string
55
-     */
56
-    protected $_redirect_form = '';
57
-
58
-    /**
59
-     * @var string
60
-     */
61
-    protected $_reg_step_html = '';
62
-
63
-    /**
64
-     * @var string
65
-     */
66
-    protected $_method_of_payment = '';
67
-
68
-    /**
69
-     * @var float
70
-     */
71
-    protected $_payment_amount;
72
-
73
-    /**
74
-     * @var array
75
-     */
76
-    protected $_return_data = array();
77
-
78
-
79
-    /**
80
-     * @var array
81
-     */
82
-    protected $_validation_rules = array();
83
-
84
-
85
-    /**
86
-     *    class constructor
87
-     */
88
-    public function __construct()
89
-    {
90
-    }
91
-
92
-
93
-    /**
94
-     *    __toString
95
-     *
96
-     *        allows you to simply echo or print an EE_SPCO_JSON_Response object to produce a  JSON encoded string
97
-     *
98
-     * @access    public
99
-     * @return    string
100
-     */
101
-    public function __toString()
102
-    {
103
-        $JSON_response = array();
104
-        // grab notices
105
-        $notices = EE_Error::get_notices(false);
106
-        $this->set_attention(isset($notices['attention']) ? $notices['attention'] : '');
107
-        $this->set_errors(isset($notices['errors']) ? $notices['errors'] : '');
108
-        $this->set_success(isset($notices['success']) ? $notices['success'] : '');
109
-        // add notices to JSON response, but only if they exist
110
-        if ($this->attention()) {
111
-            $JSON_response['attention'] = $this->attention();
112
-        }
113
-        if ($this->errors()) {
114
-            $JSON_response['errors'] = $this->errors();
115
-        }
116
-        if ($this->unexpected_errors()) {
117
-            $JSON_response['unexpected_errors'] = $this->unexpected_errors();
118
-        }
119
-        if ($this->success()) {
120
-            $JSON_response['success'] = $this->success();
121
-        }
122
-        // but if NO notices are set... at least set the "success" as a key so that the JS knows everything worked
123
-        if (! isset($JSON_response['attention']) && ! isset($JSON_response['errors']) && ! isset($JSON_response['success'])) {
124
-            $JSON_response['success'] = null;
125
-        }
126
-        // set redirect_url, IF it exists
127
-        if ($this->redirect_url()) {
128
-            $JSON_response['redirect_url'] = $this->redirect_url();
129
-        }
130
-        // set registration_time_limit, IF it exists
131
-        if ($this->registration_time_limit()) {
132
-            $JSON_response['registration_time_limit'] = $this->registration_time_limit();
133
-        }
134
-        // set payment_amount, IF it exists
135
-        if ($this->payment_amount() !== null) {
136
-            $JSON_response['payment_amount'] = $this->payment_amount();
137
-        }
138
-        // grab generic return data
139
-        $return_data = $this->return_data();
140
-        // add billing form validation rules
141
-        if ($this->validation_rules()) {
142
-            $return_data['validation_rules'] = $this->validation_rules();
143
-        }
144
-        // set reg_step_html, IF it exists
145
-        if ($this->reg_step_html()) {
146
-            $return_data['reg_step_html'] = $this->reg_step_html();
147
-        }
148
-        // set method of payment, IF it exists
149
-        if ($this->method_of_payment()) {
150
-            $return_data['method_of_payment'] = $this->method_of_payment();
151
-        }
152
-        // set "plz_select_method_of_payment" message, IF it exists
153
-        if ($this->plz_select_method_of_payment()) {
154
-            $return_data['plz_select_method_of_payment'] = $this->plz_select_method_of_payment();
155
-        }
156
-        // set redirect_form, IF it exists
157
-        if ($this->redirect_form()) {
158
-            $return_data['redirect_form'] = $this->redirect_form();
159
-        }
160
-        // and finally, add return_data array to main JSON response array, IF it contains anything
161
-        // why did we add some of the above properties to the return data array?
162
-        // because it is easier and cleaner in the Javascript to deal with this way
163
-        if (! empty($return_data)) {
164
-            $JSON_response['return_data'] = $return_data;
165
-        }
166
-        // filter final array
167
-        $JSON_response = apply_filters('FHEE__EE_SPCO_JSON_Response___toString__JSON_response', $JSON_response);
168
-        // return encoded array
169
-        return (string) wp_json_encode($JSON_response);
170
-    }
171
-
172
-
173
-    /**
174
-     * @param string $attention
175
-     */
176
-    public function set_attention($attention)
177
-    {
178
-        $this->_attention = $attention;
179
-    }
180
-
181
-
182
-    /**
183
-     * @return string
184
-     */
185
-    public function attention()
186
-    {
187
-        return $this->_attention;
188
-    }
189
-
190
-
191
-    /**
192
-     * @param string $errors
193
-     */
194
-    public function set_errors($errors)
195
-    {
196
-        $this->_errors = $errors;
197
-    }
198
-
199
-
200
-    /**
201
-     * @return string
202
-     */
203
-    public function errors()
204
-    {
205
-        return $this->_errors;
206
-    }
207
-
208
-
209
-    /**
210
-     * @return string
211
-     */
212
-    public function unexpected_errors()
213
-    {
214
-        return $this->_unexpected_errors;
215
-    }
216
-
217
-
218
-    /**
219
-     * @param string $unexpected_errors
220
-     */
221
-    public function set_unexpected_errors($unexpected_errors)
222
-    {
223
-        $this->_unexpected_errors = $unexpected_errors;
224
-    }
225
-
226
-
227
-    /**
228
-     * @param string $success
229
-     */
230
-    public function set_success($success)
231
-    {
232
-        $this->_success = $success;
233
-    }
234
-
235
-
236
-    /**
237
-     * @return string
238
-     */
239
-    public function success()
240
-    {
241
-        return $this->_success;
242
-    }
243
-
244
-
245
-    /**
246
-     * @param string $method_of_payment
247
-     */
248
-    public function set_method_of_payment($method_of_payment)
249
-    {
250
-        $this->_method_of_payment = $method_of_payment;
251
-    }
252
-
253
-
254
-    /**
255
-     * @return string
256
-     */
257
-    public function method_of_payment()
258
-    {
259
-        return $this->_method_of_payment;
260
-    }
261
-
262
-
263
-    /**
264
-     * @return float
265
-     */
266
-    public function payment_amount()
267
-    {
268
-        return $this->_payment_amount;
269
-    }
270
-
271
-
272
-    /**
273
-     * @param float $payment_amount
274
-     * @throws EE_Error
275
-     */
276
-    public function set_payment_amount($payment_amount)
277
-    {
278
-        $this->_payment_amount = (float) $payment_amount;
279
-    }
280
-
281
-
282
-    /**
283
-     * @param string $next_step_html
284
-     */
285
-    public function set_reg_step_html($next_step_html)
286
-    {
287
-        $this->_reg_step_html = $next_step_html;
288
-    }
289
-
290
-
291
-    /**
292
-     * @return string
293
-     */
294
-    public function reg_step_html()
295
-    {
296
-        return $this->_reg_step_html;
297
-    }
298
-
299
-
300
-    /**
301
-     * @param string $redirect_form
302
-     */
303
-    public function set_redirect_form($redirect_form)
304
-    {
305
-        $this->_redirect_form = $redirect_form;
306
-    }
307
-
308
-
309
-    /**
310
-     * @return string
311
-     */
312
-    public function redirect_form()
313
-    {
314
-        return ! empty($this->_redirect_form) ? $this->_redirect_form : false;
315
-    }
316
-
317
-
318
-    /**
319
-     * @param string $plz_select_method_of_payment
320
-     */
321
-    public function set_plz_select_method_of_payment($plz_select_method_of_payment)
322
-    {
323
-        $this->_plz_select_method_of_payment = $plz_select_method_of_payment;
324
-    }
325
-
326
-
327
-    /**
328
-     * @return string
329
-     */
330
-    public function plz_select_method_of_payment()
331
-    {
332
-        return $this->_plz_select_method_of_payment;
333
-    }
334
-
335
-
336
-    /**
337
-     * @param string $redirect_url
338
-     */
339
-    public function set_redirect_url($redirect_url)
340
-    {
341
-        $this->_redirect_url = $redirect_url;
342
-    }
343
-
344
-
345
-    /**
346
-     * @return string
347
-     */
348
-    public function redirect_url()
349
-    {
350
-        return $this->_redirect_url;
351
-    }
352
-
353
-
354
-    /**
355
-     * @return string
356
-     */
357
-    public function registration_time_limit()
358
-    {
359
-        return $this->_registration_time_limit;
360
-    }
361
-
362
-
363
-    /**
364
-     * @param string $registration_time_limit
365
-     */
366
-    public function set_registration_time_limit($registration_time_limit)
367
-    {
368
-        $this->_registration_time_limit = $registration_time_limit;
369
-    }
370
-
371
-
372
-    /**
373
-     * @param array $return_data
374
-     */
375
-    public function set_return_data($return_data)
376
-    {
377
-        $this->_return_data = array_merge($this->_return_data, $return_data);
378
-    }
379
-
380
-
381
-    /**
382
-     * @return array
383
-     */
384
-    public function return_data()
385
-    {
386
-        return $this->_return_data;
387
-    }
388
-
389
-
390
-    /**
391
-     * @param array $validation_rules
392
-     */
393
-    public function add_validation_rules(array $validation_rules = array())
394
-    {
395
-        if (is_array($validation_rules) && ! empty($validation_rules)) {
396
-            $this->_validation_rules = array_merge($this->_validation_rules, $validation_rules);
397
-        }
398
-    }
399
-
400
-
401
-    /**
402
-     * @return array | bool
403
-     */
404
-    public function validation_rules()
405
-    {
406
-        return ! empty($this->_validation_rules) ? $this->_validation_rules : false;
407
-    }
408
-
409
-
410
-    public function echoAndExit()
411
-    {
412
-        echo $this;
413
-        exit();
414
-    }
18
+	/**
19
+	 * @var string
20
+	 */
21
+	protected $_errors = '';
22
+
23
+	/**
24
+	 * @var string
25
+	 */
26
+	protected $_unexpected_errors = '';
27
+
28
+	/**
29
+	 * @var string
30
+	 */
31
+	protected $_attention = '';
32
+
33
+	/**
34
+	 * @var string
35
+	 */
36
+	protected $_success = '';
37
+
38
+	/**
39
+	 * @var string
40
+	 */
41
+	protected $_plz_select_method_of_payment = '';
42
+
43
+	/**
44
+	 * @var string
45
+	 */
46
+	protected $_redirect_url = '';
47
+
48
+	/**
49
+	 * @var string
50
+	 */
51
+	protected $_registration_time_limit = '';
52
+
53
+	/**
54
+	 * @var string
55
+	 */
56
+	protected $_redirect_form = '';
57
+
58
+	/**
59
+	 * @var string
60
+	 */
61
+	protected $_reg_step_html = '';
62
+
63
+	/**
64
+	 * @var string
65
+	 */
66
+	protected $_method_of_payment = '';
67
+
68
+	/**
69
+	 * @var float
70
+	 */
71
+	protected $_payment_amount;
72
+
73
+	/**
74
+	 * @var array
75
+	 */
76
+	protected $_return_data = array();
77
+
78
+
79
+	/**
80
+	 * @var array
81
+	 */
82
+	protected $_validation_rules = array();
83
+
84
+
85
+	/**
86
+	 *    class constructor
87
+	 */
88
+	public function __construct()
89
+	{
90
+	}
91
+
92
+
93
+	/**
94
+	 *    __toString
95
+	 *
96
+	 *        allows you to simply echo or print an EE_SPCO_JSON_Response object to produce a  JSON encoded string
97
+	 *
98
+	 * @access    public
99
+	 * @return    string
100
+	 */
101
+	public function __toString()
102
+	{
103
+		$JSON_response = array();
104
+		// grab notices
105
+		$notices = EE_Error::get_notices(false);
106
+		$this->set_attention(isset($notices['attention']) ? $notices['attention'] : '');
107
+		$this->set_errors(isset($notices['errors']) ? $notices['errors'] : '');
108
+		$this->set_success(isset($notices['success']) ? $notices['success'] : '');
109
+		// add notices to JSON response, but only if they exist
110
+		if ($this->attention()) {
111
+			$JSON_response['attention'] = $this->attention();
112
+		}
113
+		if ($this->errors()) {
114
+			$JSON_response['errors'] = $this->errors();
115
+		}
116
+		if ($this->unexpected_errors()) {
117
+			$JSON_response['unexpected_errors'] = $this->unexpected_errors();
118
+		}
119
+		if ($this->success()) {
120
+			$JSON_response['success'] = $this->success();
121
+		}
122
+		// but if NO notices are set... at least set the "success" as a key so that the JS knows everything worked
123
+		if (! isset($JSON_response['attention']) && ! isset($JSON_response['errors']) && ! isset($JSON_response['success'])) {
124
+			$JSON_response['success'] = null;
125
+		}
126
+		// set redirect_url, IF it exists
127
+		if ($this->redirect_url()) {
128
+			$JSON_response['redirect_url'] = $this->redirect_url();
129
+		}
130
+		// set registration_time_limit, IF it exists
131
+		if ($this->registration_time_limit()) {
132
+			$JSON_response['registration_time_limit'] = $this->registration_time_limit();
133
+		}
134
+		// set payment_amount, IF it exists
135
+		if ($this->payment_amount() !== null) {
136
+			$JSON_response['payment_amount'] = $this->payment_amount();
137
+		}
138
+		// grab generic return data
139
+		$return_data = $this->return_data();
140
+		// add billing form validation rules
141
+		if ($this->validation_rules()) {
142
+			$return_data['validation_rules'] = $this->validation_rules();
143
+		}
144
+		// set reg_step_html, IF it exists
145
+		if ($this->reg_step_html()) {
146
+			$return_data['reg_step_html'] = $this->reg_step_html();
147
+		}
148
+		// set method of payment, IF it exists
149
+		if ($this->method_of_payment()) {
150
+			$return_data['method_of_payment'] = $this->method_of_payment();
151
+		}
152
+		// set "plz_select_method_of_payment" message, IF it exists
153
+		if ($this->plz_select_method_of_payment()) {
154
+			$return_data['plz_select_method_of_payment'] = $this->plz_select_method_of_payment();
155
+		}
156
+		// set redirect_form, IF it exists
157
+		if ($this->redirect_form()) {
158
+			$return_data['redirect_form'] = $this->redirect_form();
159
+		}
160
+		// and finally, add return_data array to main JSON response array, IF it contains anything
161
+		// why did we add some of the above properties to the return data array?
162
+		// because it is easier and cleaner in the Javascript to deal with this way
163
+		if (! empty($return_data)) {
164
+			$JSON_response['return_data'] = $return_data;
165
+		}
166
+		// filter final array
167
+		$JSON_response = apply_filters('FHEE__EE_SPCO_JSON_Response___toString__JSON_response', $JSON_response);
168
+		// return encoded array
169
+		return (string) wp_json_encode($JSON_response);
170
+	}
171
+
172
+
173
+	/**
174
+	 * @param string $attention
175
+	 */
176
+	public function set_attention($attention)
177
+	{
178
+		$this->_attention = $attention;
179
+	}
180
+
181
+
182
+	/**
183
+	 * @return string
184
+	 */
185
+	public function attention()
186
+	{
187
+		return $this->_attention;
188
+	}
189
+
190
+
191
+	/**
192
+	 * @param string $errors
193
+	 */
194
+	public function set_errors($errors)
195
+	{
196
+		$this->_errors = $errors;
197
+	}
198
+
199
+
200
+	/**
201
+	 * @return string
202
+	 */
203
+	public function errors()
204
+	{
205
+		return $this->_errors;
206
+	}
207
+
208
+
209
+	/**
210
+	 * @return string
211
+	 */
212
+	public function unexpected_errors()
213
+	{
214
+		return $this->_unexpected_errors;
215
+	}
216
+
217
+
218
+	/**
219
+	 * @param string $unexpected_errors
220
+	 */
221
+	public function set_unexpected_errors($unexpected_errors)
222
+	{
223
+		$this->_unexpected_errors = $unexpected_errors;
224
+	}
225
+
226
+
227
+	/**
228
+	 * @param string $success
229
+	 */
230
+	public function set_success($success)
231
+	{
232
+		$this->_success = $success;
233
+	}
234
+
235
+
236
+	/**
237
+	 * @return string
238
+	 */
239
+	public function success()
240
+	{
241
+		return $this->_success;
242
+	}
243
+
244
+
245
+	/**
246
+	 * @param string $method_of_payment
247
+	 */
248
+	public function set_method_of_payment($method_of_payment)
249
+	{
250
+		$this->_method_of_payment = $method_of_payment;
251
+	}
252
+
253
+
254
+	/**
255
+	 * @return string
256
+	 */
257
+	public function method_of_payment()
258
+	{
259
+		return $this->_method_of_payment;
260
+	}
261
+
262
+
263
+	/**
264
+	 * @return float
265
+	 */
266
+	public function payment_amount()
267
+	{
268
+		return $this->_payment_amount;
269
+	}
270
+
271
+
272
+	/**
273
+	 * @param float $payment_amount
274
+	 * @throws EE_Error
275
+	 */
276
+	public function set_payment_amount($payment_amount)
277
+	{
278
+		$this->_payment_amount = (float) $payment_amount;
279
+	}
280
+
281
+
282
+	/**
283
+	 * @param string $next_step_html
284
+	 */
285
+	public function set_reg_step_html($next_step_html)
286
+	{
287
+		$this->_reg_step_html = $next_step_html;
288
+	}
289
+
290
+
291
+	/**
292
+	 * @return string
293
+	 */
294
+	public function reg_step_html()
295
+	{
296
+		return $this->_reg_step_html;
297
+	}
298
+
299
+
300
+	/**
301
+	 * @param string $redirect_form
302
+	 */
303
+	public function set_redirect_form($redirect_form)
304
+	{
305
+		$this->_redirect_form = $redirect_form;
306
+	}
307
+
308
+
309
+	/**
310
+	 * @return string
311
+	 */
312
+	public function redirect_form()
313
+	{
314
+		return ! empty($this->_redirect_form) ? $this->_redirect_form : false;
315
+	}
316
+
317
+
318
+	/**
319
+	 * @param string $plz_select_method_of_payment
320
+	 */
321
+	public function set_plz_select_method_of_payment($plz_select_method_of_payment)
322
+	{
323
+		$this->_plz_select_method_of_payment = $plz_select_method_of_payment;
324
+	}
325
+
326
+
327
+	/**
328
+	 * @return string
329
+	 */
330
+	public function plz_select_method_of_payment()
331
+	{
332
+		return $this->_plz_select_method_of_payment;
333
+	}
334
+
335
+
336
+	/**
337
+	 * @param string $redirect_url
338
+	 */
339
+	public function set_redirect_url($redirect_url)
340
+	{
341
+		$this->_redirect_url = $redirect_url;
342
+	}
343
+
344
+
345
+	/**
346
+	 * @return string
347
+	 */
348
+	public function redirect_url()
349
+	{
350
+		return $this->_redirect_url;
351
+	}
352
+
353
+
354
+	/**
355
+	 * @return string
356
+	 */
357
+	public function registration_time_limit()
358
+	{
359
+		return $this->_registration_time_limit;
360
+	}
361
+
362
+
363
+	/**
364
+	 * @param string $registration_time_limit
365
+	 */
366
+	public function set_registration_time_limit($registration_time_limit)
367
+	{
368
+		$this->_registration_time_limit = $registration_time_limit;
369
+	}
370
+
371
+
372
+	/**
373
+	 * @param array $return_data
374
+	 */
375
+	public function set_return_data($return_data)
376
+	{
377
+		$this->_return_data = array_merge($this->_return_data, $return_data);
378
+	}
379
+
380
+
381
+	/**
382
+	 * @return array
383
+	 */
384
+	public function return_data()
385
+	{
386
+		return $this->_return_data;
387
+	}
388
+
389
+
390
+	/**
391
+	 * @param array $validation_rules
392
+	 */
393
+	public function add_validation_rules(array $validation_rules = array())
394
+	{
395
+		if (is_array($validation_rules) && ! empty($validation_rules)) {
396
+			$this->_validation_rules = array_merge($this->_validation_rules, $validation_rules);
397
+		}
398
+	}
399
+
400
+
401
+	/**
402
+	 * @return array | bool
403
+	 */
404
+	public function validation_rules()
405
+	{
406
+		return ! empty($this->_validation_rules) ? $this->_validation_rules : false;
407
+	}
408
+
409
+
410
+	public function echoAndExit()
411
+	{
412
+		echo $this;
413
+		exit();
414
+	}
415 415
 }
Please login to merge, or discard this patch.